xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaExpr.cpp (revision 924226fba12cc9a228c73b956e1b7fa24c60b055)
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   // Half FP have to be promoted to float unless it is natively supported
777   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
778     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
779 
780   // Try to perform integral promotions if the object has a theoretically
781   // promotable type.
782   if (Ty->isIntegralOrUnscopedEnumerationType()) {
783     // C99 6.3.1.1p2:
784     //
785     //   The following may be used in an expression wherever an int or
786     //   unsigned int may be used:
787     //     - an object or expression with an integer type whose integer
788     //       conversion rank is less than or equal to the rank of int
789     //       and unsigned int.
790     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
791     //
792     //   If an int can represent all values of the original type, the
793     //   value is converted to an int; otherwise, it is converted to an
794     //   unsigned int. These are called the integer promotions. All
795     //   other types are unchanged by the integer promotions.
796 
797     QualType PTy = Context.isPromotableBitField(E);
798     if (!PTy.isNull()) {
799       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
800       return E;
801     }
802     if (Ty->isPromotableIntegerType()) {
803       QualType PT = Context.getPromotedIntegerType(Ty);
804       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
805       return E;
806     }
807   }
808   return E;
809 }
810 
811 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
812 /// do not have a prototype. Arguments that have type float or __fp16
813 /// are promoted to double. All other argument types are converted by
814 /// UsualUnaryConversions().
815 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
816   QualType Ty = E->getType();
817   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
818 
819   ExprResult Res = UsualUnaryConversions(E);
820   if (Res.isInvalid())
821     return ExprError();
822   E = Res.get();
823 
824   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
825   // promote to double.
826   // Note that default argument promotion applies only to float (and
827   // half/fp16); it does not apply to _Float16.
828   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
829   if (BTy && (BTy->getKind() == BuiltinType::Half ||
830               BTy->getKind() == BuiltinType::Float)) {
831     if (getLangOpts().OpenCL &&
832         !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
833       if (BTy->getKind() == BuiltinType::Half) {
834         E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
835       }
836     } else {
837       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
838     }
839   }
840   if (BTy &&
841       getLangOpts().getExtendIntArgs() ==
842           LangOptions::ExtendArgsKind::ExtendTo64 &&
843       Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
844       Context.getTypeSizeInChars(BTy) <
845           Context.getTypeSizeInChars(Context.LongLongTy)) {
846     E = (Ty->isUnsignedIntegerType())
847             ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
848                   .get()
849             : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
850     assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
851            "Unexpected typesize for LongLongTy");
852   }
853 
854   // C++ performs lvalue-to-rvalue conversion as a default argument
855   // promotion, even on class types, but note:
856   //   C++11 [conv.lval]p2:
857   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
858   //     operand or a subexpression thereof the value contained in the
859   //     referenced object is not accessed. Otherwise, if the glvalue
860   //     has a class type, the conversion copy-initializes a temporary
861   //     of type T from the glvalue and the result of the conversion
862   //     is a prvalue for the temporary.
863   // FIXME: add some way to gate this entire thing for correctness in
864   // potentially potentially evaluated contexts.
865   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
866     ExprResult Temp = PerformCopyInitialization(
867                        InitializedEntity::InitializeTemporary(E->getType()),
868                                                 E->getExprLoc(), E);
869     if (Temp.isInvalid())
870       return ExprError();
871     E = Temp.get();
872   }
873 
874   return E;
875 }
876 
877 /// Determine the degree of POD-ness for an expression.
878 /// Incomplete types are considered POD, since this check can be performed
879 /// when we're in an unevaluated context.
880 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
881   if (Ty->isIncompleteType()) {
882     // C++11 [expr.call]p7:
883     //   After these conversions, if the argument does not have arithmetic,
884     //   enumeration, pointer, pointer to member, or class type, the program
885     //   is ill-formed.
886     //
887     // Since we've already performed array-to-pointer and function-to-pointer
888     // decay, the only such type in C++ is cv void. This also handles
889     // initializer lists as variadic arguments.
890     if (Ty->isVoidType())
891       return VAK_Invalid;
892 
893     if (Ty->isObjCObjectType())
894       return VAK_Invalid;
895     return VAK_Valid;
896   }
897 
898   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
899     return VAK_Invalid;
900 
901   if (Ty.isCXX98PODType(Context))
902     return VAK_Valid;
903 
904   // C++11 [expr.call]p7:
905   //   Passing a potentially-evaluated argument of class type (Clause 9)
906   //   having a non-trivial copy constructor, a non-trivial move constructor,
907   //   or a non-trivial destructor, with no corresponding parameter,
908   //   is conditionally-supported with implementation-defined semantics.
909   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
910     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
911       if (!Record->hasNonTrivialCopyConstructor() &&
912           !Record->hasNonTrivialMoveConstructor() &&
913           !Record->hasNonTrivialDestructor())
914         return VAK_ValidInCXX11;
915 
916   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
917     return VAK_Valid;
918 
919   if (Ty->isObjCObjectType())
920     return VAK_Invalid;
921 
922   if (getLangOpts().MSVCCompat)
923     return VAK_MSVCUndefined;
924 
925   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
926   // permitted to reject them. We should consider doing so.
927   return VAK_Undefined;
928 }
929 
930 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
931   // Don't allow one to pass an Objective-C interface to a vararg.
932   const QualType &Ty = E->getType();
933   VarArgKind VAK = isValidVarArgType(Ty);
934 
935   // Complain about passing non-POD types through varargs.
936   switch (VAK) {
937   case VAK_ValidInCXX11:
938     DiagRuntimeBehavior(
939         E->getBeginLoc(), nullptr,
940         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
941     LLVM_FALLTHROUGH;
942   case VAK_Valid:
943     if (Ty->isRecordType()) {
944       // This is unlikely to be what the user intended. If the class has a
945       // 'c_str' member function, the user probably meant to call that.
946       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
947                           PDiag(diag::warn_pass_class_arg_to_vararg)
948                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
949     }
950     break;
951 
952   case VAK_Undefined:
953   case VAK_MSVCUndefined:
954     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
955                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
956                             << getLangOpts().CPlusPlus11 << Ty << CT);
957     break;
958 
959   case VAK_Invalid:
960     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
961       Diag(E->getBeginLoc(),
962            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
963           << Ty << CT;
964     else if (Ty->isObjCObjectType())
965       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
966                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
967                               << Ty << CT);
968     else
969       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
970           << isa<InitListExpr>(E) << Ty << CT;
971     break;
972   }
973 }
974 
975 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
976 /// will create a trap if the resulting type is not a POD type.
977 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
978                                                   FunctionDecl *FDecl) {
979   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
980     // Strip the unbridged-cast placeholder expression off, if applicable.
981     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
982         (CT == VariadicMethod ||
983          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
984       E = stripARCUnbridgedCast(E);
985 
986     // Otherwise, do normal placeholder checking.
987     } else {
988       ExprResult ExprRes = CheckPlaceholderExpr(E);
989       if (ExprRes.isInvalid())
990         return ExprError();
991       E = ExprRes.get();
992     }
993   }
994 
995   ExprResult ExprRes = DefaultArgumentPromotion(E);
996   if (ExprRes.isInvalid())
997     return ExprError();
998 
999   // Copy blocks to the heap.
1000   if (ExprRes.get()->getType()->isBlockPointerType())
1001     maybeExtendBlockObject(ExprRes);
1002 
1003   E = ExprRes.get();
1004 
1005   // Diagnostics regarding non-POD argument types are
1006   // emitted along with format string checking in Sema::CheckFunctionCall().
1007   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1008     // Turn this into a trap.
1009     CXXScopeSpec SS;
1010     SourceLocation TemplateKWLoc;
1011     UnqualifiedId Name;
1012     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1013                        E->getBeginLoc());
1014     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1015                                           /*HasTrailingLParen=*/true,
1016                                           /*IsAddressOfOperand=*/false);
1017     if (TrapFn.isInvalid())
1018       return ExprError();
1019 
1020     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1021                                     None, E->getEndLoc());
1022     if (Call.isInvalid())
1023       return ExprError();
1024 
1025     ExprResult Comma =
1026         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1027     if (Comma.isInvalid())
1028       return ExprError();
1029     return Comma.get();
1030   }
1031 
1032   if (!getLangOpts().CPlusPlus &&
1033       RequireCompleteType(E->getExprLoc(), E->getType(),
1034                           diag::err_call_incomplete_argument))
1035     return ExprError();
1036 
1037   return E;
1038 }
1039 
1040 /// Converts an integer to complex float type.  Helper function of
1041 /// UsualArithmeticConversions()
1042 ///
1043 /// \return false if the integer expression is an integer type and is
1044 /// successfully converted to the complex type.
1045 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1046                                                   ExprResult &ComplexExpr,
1047                                                   QualType IntTy,
1048                                                   QualType ComplexTy,
1049                                                   bool SkipCast) {
1050   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1051   if (SkipCast) return false;
1052   if (IntTy->isIntegerType()) {
1053     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1054     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1055     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1056                                   CK_FloatingRealToComplex);
1057   } else {
1058     assert(IntTy->isComplexIntegerType());
1059     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1060                                   CK_IntegralComplexToFloatingComplex);
1061   }
1062   return false;
1063 }
1064 
1065 /// Handle arithmetic conversion with complex types.  Helper function of
1066 /// UsualArithmeticConversions()
1067 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1068                                              ExprResult &RHS, QualType LHSType,
1069                                              QualType RHSType,
1070                                              bool IsCompAssign) {
1071   // if we have an integer operand, the result is the complex type.
1072   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1073                                              /*skipCast*/false))
1074     return LHSType;
1075   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1076                                              /*skipCast*/IsCompAssign))
1077     return RHSType;
1078 
1079   // This handles complex/complex, complex/float, or float/complex.
1080   // When both operands are complex, the shorter operand is converted to the
1081   // type of the longer, and that is the type of the result. This corresponds
1082   // to what is done when combining two real floating-point operands.
1083   // The fun begins when size promotion occur across type domains.
1084   // From H&S 6.3.4: When one operand is complex and the other is a real
1085   // floating-point type, the less precise type is converted, within it's
1086   // real or complex domain, to the precision of the other type. For example,
1087   // when combining a "long double" with a "double _Complex", the
1088   // "double _Complex" is promoted to "long double _Complex".
1089 
1090   // Compute the rank of the two types, regardless of whether they are complex.
1091   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1092 
1093   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1094   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1095   QualType LHSElementType =
1096       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1097   QualType RHSElementType =
1098       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1099 
1100   QualType ResultType = S.Context.getComplexType(LHSElementType);
1101   if (Order < 0) {
1102     // Promote the precision of the LHS if not an assignment.
1103     ResultType = S.Context.getComplexType(RHSElementType);
1104     if (!IsCompAssign) {
1105       if (LHSComplexType)
1106         LHS =
1107             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1108       else
1109         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1110     }
1111   } else if (Order > 0) {
1112     // Promote the precision of the RHS.
1113     if (RHSComplexType)
1114       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1115     else
1116       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1117   }
1118   return ResultType;
1119 }
1120 
1121 /// Handle arithmetic conversion from integer to float.  Helper function
1122 /// of UsualArithmeticConversions()
1123 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1124                                            ExprResult &IntExpr,
1125                                            QualType FloatTy, QualType IntTy,
1126                                            bool ConvertFloat, bool ConvertInt) {
1127   if (IntTy->isIntegerType()) {
1128     if (ConvertInt)
1129       // Convert intExpr to the lhs floating point type.
1130       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1131                                     CK_IntegralToFloating);
1132     return FloatTy;
1133   }
1134 
1135   // Convert both sides to the appropriate complex float.
1136   assert(IntTy->isComplexIntegerType());
1137   QualType result = S.Context.getComplexType(FloatTy);
1138 
1139   // _Complex int -> _Complex float
1140   if (ConvertInt)
1141     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1142                                   CK_IntegralComplexToFloatingComplex);
1143 
1144   // float -> _Complex float
1145   if (ConvertFloat)
1146     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1147                                     CK_FloatingRealToComplex);
1148 
1149   return result;
1150 }
1151 
1152 /// Handle arithmethic conversion with floating point types.  Helper
1153 /// function of UsualArithmeticConversions()
1154 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1155                                       ExprResult &RHS, QualType LHSType,
1156                                       QualType RHSType, bool IsCompAssign) {
1157   bool LHSFloat = LHSType->isRealFloatingType();
1158   bool RHSFloat = RHSType->isRealFloatingType();
1159 
1160   // N1169 4.1.4: If one of the operands has a floating type and the other
1161   //              operand has a fixed-point type, the fixed-point operand
1162   //              is converted to the floating type [...]
1163   if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1164     if (LHSFloat)
1165       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1166     else if (!IsCompAssign)
1167       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1168     return LHSFloat ? LHSType : RHSType;
1169   }
1170 
1171   // If we have two real floating types, convert the smaller operand
1172   // to the bigger result.
1173   if (LHSFloat && RHSFloat) {
1174     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1175     if (order > 0) {
1176       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1177       return LHSType;
1178     }
1179 
1180     assert(order < 0 && "illegal float comparison");
1181     if (!IsCompAssign)
1182       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1183     return RHSType;
1184   }
1185 
1186   if (LHSFloat) {
1187     // Half FP has to be promoted to float unless it is natively supported
1188     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1189       LHSType = S.Context.FloatTy;
1190 
1191     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1192                                       /*ConvertFloat=*/!IsCompAssign,
1193                                       /*ConvertInt=*/ true);
1194   }
1195   assert(RHSFloat);
1196   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1197                                     /*ConvertFloat=*/ true,
1198                                     /*ConvertInt=*/!IsCompAssign);
1199 }
1200 
1201 /// Diagnose attempts to convert between __float128, __ibm128 and
1202 /// long double if there is no support for such conversion.
1203 /// Helper function of UsualArithmeticConversions().
1204 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1205                                       QualType RHSType) {
1206   // No issue if either is not a floating point type.
1207   if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1208     return false;
1209 
1210   // No issue if both have the same 128-bit float semantics.
1211   auto *LHSComplex = LHSType->getAs<ComplexType>();
1212   auto *RHSComplex = RHSType->getAs<ComplexType>();
1213 
1214   QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1215   QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1216 
1217   const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1218   const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1219 
1220   if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1221        &RHSSem != &llvm::APFloat::IEEEquad()) &&
1222       (&LHSSem != &llvm::APFloat::IEEEquad() ||
1223        &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1224     return false;
1225 
1226   return true;
1227 }
1228 
1229 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1230 
1231 namespace {
1232 /// These helper callbacks are placed in an anonymous namespace to
1233 /// permit their use as function template parameters.
1234 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1235   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1236 }
1237 
1238 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1239   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1240                              CK_IntegralComplexCast);
1241 }
1242 }
1243 
1244 /// Handle integer arithmetic conversions.  Helper function of
1245 /// UsualArithmeticConversions()
1246 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1247 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1248                                         ExprResult &RHS, QualType LHSType,
1249                                         QualType RHSType, bool IsCompAssign) {
1250   // The rules for this case are in C99 6.3.1.8
1251   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1252   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1253   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1254   if (LHSSigned == RHSSigned) {
1255     // Same signedness; use the higher-ranked type
1256     if (order >= 0) {
1257       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1258       return LHSType;
1259     } else if (!IsCompAssign)
1260       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1261     return RHSType;
1262   } else if (order != (LHSSigned ? 1 : -1)) {
1263     // The unsigned type has greater than or equal rank to the
1264     // signed type, so use the unsigned type
1265     if (RHSSigned) {
1266       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1267       return LHSType;
1268     } else if (!IsCompAssign)
1269       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1270     return RHSType;
1271   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1272     // The two types are different widths; if we are here, that
1273     // means the signed type is larger than the unsigned type, so
1274     // use the signed type.
1275     if (LHSSigned) {
1276       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1277       return LHSType;
1278     } else if (!IsCompAssign)
1279       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1280     return RHSType;
1281   } else {
1282     // The signed type is higher-ranked than the unsigned type,
1283     // but isn't actually any bigger (like unsigned int and long
1284     // on most 32-bit systems).  Use the unsigned type corresponding
1285     // to the signed type.
1286     QualType result =
1287       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1288     RHS = (*doRHSCast)(S, RHS.get(), result);
1289     if (!IsCompAssign)
1290       LHS = (*doLHSCast)(S, LHS.get(), result);
1291     return result;
1292   }
1293 }
1294 
1295 /// Handle conversions with GCC complex int extension.  Helper function
1296 /// of UsualArithmeticConversions()
1297 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1298                                            ExprResult &RHS, QualType LHSType,
1299                                            QualType RHSType,
1300                                            bool IsCompAssign) {
1301   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1302   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1303 
1304   if (LHSComplexInt && RHSComplexInt) {
1305     QualType LHSEltType = LHSComplexInt->getElementType();
1306     QualType RHSEltType = RHSComplexInt->getElementType();
1307     QualType ScalarType =
1308       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1309         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1310 
1311     return S.Context.getComplexType(ScalarType);
1312   }
1313 
1314   if (LHSComplexInt) {
1315     QualType LHSEltType = LHSComplexInt->getElementType();
1316     QualType ScalarType =
1317       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1318         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1319     QualType ComplexType = S.Context.getComplexType(ScalarType);
1320     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1321                               CK_IntegralRealToComplex);
1322 
1323     return ComplexType;
1324   }
1325 
1326   assert(RHSComplexInt);
1327 
1328   QualType RHSEltType = RHSComplexInt->getElementType();
1329   QualType ScalarType =
1330     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1331       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1332   QualType ComplexType = S.Context.getComplexType(ScalarType);
1333 
1334   if (!IsCompAssign)
1335     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1336                               CK_IntegralRealToComplex);
1337   return ComplexType;
1338 }
1339 
1340 /// Return the rank of a given fixed point or integer type. The value itself
1341 /// doesn't matter, but the values must be increasing with proper increasing
1342 /// rank as described in N1169 4.1.1.
1343 static unsigned GetFixedPointRank(QualType Ty) {
1344   const auto *BTy = Ty->getAs<BuiltinType>();
1345   assert(BTy && "Expected a builtin type.");
1346 
1347   switch (BTy->getKind()) {
1348   case BuiltinType::ShortFract:
1349   case BuiltinType::UShortFract:
1350   case BuiltinType::SatShortFract:
1351   case BuiltinType::SatUShortFract:
1352     return 1;
1353   case BuiltinType::Fract:
1354   case BuiltinType::UFract:
1355   case BuiltinType::SatFract:
1356   case BuiltinType::SatUFract:
1357     return 2;
1358   case BuiltinType::LongFract:
1359   case BuiltinType::ULongFract:
1360   case BuiltinType::SatLongFract:
1361   case BuiltinType::SatULongFract:
1362     return 3;
1363   case BuiltinType::ShortAccum:
1364   case BuiltinType::UShortAccum:
1365   case BuiltinType::SatShortAccum:
1366   case BuiltinType::SatUShortAccum:
1367     return 4;
1368   case BuiltinType::Accum:
1369   case BuiltinType::UAccum:
1370   case BuiltinType::SatAccum:
1371   case BuiltinType::SatUAccum:
1372     return 5;
1373   case BuiltinType::LongAccum:
1374   case BuiltinType::ULongAccum:
1375   case BuiltinType::SatLongAccum:
1376   case BuiltinType::SatULongAccum:
1377     return 6;
1378   default:
1379     if (BTy->isInteger())
1380       return 0;
1381     llvm_unreachable("Unexpected fixed point or integer type");
1382   }
1383 }
1384 
1385 /// handleFixedPointConversion - Fixed point operations between fixed
1386 /// point types and integers or other fixed point types do not fall under
1387 /// usual arithmetic conversion since these conversions could result in loss
1388 /// of precsision (N1169 4.1.4). These operations should be calculated with
1389 /// the full precision of their result type (N1169 4.1.6.2.1).
1390 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1391                                            QualType RHSTy) {
1392   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1393          "Expected at least one of the operands to be a fixed point type");
1394   assert((LHSTy->isFixedPointOrIntegerType() ||
1395           RHSTy->isFixedPointOrIntegerType()) &&
1396          "Special fixed point arithmetic operation conversions are only "
1397          "applied to ints or other fixed point types");
1398 
1399   // If one operand has signed fixed-point type and the other operand has
1400   // unsigned fixed-point type, then the unsigned fixed-point operand is
1401   // converted to its corresponding signed fixed-point type and the resulting
1402   // type is the type of the converted operand.
1403   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1404     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1405   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1406     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1407 
1408   // The result type is the type with the highest rank, whereby a fixed-point
1409   // conversion rank is always greater than an integer conversion rank; if the
1410   // type of either of the operands is a saturating fixedpoint type, the result
1411   // type shall be the saturating fixed-point type corresponding to the type
1412   // with the highest rank; the resulting value is converted (taking into
1413   // account rounding and overflow) to the precision of the resulting type.
1414   // Same ranks between signed and unsigned types are resolved earlier, so both
1415   // types are either signed or both unsigned at this point.
1416   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1417   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1418 
1419   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1420 
1421   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1422     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1423 
1424   return ResultTy;
1425 }
1426 
1427 /// Check that the usual arithmetic conversions can be performed on this pair of
1428 /// expressions that might be of enumeration type.
1429 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1430                                            SourceLocation Loc,
1431                                            Sema::ArithConvKind ACK) {
1432   // C++2a [expr.arith.conv]p1:
1433   //   If one operand is of enumeration type and the other operand is of a
1434   //   different enumeration type or a floating-point type, this behavior is
1435   //   deprecated ([depr.arith.conv.enum]).
1436   //
1437   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1438   // Eventually we will presumably reject these cases (in C++23 onwards?).
1439   QualType L = LHS->getType(), R = RHS->getType();
1440   bool LEnum = L->isUnscopedEnumerationType(),
1441        REnum = R->isUnscopedEnumerationType();
1442   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1443   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1444       (REnum && L->isFloatingType())) {
1445     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1446                     ? diag::warn_arith_conv_enum_float_cxx20
1447                     : diag::warn_arith_conv_enum_float)
1448         << LHS->getSourceRange() << RHS->getSourceRange()
1449         << (int)ACK << LEnum << L << R;
1450   } else if (!IsCompAssign && LEnum && REnum &&
1451              !S.Context.hasSameUnqualifiedType(L, R)) {
1452     unsigned DiagID;
1453     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1454         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1455       // If either enumeration type is unnamed, it's less likely that the
1456       // user cares about this, but this situation is still deprecated in
1457       // C++2a. Use a different warning group.
1458       DiagID = S.getLangOpts().CPlusPlus20
1459                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1460                     : diag::warn_arith_conv_mixed_anon_enum_types;
1461     } else if (ACK == Sema::ACK_Conditional) {
1462       // Conditional expressions are separated out because they have
1463       // historically had a different warning flag.
1464       DiagID = S.getLangOpts().CPlusPlus20
1465                    ? diag::warn_conditional_mixed_enum_types_cxx20
1466                    : diag::warn_conditional_mixed_enum_types;
1467     } else if (ACK == Sema::ACK_Comparison) {
1468       // Comparison expressions are separated out because they have
1469       // historically had a different warning flag.
1470       DiagID = S.getLangOpts().CPlusPlus20
1471                    ? diag::warn_comparison_mixed_enum_types_cxx20
1472                    : diag::warn_comparison_mixed_enum_types;
1473     } else {
1474       DiagID = S.getLangOpts().CPlusPlus20
1475                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1476                    : diag::warn_arith_conv_mixed_enum_types;
1477     }
1478     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1479                         << (int)ACK << L << R;
1480   }
1481 }
1482 
1483 /// UsualArithmeticConversions - Performs various conversions that are common to
1484 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1485 /// routine returns the first non-arithmetic type found. The client is
1486 /// responsible for emitting appropriate error diagnostics.
1487 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1488                                           SourceLocation Loc,
1489                                           ArithConvKind ACK) {
1490   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1491 
1492   if (ACK != ACK_CompAssign) {
1493     LHS = UsualUnaryConversions(LHS.get());
1494     if (LHS.isInvalid())
1495       return QualType();
1496   }
1497 
1498   RHS = UsualUnaryConversions(RHS.get());
1499   if (RHS.isInvalid())
1500     return QualType();
1501 
1502   // For conversion purposes, we ignore any qualifiers.
1503   // For example, "const float" and "float" are equivalent.
1504   QualType LHSType =
1505     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1506   QualType RHSType =
1507     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1508 
1509   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1510   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1511     LHSType = AtomicLHS->getValueType();
1512 
1513   // If both types are identical, no conversion is needed.
1514   if (LHSType == RHSType)
1515     return LHSType;
1516 
1517   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1518   // The caller can deal with this (e.g. pointer + int).
1519   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1520     return QualType();
1521 
1522   // Apply unary and bitfield promotions to the LHS's type.
1523   QualType LHSUnpromotedType = LHSType;
1524   if (LHSType->isPromotableIntegerType())
1525     LHSType = Context.getPromotedIntegerType(LHSType);
1526   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1527   if (!LHSBitfieldPromoteTy.isNull())
1528     LHSType = LHSBitfieldPromoteTy;
1529   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1530     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1531 
1532   // If both types are identical, no conversion is needed.
1533   if (LHSType == RHSType)
1534     return LHSType;
1535 
1536   // At this point, we have two different arithmetic types.
1537 
1538   // Diagnose attempts to convert between __ibm128, __float128 and long double
1539   // where such conversions currently can't be handled.
1540   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1541     return QualType();
1542 
1543   // Handle complex types first (C99 6.3.1.8p1).
1544   if (LHSType->isComplexType() || RHSType->isComplexType())
1545     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1546                                         ACK == ACK_CompAssign);
1547 
1548   // Now handle "real" floating types (i.e. float, double, long double).
1549   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1550     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1551                                  ACK == ACK_CompAssign);
1552 
1553   // Handle GCC complex int extension.
1554   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1555     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1556                                       ACK == ACK_CompAssign);
1557 
1558   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1559     return handleFixedPointConversion(*this, LHSType, RHSType);
1560 
1561   // Finally, we have two differing integer types.
1562   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1563            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1564 }
1565 
1566 //===----------------------------------------------------------------------===//
1567 //  Semantic Analysis for various Expression Types
1568 //===----------------------------------------------------------------------===//
1569 
1570 
1571 ExprResult
1572 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1573                                 SourceLocation DefaultLoc,
1574                                 SourceLocation RParenLoc,
1575                                 Expr *ControllingExpr,
1576                                 ArrayRef<ParsedType> ArgTypes,
1577                                 ArrayRef<Expr *> ArgExprs) {
1578   unsigned NumAssocs = ArgTypes.size();
1579   assert(NumAssocs == ArgExprs.size());
1580 
1581   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1582   for (unsigned i = 0; i < NumAssocs; ++i) {
1583     if (ArgTypes[i])
1584       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1585     else
1586       Types[i] = nullptr;
1587   }
1588 
1589   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1590                                              ControllingExpr,
1591                                              llvm::makeArrayRef(Types, NumAssocs),
1592                                              ArgExprs);
1593   delete [] Types;
1594   return ER;
1595 }
1596 
1597 ExprResult
1598 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1599                                  SourceLocation DefaultLoc,
1600                                  SourceLocation RParenLoc,
1601                                  Expr *ControllingExpr,
1602                                  ArrayRef<TypeSourceInfo *> Types,
1603                                  ArrayRef<Expr *> Exprs) {
1604   unsigned NumAssocs = Types.size();
1605   assert(NumAssocs == Exprs.size());
1606 
1607   // Decay and strip qualifiers for the controlling expression type, and handle
1608   // placeholder type replacement. See committee discussion from WG14 DR423.
1609   {
1610     EnterExpressionEvaluationContext Unevaluated(
1611         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1612     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1613     if (R.isInvalid())
1614       return ExprError();
1615     ControllingExpr = R.get();
1616   }
1617 
1618   // The controlling expression is an unevaluated operand, so side effects are
1619   // likely unintended.
1620   if (!inTemplateInstantiation() &&
1621       ControllingExpr->HasSideEffects(Context, false))
1622     Diag(ControllingExpr->getExprLoc(),
1623          diag::warn_side_effects_unevaluated_context);
1624 
1625   bool TypeErrorFound = false,
1626        IsResultDependent = ControllingExpr->isTypeDependent(),
1627        ContainsUnexpandedParameterPack
1628          = ControllingExpr->containsUnexpandedParameterPack();
1629 
1630   for (unsigned i = 0; i < NumAssocs; ++i) {
1631     if (Exprs[i]->containsUnexpandedParameterPack())
1632       ContainsUnexpandedParameterPack = true;
1633 
1634     if (Types[i]) {
1635       if (Types[i]->getType()->containsUnexpandedParameterPack())
1636         ContainsUnexpandedParameterPack = true;
1637 
1638       if (Types[i]->getType()->isDependentType()) {
1639         IsResultDependent = true;
1640       } else {
1641         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1642         // complete object type other than a variably modified type."
1643         unsigned D = 0;
1644         if (Types[i]->getType()->isIncompleteType())
1645           D = diag::err_assoc_type_incomplete;
1646         else if (!Types[i]->getType()->isObjectType())
1647           D = diag::err_assoc_type_nonobject;
1648         else if (Types[i]->getType()->isVariablyModifiedType())
1649           D = diag::err_assoc_type_variably_modified;
1650 
1651         if (D != 0) {
1652           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1653             << Types[i]->getTypeLoc().getSourceRange()
1654             << Types[i]->getType();
1655           TypeErrorFound = true;
1656         }
1657 
1658         // C11 6.5.1.1p2 "No two generic associations in the same generic
1659         // selection shall specify compatible types."
1660         for (unsigned j = i+1; j < NumAssocs; ++j)
1661           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1662               Context.typesAreCompatible(Types[i]->getType(),
1663                                          Types[j]->getType())) {
1664             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1665                  diag::err_assoc_compatible_types)
1666               << Types[j]->getTypeLoc().getSourceRange()
1667               << Types[j]->getType()
1668               << Types[i]->getType();
1669             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1670                  diag::note_compat_assoc)
1671               << Types[i]->getTypeLoc().getSourceRange()
1672               << Types[i]->getType();
1673             TypeErrorFound = true;
1674           }
1675       }
1676     }
1677   }
1678   if (TypeErrorFound)
1679     return ExprError();
1680 
1681   // If we determined that the generic selection is result-dependent, don't
1682   // try to compute the result expression.
1683   if (IsResultDependent)
1684     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1685                                         Exprs, DefaultLoc, RParenLoc,
1686                                         ContainsUnexpandedParameterPack);
1687 
1688   SmallVector<unsigned, 1> CompatIndices;
1689   unsigned DefaultIndex = -1U;
1690   for (unsigned i = 0; i < NumAssocs; ++i) {
1691     if (!Types[i])
1692       DefaultIndex = i;
1693     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1694                                         Types[i]->getType()))
1695       CompatIndices.push_back(i);
1696   }
1697 
1698   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1699   // type compatible with at most one of the types named in its generic
1700   // association list."
1701   if (CompatIndices.size() > 1) {
1702     // We strip parens here because the controlling expression is typically
1703     // parenthesized in macro definitions.
1704     ControllingExpr = ControllingExpr->IgnoreParens();
1705     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1706         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1707         << (unsigned)CompatIndices.size();
1708     for (unsigned I : CompatIndices) {
1709       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1710            diag::note_compat_assoc)
1711         << Types[I]->getTypeLoc().getSourceRange()
1712         << Types[I]->getType();
1713     }
1714     return ExprError();
1715   }
1716 
1717   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1718   // its controlling expression shall have type compatible with exactly one of
1719   // the types named in its generic association list."
1720   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1721     // We strip parens here because the controlling expression is typically
1722     // parenthesized in macro definitions.
1723     ControllingExpr = ControllingExpr->IgnoreParens();
1724     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1725         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1726     return ExprError();
1727   }
1728 
1729   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1730   // type name that is compatible with the type of the controlling expression,
1731   // then the result expression of the generic selection is the expression
1732   // in that generic association. Otherwise, the result expression of the
1733   // generic selection is the expression in the default generic association."
1734   unsigned ResultIndex =
1735     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1736 
1737   return GenericSelectionExpr::Create(
1738       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1739       ContainsUnexpandedParameterPack, ResultIndex);
1740 }
1741 
1742 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1743 /// location of the token and the offset of the ud-suffix within it.
1744 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1745                                      unsigned Offset) {
1746   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1747                                         S.getLangOpts());
1748 }
1749 
1750 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1751 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1752 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1753                                                  IdentifierInfo *UDSuffix,
1754                                                  SourceLocation UDSuffixLoc,
1755                                                  ArrayRef<Expr*> Args,
1756                                                  SourceLocation LitEndLoc) {
1757   assert(Args.size() <= 2 && "too many arguments for literal operator");
1758 
1759   QualType ArgTy[2];
1760   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1761     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1762     if (ArgTy[ArgIdx]->isArrayType())
1763       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1764   }
1765 
1766   DeclarationName OpName =
1767     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1768   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1769   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1770 
1771   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1772   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1773                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1774                               /*AllowStringTemplatePack*/ false,
1775                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1776     return ExprError();
1777 
1778   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1779 }
1780 
1781 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1782 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1783 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1784 /// multiple tokens.  However, the common case is that StringToks points to one
1785 /// string.
1786 ///
1787 ExprResult
1788 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1789   assert(!StringToks.empty() && "Must have at least one string!");
1790 
1791   StringLiteralParser Literal(StringToks, PP);
1792   if (Literal.hadError)
1793     return ExprError();
1794 
1795   SmallVector<SourceLocation, 4> StringTokLocs;
1796   for (const Token &Tok : StringToks)
1797     StringTokLocs.push_back(Tok.getLocation());
1798 
1799   QualType CharTy = Context.CharTy;
1800   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1801   if (Literal.isWide()) {
1802     CharTy = Context.getWideCharType();
1803     Kind = StringLiteral::Wide;
1804   } else if (Literal.isUTF8()) {
1805     if (getLangOpts().Char8)
1806       CharTy = Context.Char8Ty;
1807     Kind = StringLiteral::UTF8;
1808   } else if (Literal.isUTF16()) {
1809     CharTy = Context.Char16Ty;
1810     Kind = StringLiteral::UTF16;
1811   } else if (Literal.isUTF32()) {
1812     CharTy = Context.Char32Ty;
1813     Kind = StringLiteral::UTF32;
1814   } else if (Literal.isPascal()) {
1815     CharTy = Context.UnsignedCharTy;
1816   }
1817 
1818   // Warn on initializing an array of char from a u8 string literal; this
1819   // becomes ill-formed in C++2a.
1820   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1821       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1822     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1823 
1824     // Create removals for all 'u8' prefixes in the string literal(s). This
1825     // ensures C++2a compatibility (but may change the program behavior when
1826     // built by non-Clang compilers for which the execution character set is
1827     // not always UTF-8).
1828     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1829     SourceLocation RemovalDiagLoc;
1830     for (const Token &Tok : StringToks) {
1831       if (Tok.getKind() == tok::utf8_string_literal) {
1832         if (RemovalDiagLoc.isInvalid())
1833           RemovalDiagLoc = Tok.getLocation();
1834         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1835             Tok.getLocation(),
1836             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1837                                            getSourceManager(), getLangOpts())));
1838       }
1839     }
1840     Diag(RemovalDiagLoc, RemovalDiag);
1841   }
1842 
1843   QualType StrTy =
1844       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1845 
1846   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1847   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1848                                              Kind, Literal.Pascal, StrTy,
1849                                              &StringTokLocs[0],
1850                                              StringTokLocs.size());
1851   if (Literal.getUDSuffix().empty())
1852     return Lit;
1853 
1854   // We're building a user-defined literal.
1855   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1856   SourceLocation UDSuffixLoc =
1857     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1858                    Literal.getUDSuffixOffset());
1859 
1860   // Make sure we're allowed user-defined literals here.
1861   if (!UDLScope)
1862     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1863 
1864   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1865   //   operator "" X (str, len)
1866   QualType SizeType = Context.getSizeType();
1867 
1868   DeclarationName OpName =
1869     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1870   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1871   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1872 
1873   QualType ArgTy[] = {
1874     Context.getArrayDecayedType(StrTy), SizeType
1875   };
1876 
1877   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1878   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1879                                 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1880                                 /*AllowStringTemplatePack*/ true,
1881                                 /*DiagnoseMissing*/ true, Lit)) {
1882 
1883   case LOLR_Cooked: {
1884     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1885     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1886                                                     StringTokLocs[0]);
1887     Expr *Args[] = { Lit, LenArg };
1888 
1889     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1890   }
1891 
1892   case LOLR_Template: {
1893     TemplateArgumentListInfo ExplicitArgs;
1894     TemplateArgument Arg(Lit);
1895     TemplateArgumentLocInfo ArgInfo(Lit);
1896     ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1897     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1898                                     &ExplicitArgs);
1899   }
1900 
1901   case LOLR_StringTemplatePack: {
1902     TemplateArgumentListInfo ExplicitArgs;
1903 
1904     unsigned CharBits = Context.getIntWidth(CharTy);
1905     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1906     llvm::APSInt Value(CharBits, CharIsUnsigned);
1907 
1908     TemplateArgument TypeArg(CharTy);
1909     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1910     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1911 
1912     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1913       Value = Lit->getCodeUnit(I);
1914       TemplateArgument Arg(Context, Value, CharTy);
1915       TemplateArgumentLocInfo ArgInfo;
1916       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1917     }
1918     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1919                                     &ExplicitArgs);
1920   }
1921   case LOLR_Raw:
1922   case LOLR_ErrorNoDiagnostic:
1923     llvm_unreachable("unexpected literal operator lookup result");
1924   case LOLR_Error:
1925     return ExprError();
1926   }
1927   llvm_unreachable("unexpected literal operator lookup result");
1928 }
1929 
1930 DeclRefExpr *
1931 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1932                        SourceLocation Loc,
1933                        const CXXScopeSpec *SS) {
1934   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1935   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1936 }
1937 
1938 DeclRefExpr *
1939 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1940                        const DeclarationNameInfo &NameInfo,
1941                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1942                        SourceLocation TemplateKWLoc,
1943                        const TemplateArgumentListInfo *TemplateArgs) {
1944   NestedNameSpecifierLoc NNS =
1945       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1946   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1947                           TemplateArgs);
1948 }
1949 
1950 // CUDA/HIP: Check whether a captured reference variable is referencing a
1951 // host variable in a device or host device lambda.
1952 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1953                                                             VarDecl *VD) {
1954   if (!S.getLangOpts().CUDA || !VD->hasInit())
1955     return false;
1956   assert(VD->getType()->isReferenceType());
1957 
1958   // Check whether the reference variable is referencing a host variable.
1959   auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1960   if (!DRE)
1961     return false;
1962   auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
1963   if (!Referee || !Referee->hasGlobalStorage() ||
1964       Referee->hasAttr<CUDADeviceAttr>())
1965     return false;
1966 
1967   // Check whether the current function is a device or host device lambda.
1968   // Check whether the reference variable is a capture by getDeclContext()
1969   // since refersToEnclosingVariableOrCapture() is not ready at this point.
1970   auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
1971   if (MD && MD->getParent()->isLambda() &&
1972       MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
1973       VD->getDeclContext() != MD)
1974     return true;
1975 
1976   return false;
1977 }
1978 
1979 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1980   // A declaration named in an unevaluated operand never constitutes an odr-use.
1981   if (isUnevaluatedContext())
1982     return NOUR_Unevaluated;
1983 
1984   // C++2a [basic.def.odr]p4:
1985   //   A variable x whose name appears as a potentially-evaluated expression e
1986   //   is odr-used by e unless [...] x is a reference that is usable in
1987   //   constant expressions.
1988   // CUDA/HIP:
1989   //   If a reference variable referencing a host variable is captured in a
1990   //   device or host device lambda, the value of the referee must be copied
1991   //   to the capture and the reference variable must be treated as odr-use
1992   //   since the value of the referee is not known at compile time and must
1993   //   be loaded from the captured.
1994   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1995     if (VD->getType()->isReferenceType() &&
1996         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1997         !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
1998         VD->isUsableInConstantExpressions(Context))
1999       return NOUR_Constant;
2000   }
2001 
2002   // All remaining non-variable cases constitute an odr-use. For variables, we
2003   // need to wait and see how the expression is used.
2004   return NOUR_None;
2005 }
2006 
2007 /// BuildDeclRefExpr - Build an expression that references a
2008 /// declaration that does not require a closure capture.
2009 DeclRefExpr *
2010 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2011                        const DeclarationNameInfo &NameInfo,
2012                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2013                        SourceLocation TemplateKWLoc,
2014                        const TemplateArgumentListInfo *TemplateArgs) {
2015   bool RefersToCapturedVariable =
2016       isa<VarDecl>(D) &&
2017       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2018 
2019   DeclRefExpr *E = DeclRefExpr::Create(
2020       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2021       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2022   MarkDeclRefReferenced(E);
2023 
2024   // C++ [except.spec]p17:
2025   //   An exception-specification is considered to be needed when:
2026   //   - in an expression, the function is the unique lookup result or
2027   //     the selected member of a set of overloaded functions.
2028   //
2029   // We delay doing this until after we've built the function reference and
2030   // marked it as used so that:
2031   //  a) if the function is defaulted, we get errors from defining it before /
2032   //     instead of errors from computing its exception specification, and
2033   //  b) if the function is a defaulted comparison, we can use the body we
2034   //     build when defining it as input to the exception specification
2035   //     computation rather than computing a new body.
2036   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2037     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2038       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2039         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2040     }
2041   }
2042 
2043   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2044       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2045       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2046     getCurFunction()->recordUseOfWeak(E);
2047 
2048   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2049   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2050     FD = IFD->getAnonField();
2051   if (FD) {
2052     UnusedPrivateFields.remove(FD);
2053     // Just in case we're building an illegal pointer-to-member.
2054     if (FD->isBitField())
2055       E->setObjectKind(OK_BitField);
2056   }
2057 
2058   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2059   // designates a bit-field.
2060   if (auto *BD = dyn_cast<BindingDecl>(D))
2061     if (auto *BE = BD->getBinding())
2062       E->setObjectKind(BE->getObjectKind());
2063 
2064   return E;
2065 }
2066 
2067 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2068 /// possibly a list of template arguments.
2069 ///
2070 /// If this produces template arguments, it is permitted to call
2071 /// DecomposeTemplateName.
2072 ///
2073 /// This actually loses a lot of source location information for
2074 /// non-standard name kinds; we should consider preserving that in
2075 /// some way.
2076 void
2077 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2078                              TemplateArgumentListInfo &Buffer,
2079                              DeclarationNameInfo &NameInfo,
2080                              const TemplateArgumentListInfo *&TemplateArgs) {
2081   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2082     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2083     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2084 
2085     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2086                                        Id.TemplateId->NumArgs);
2087     translateTemplateArguments(TemplateArgsPtr, Buffer);
2088 
2089     TemplateName TName = Id.TemplateId->Template.get();
2090     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2091     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2092     TemplateArgs = &Buffer;
2093   } else {
2094     NameInfo = GetNameFromUnqualifiedId(Id);
2095     TemplateArgs = nullptr;
2096   }
2097 }
2098 
2099 static void emitEmptyLookupTypoDiagnostic(
2100     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2101     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2102     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2103   DeclContext *Ctx =
2104       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2105   if (!TC) {
2106     // Emit a special diagnostic for failed member lookups.
2107     // FIXME: computing the declaration context might fail here (?)
2108     if (Ctx)
2109       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2110                                                  << SS.getRange();
2111     else
2112       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2113     return;
2114   }
2115 
2116   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2117   bool DroppedSpecifier =
2118       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2119   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2120                         ? diag::note_implicit_param_decl
2121                         : diag::note_previous_decl;
2122   if (!Ctx)
2123     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2124                          SemaRef.PDiag(NoteID));
2125   else
2126     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2127                                  << Typo << Ctx << DroppedSpecifier
2128                                  << SS.getRange(),
2129                          SemaRef.PDiag(NoteID));
2130 }
2131 
2132 /// Diagnose a lookup that found results in an enclosing class during error
2133 /// recovery. This usually indicates that the results were found in a dependent
2134 /// base class that could not be searched as part of a template definition.
2135 /// Always issues a diagnostic (though this may be only a warning in MS
2136 /// compatibility mode).
2137 ///
2138 /// Return \c true if the error is unrecoverable, or \c false if the caller
2139 /// should attempt to recover using these lookup results.
2140 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2141   // During a default argument instantiation the CurContext points
2142   // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2143   // function parameter list, hence add an explicit check.
2144   bool isDefaultArgument =
2145       !CodeSynthesisContexts.empty() &&
2146       CodeSynthesisContexts.back().Kind ==
2147           CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2148   CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2149   bool isInstance = CurMethod && CurMethod->isInstance() &&
2150                     R.getNamingClass() == CurMethod->getParent() &&
2151                     !isDefaultArgument;
2152 
2153   // There are two ways we can find a class-scope declaration during template
2154   // instantiation that we did not find in the template definition: if it is a
2155   // member of a dependent base class, or if it is declared after the point of
2156   // use in the same class. Distinguish these by comparing the class in which
2157   // the member was found to the naming class of the lookup.
2158   unsigned DiagID = diag::err_found_in_dependent_base;
2159   unsigned NoteID = diag::note_member_declared_at;
2160   if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2161     DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2162                                       : diag::err_found_later_in_class;
2163   } else if (getLangOpts().MSVCCompat) {
2164     DiagID = diag::ext_found_in_dependent_base;
2165     NoteID = diag::note_dependent_member_use;
2166   }
2167 
2168   if (isInstance) {
2169     // Give a code modification hint to insert 'this->'.
2170     Diag(R.getNameLoc(), DiagID)
2171         << R.getLookupName()
2172         << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2173     CheckCXXThisCapture(R.getNameLoc());
2174   } else {
2175     // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2176     // they're not shadowed).
2177     Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2178   }
2179 
2180   for (NamedDecl *D : R)
2181     Diag(D->getLocation(), NoteID);
2182 
2183   // Return true if we are inside a default argument instantiation
2184   // and the found name refers to an instance member function, otherwise
2185   // the caller will try to create an implicit member call and this is wrong
2186   // for default arguments.
2187   //
2188   // FIXME: Is this special case necessary? We could allow the caller to
2189   // diagnose this.
2190   if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2191     Diag(R.getNameLoc(), diag::err_member_call_without_object);
2192     return true;
2193   }
2194 
2195   // Tell the callee to try to recover.
2196   return false;
2197 }
2198 
2199 /// Diagnose an empty lookup.
2200 ///
2201 /// \return false if new lookup candidates were found
2202 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2203                                CorrectionCandidateCallback &CCC,
2204                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2205                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2206   DeclarationName Name = R.getLookupName();
2207 
2208   unsigned diagnostic = diag::err_undeclared_var_use;
2209   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2210   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2211       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2212       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2213     diagnostic = diag::err_undeclared_use;
2214     diagnostic_suggest = diag::err_undeclared_use_suggest;
2215   }
2216 
2217   // If the original lookup was an unqualified lookup, fake an
2218   // unqualified lookup.  This is useful when (for example) the
2219   // original lookup would not have found something because it was a
2220   // dependent name.
2221   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2222   while (DC) {
2223     if (isa<CXXRecordDecl>(DC)) {
2224       LookupQualifiedName(R, DC);
2225 
2226       if (!R.empty()) {
2227         // Don't give errors about ambiguities in this lookup.
2228         R.suppressDiagnostics();
2229 
2230         // If there's a best viable function among the results, only mention
2231         // that one in the notes.
2232         OverloadCandidateSet Candidates(R.getNameLoc(),
2233                                         OverloadCandidateSet::CSK_Normal);
2234         AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2235         OverloadCandidateSet::iterator Best;
2236         if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2237             OR_Success) {
2238           R.clear();
2239           R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2240           R.resolveKind();
2241         }
2242 
2243         return DiagnoseDependentMemberLookup(R);
2244       }
2245 
2246       R.clear();
2247     }
2248 
2249     DC = DC->getLookupParent();
2250   }
2251 
2252   // We didn't find anything, so try to correct for a typo.
2253   TypoCorrection Corrected;
2254   if (S && Out) {
2255     SourceLocation TypoLoc = R.getNameLoc();
2256     assert(!ExplicitTemplateArgs &&
2257            "Diagnosing an empty lookup with explicit template args!");
2258     *Out = CorrectTypoDelayed(
2259         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2260         [=](const TypoCorrection &TC) {
2261           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2262                                         diagnostic, diagnostic_suggest);
2263         },
2264         nullptr, CTK_ErrorRecovery);
2265     if (*Out)
2266       return true;
2267   } else if (S &&
2268              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2269                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2270     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2271     bool DroppedSpecifier =
2272         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2273     R.setLookupName(Corrected.getCorrection());
2274 
2275     bool AcceptableWithRecovery = false;
2276     bool AcceptableWithoutRecovery = false;
2277     NamedDecl *ND = Corrected.getFoundDecl();
2278     if (ND) {
2279       if (Corrected.isOverloaded()) {
2280         OverloadCandidateSet OCS(R.getNameLoc(),
2281                                  OverloadCandidateSet::CSK_Normal);
2282         OverloadCandidateSet::iterator Best;
2283         for (NamedDecl *CD : Corrected) {
2284           if (FunctionTemplateDecl *FTD =
2285                    dyn_cast<FunctionTemplateDecl>(CD))
2286             AddTemplateOverloadCandidate(
2287                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2288                 Args, OCS);
2289           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2290             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2291               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2292                                    Args, OCS);
2293         }
2294         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2295         case OR_Success:
2296           ND = Best->FoundDecl;
2297           Corrected.setCorrectionDecl(ND);
2298           break;
2299         default:
2300           // FIXME: Arbitrarily pick the first declaration for the note.
2301           Corrected.setCorrectionDecl(ND);
2302           break;
2303         }
2304       }
2305       R.addDecl(ND);
2306       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2307         CXXRecordDecl *Record = nullptr;
2308         if (Corrected.getCorrectionSpecifier()) {
2309           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2310           Record = Ty->getAsCXXRecordDecl();
2311         }
2312         if (!Record)
2313           Record = cast<CXXRecordDecl>(
2314               ND->getDeclContext()->getRedeclContext());
2315         R.setNamingClass(Record);
2316       }
2317 
2318       auto *UnderlyingND = ND->getUnderlyingDecl();
2319       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2320                                isa<FunctionTemplateDecl>(UnderlyingND);
2321       // FIXME: If we ended up with a typo for a type name or
2322       // Objective-C class name, we're in trouble because the parser
2323       // is in the wrong place to recover. Suggest the typo
2324       // correction, but don't make it a fix-it since we're not going
2325       // to recover well anyway.
2326       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2327                                   getAsTypeTemplateDecl(UnderlyingND) ||
2328                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2329     } else {
2330       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2331       // because we aren't able to recover.
2332       AcceptableWithoutRecovery = true;
2333     }
2334 
2335     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2336       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2337                             ? diag::note_implicit_param_decl
2338                             : diag::note_previous_decl;
2339       if (SS.isEmpty())
2340         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2341                      PDiag(NoteID), AcceptableWithRecovery);
2342       else
2343         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2344                                   << Name << computeDeclContext(SS, false)
2345                                   << DroppedSpecifier << SS.getRange(),
2346                      PDiag(NoteID), AcceptableWithRecovery);
2347 
2348       // Tell the callee whether to try to recover.
2349       return !AcceptableWithRecovery;
2350     }
2351   }
2352   R.clear();
2353 
2354   // Emit a special diagnostic for failed member lookups.
2355   // FIXME: computing the declaration context might fail here (?)
2356   if (!SS.isEmpty()) {
2357     Diag(R.getNameLoc(), diag::err_no_member)
2358       << Name << computeDeclContext(SS, false)
2359       << SS.getRange();
2360     return true;
2361   }
2362 
2363   // Give up, we can't recover.
2364   Diag(R.getNameLoc(), diagnostic) << Name;
2365   return true;
2366 }
2367 
2368 /// In Microsoft mode, if we are inside a template class whose parent class has
2369 /// dependent base classes, and we can't resolve an unqualified identifier, then
2370 /// assume the identifier is a member of a dependent base class.  We can only
2371 /// recover successfully in static methods, instance methods, and other contexts
2372 /// where 'this' is available.  This doesn't precisely match MSVC's
2373 /// instantiation model, but it's close enough.
2374 static Expr *
2375 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2376                                DeclarationNameInfo &NameInfo,
2377                                SourceLocation TemplateKWLoc,
2378                                const TemplateArgumentListInfo *TemplateArgs) {
2379   // Only try to recover from lookup into dependent bases in static methods or
2380   // contexts where 'this' is available.
2381   QualType ThisType = S.getCurrentThisType();
2382   const CXXRecordDecl *RD = nullptr;
2383   if (!ThisType.isNull())
2384     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2385   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2386     RD = MD->getParent();
2387   if (!RD || !RD->hasAnyDependentBases())
2388     return nullptr;
2389 
2390   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2391   // is available, suggest inserting 'this->' as a fixit.
2392   SourceLocation Loc = NameInfo.getLoc();
2393   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2394   DB << NameInfo.getName() << RD;
2395 
2396   if (!ThisType.isNull()) {
2397     DB << FixItHint::CreateInsertion(Loc, "this->");
2398     return CXXDependentScopeMemberExpr::Create(
2399         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2400         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2401         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2402   }
2403 
2404   // Synthesize a fake NNS that points to the derived class.  This will
2405   // perform name lookup during template instantiation.
2406   CXXScopeSpec SS;
2407   auto *NNS =
2408       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2409   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2410   return DependentScopeDeclRefExpr::Create(
2411       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2412       TemplateArgs);
2413 }
2414 
2415 ExprResult
2416 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2417                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2418                         bool HasTrailingLParen, bool IsAddressOfOperand,
2419                         CorrectionCandidateCallback *CCC,
2420                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2421   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2422          "cannot be direct & operand and have a trailing lparen");
2423   if (SS.isInvalid())
2424     return ExprError();
2425 
2426   TemplateArgumentListInfo TemplateArgsBuffer;
2427 
2428   // Decompose the UnqualifiedId into the following data.
2429   DeclarationNameInfo NameInfo;
2430   const TemplateArgumentListInfo *TemplateArgs;
2431   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2432 
2433   DeclarationName Name = NameInfo.getName();
2434   IdentifierInfo *II = Name.getAsIdentifierInfo();
2435   SourceLocation NameLoc = NameInfo.getLoc();
2436 
2437   if (II && II->isEditorPlaceholder()) {
2438     // FIXME: When typed placeholders are supported we can create a typed
2439     // placeholder expression node.
2440     return ExprError();
2441   }
2442 
2443   // C++ [temp.dep.expr]p3:
2444   //   An id-expression is type-dependent if it contains:
2445   //     -- an identifier that was declared with a dependent type,
2446   //        (note: handled after lookup)
2447   //     -- a template-id that is dependent,
2448   //        (note: handled in BuildTemplateIdExpr)
2449   //     -- a conversion-function-id that specifies a dependent type,
2450   //     -- a nested-name-specifier that contains a class-name that
2451   //        names a dependent type.
2452   // Determine whether this is a member of an unknown specialization;
2453   // we need to handle these differently.
2454   bool DependentID = false;
2455   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2456       Name.getCXXNameType()->isDependentType()) {
2457     DependentID = true;
2458   } else if (SS.isSet()) {
2459     if (DeclContext *DC = computeDeclContext(SS, false)) {
2460       if (RequireCompleteDeclContext(SS, DC))
2461         return ExprError();
2462     } else {
2463       DependentID = true;
2464     }
2465   }
2466 
2467   if (DependentID)
2468     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2469                                       IsAddressOfOperand, TemplateArgs);
2470 
2471   // Perform the required lookup.
2472   LookupResult R(*this, NameInfo,
2473                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2474                      ? LookupObjCImplicitSelfParam
2475                      : LookupOrdinaryName);
2476   if (TemplateKWLoc.isValid() || TemplateArgs) {
2477     // Lookup the template name again to correctly establish the context in
2478     // which it was found. This is really unfortunate as we already did the
2479     // lookup to determine that it was a template name in the first place. If
2480     // this becomes a performance hit, we can work harder to preserve those
2481     // results until we get here but it's likely not worth it.
2482     bool MemberOfUnknownSpecialization;
2483     AssumedTemplateKind AssumedTemplate;
2484     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2485                            MemberOfUnknownSpecialization, TemplateKWLoc,
2486                            &AssumedTemplate))
2487       return ExprError();
2488 
2489     if (MemberOfUnknownSpecialization ||
2490         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2491       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2492                                         IsAddressOfOperand, TemplateArgs);
2493   } else {
2494     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2495     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2496 
2497     // If the result might be in a dependent base class, this is a dependent
2498     // id-expression.
2499     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2500       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2501                                         IsAddressOfOperand, TemplateArgs);
2502 
2503     // If this reference is in an Objective-C method, then we need to do
2504     // some special Objective-C lookup, too.
2505     if (IvarLookupFollowUp) {
2506       ExprResult E(LookupInObjCMethod(R, S, II, true));
2507       if (E.isInvalid())
2508         return ExprError();
2509 
2510       if (Expr *Ex = E.getAs<Expr>())
2511         return Ex;
2512     }
2513   }
2514 
2515   if (R.isAmbiguous())
2516     return ExprError();
2517 
2518   // This could be an implicitly declared function reference (legal in C90,
2519   // extension in C99, forbidden in C++).
2520   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2521     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2522     if (D) R.addDecl(D);
2523   }
2524 
2525   // Determine whether this name might be a candidate for
2526   // argument-dependent lookup.
2527   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2528 
2529   if (R.empty() && !ADL) {
2530     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2531       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2532                                                    TemplateKWLoc, TemplateArgs))
2533         return E;
2534     }
2535 
2536     // Don't diagnose an empty lookup for inline assembly.
2537     if (IsInlineAsmIdentifier)
2538       return ExprError();
2539 
2540     // If this name wasn't predeclared and if this is not a function
2541     // call, diagnose the problem.
2542     TypoExpr *TE = nullptr;
2543     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2544                                                        : nullptr);
2545     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2546     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2547            "Typo correction callback misconfigured");
2548     if (CCC) {
2549       // Make sure the callback knows what the typo being diagnosed is.
2550       CCC->setTypoName(II);
2551       if (SS.isValid())
2552         CCC->setTypoNNS(SS.getScopeRep());
2553     }
2554     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2555     // a template name, but we happen to have always already looked up the name
2556     // before we get here if it must be a template name.
2557     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2558                             None, &TE)) {
2559       if (TE && KeywordReplacement) {
2560         auto &State = getTypoExprState(TE);
2561         auto BestTC = State.Consumer->getNextCorrection();
2562         if (BestTC.isKeyword()) {
2563           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2564           if (State.DiagHandler)
2565             State.DiagHandler(BestTC);
2566           KeywordReplacement->startToken();
2567           KeywordReplacement->setKind(II->getTokenID());
2568           KeywordReplacement->setIdentifierInfo(II);
2569           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2570           // Clean up the state associated with the TypoExpr, since it has
2571           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2572           clearDelayedTypo(TE);
2573           // Signal that a correction to a keyword was performed by returning a
2574           // valid-but-null ExprResult.
2575           return (Expr*)nullptr;
2576         }
2577         State.Consumer->resetCorrectionStream();
2578       }
2579       return TE ? TE : ExprError();
2580     }
2581 
2582     assert(!R.empty() &&
2583            "DiagnoseEmptyLookup returned false but added no results");
2584 
2585     // If we found an Objective-C instance variable, let
2586     // LookupInObjCMethod build the appropriate expression to
2587     // reference the ivar.
2588     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2589       R.clear();
2590       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2591       // In a hopelessly buggy code, Objective-C instance variable
2592       // lookup fails and no expression will be built to reference it.
2593       if (!E.isInvalid() && !E.get())
2594         return ExprError();
2595       return E;
2596     }
2597   }
2598 
2599   // This is guaranteed from this point on.
2600   assert(!R.empty() || ADL);
2601 
2602   // Check whether this might be a C++ implicit instance member access.
2603   // C++ [class.mfct.non-static]p3:
2604   //   When an id-expression that is not part of a class member access
2605   //   syntax and not used to form a pointer to member is used in the
2606   //   body of a non-static member function of class X, if name lookup
2607   //   resolves the name in the id-expression to a non-static non-type
2608   //   member of some class C, the id-expression is transformed into a
2609   //   class member access expression using (*this) as the
2610   //   postfix-expression to the left of the . operator.
2611   //
2612   // But we don't actually need to do this for '&' operands if R
2613   // resolved to a function or overloaded function set, because the
2614   // expression is ill-formed if it actually works out to be a
2615   // non-static member function:
2616   //
2617   // C++ [expr.ref]p4:
2618   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2619   //   [t]he expression can be used only as the left-hand operand of a
2620   //   member function call.
2621   //
2622   // There are other safeguards against such uses, but it's important
2623   // to get this right here so that we don't end up making a
2624   // spuriously dependent expression if we're inside a dependent
2625   // instance method.
2626   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2627     bool MightBeImplicitMember;
2628     if (!IsAddressOfOperand)
2629       MightBeImplicitMember = true;
2630     else if (!SS.isEmpty())
2631       MightBeImplicitMember = false;
2632     else if (R.isOverloadedResult())
2633       MightBeImplicitMember = false;
2634     else if (R.isUnresolvableResult())
2635       MightBeImplicitMember = true;
2636     else
2637       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2638                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2639                               isa<MSPropertyDecl>(R.getFoundDecl());
2640 
2641     if (MightBeImplicitMember)
2642       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2643                                              R, TemplateArgs, S);
2644   }
2645 
2646   if (TemplateArgs || TemplateKWLoc.isValid()) {
2647 
2648     // In C++1y, if this is a variable template id, then check it
2649     // in BuildTemplateIdExpr().
2650     // The single lookup result must be a variable template declaration.
2651     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2652         Id.TemplateId->Kind == TNK_Var_template) {
2653       assert(R.getAsSingle<VarTemplateDecl>() &&
2654              "There should only be one declaration found.");
2655     }
2656 
2657     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2658   }
2659 
2660   return BuildDeclarationNameExpr(SS, R, ADL);
2661 }
2662 
2663 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2664 /// declaration name, generally during template instantiation.
2665 /// There's a large number of things which don't need to be done along
2666 /// this path.
2667 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2668     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2669     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2670   DeclContext *DC = computeDeclContext(SS, false);
2671   if (!DC)
2672     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2673                                      NameInfo, /*TemplateArgs=*/nullptr);
2674 
2675   if (RequireCompleteDeclContext(SS, DC))
2676     return ExprError();
2677 
2678   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2679   LookupQualifiedName(R, DC);
2680 
2681   if (R.isAmbiguous())
2682     return ExprError();
2683 
2684   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2685     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2686                                      NameInfo, /*TemplateArgs=*/nullptr);
2687 
2688   if (R.empty()) {
2689     // Don't diagnose problems with invalid record decl, the secondary no_member
2690     // diagnostic during template instantiation is likely bogus, e.g. if a class
2691     // is invalid because it's derived from an invalid base class, then missing
2692     // members were likely supposed to be inherited.
2693     if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2694       if (CD->isInvalidDecl())
2695         return ExprError();
2696     Diag(NameInfo.getLoc(), diag::err_no_member)
2697       << NameInfo.getName() << DC << SS.getRange();
2698     return ExprError();
2699   }
2700 
2701   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2702     // Diagnose a missing typename if this resolved unambiguously to a type in
2703     // a dependent context.  If we can recover with a type, downgrade this to
2704     // a warning in Microsoft compatibility mode.
2705     unsigned DiagID = diag::err_typename_missing;
2706     if (RecoveryTSI && getLangOpts().MSVCCompat)
2707       DiagID = diag::ext_typename_missing;
2708     SourceLocation Loc = SS.getBeginLoc();
2709     auto D = Diag(Loc, DiagID);
2710     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2711       << SourceRange(Loc, NameInfo.getEndLoc());
2712 
2713     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2714     // context.
2715     if (!RecoveryTSI)
2716       return ExprError();
2717 
2718     // Only issue the fixit if we're prepared to recover.
2719     D << FixItHint::CreateInsertion(Loc, "typename ");
2720 
2721     // Recover by pretending this was an elaborated type.
2722     QualType Ty = Context.getTypeDeclType(TD);
2723     TypeLocBuilder TLB;
2724     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2725 
2726     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2727     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2728     QTL.setElaboratedKeywordLoc(SourceLocation());
2729     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2730 
2731     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2732 
2733     return ExprEmpty();
2734   }
2735 
2736   // Defend against this resolving to an implicit member access. We usually
2737   // won't get here if this might be a legitimate a class member (we end up in
2738   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2739   // a pointer-to-member or in an unevaluated context in C++11.
2740   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2741     return BuildPossibleImplicitMemberExpr(SS,
2742                                            /*TemplateKWLoc=*/SourceLocation(),
2743                                            R, /*TemplateArgs=*/nullptr, S);
2744 
2745   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2746 }
2747 
2748 /// The parser has read a name in, and Sema has detected that we're currently
2749 /// inside an ObjC method. Perform some additional checks and determine if we
2750 /// should form a reference to an ivar.
2751 ///
2752 /// Ideally, most of this would be done by lookup, but there's
2753 /// actually quite a lot of extra work involved.
2754 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2755                                         IdentifierInfo *II) {
2756   SourceLocation Loc = Lookup.getNameLoc();
2757   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2758 
2759   // Check for error condition which is already reported.
2760   if (!CurMethod)
2761     return DeclResult(true);
2762 
2763   // There are two cases to handle here.  1) scoped lookup could have failed,
2764   // in which case we should look for an ivar.  2) scoped lookup could have
2765   // found a decl, but that decl is outside the current instance method (i.e.
2766   // a global variable).  In these two cases, we do a lookup for an ivar with
2767   // this name, if the lookup sucedes, we replace it our current decl.
2768 
2769   // If we're in a class method, we don't normally want to look for
2770   // ivars.  But if we don't find anything else, and there's an
2771   // ivar, that's an error.
2772   bool IsClassMethod = CurMethod->isClassMethod();
2773 
2774   bool LookForIvars;
2775   if (Lookup.empty())
2776     LookForIvars = true;
2777   else if (IsClassMethod)
2778     LookForIvars = false;
2779   else
2780     LookForIvars = (Lookup.isSingleResult() &&
2781                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2782   ObjCInterfaceDecl *IFace = nullptr;
2783   if (LookForIvars) {
2784     IFace = CurMethod->getClassInterface();
2785     ObjCInterfaceDecl *ClassDeclared;
2786     ObjCIvarDecl *IV = nullptr;
2787     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2788       // Diagnose using an ivar in a class method.
2789       if (IsClassMethod) {
2790         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2791         return DeclResult(true);
2792       }
2793 
2794       // Diagnose the use of an ivar outside of the declaring class.
2795       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2796           !declaresSameEntity(ClassDeclared, IFace) &&
2797           !getLangOpts().DebuggerSupport)
2798         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2799 
2800       // Success.
2801       return IV;
2802     }
2803   } else if (CurMethod->isInstanceMethod()) {
2804     // We should warn if a local variable hides an ivar.
2805     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2806       ObjCInterfaceDecl *ClassDeclared;
2807       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2808         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2809             declaresSameEntity(IFace, ClassDeclared))
2810           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2811       }
2812     }
2813   } else if (Lookup.isSingleResult() &&
2814              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2815     // If accessing a stand-alone ivar in a class method, this is an error.
2816     if (const ObjCIvarDecl *IV =
2817             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2818       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2819       return DeclResult(true);
2820     }
2821   }
2822 
2823   // Didn't encounter an error, didn't find an ivar.
2824   return DeclResult(false);
2825 }
2826 
2827 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2828                                   ObjCIvarDecl *IV) {
2829   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2830   assert(CurMethod && CurMethod->isInstanceMethod() &&
2831          "should not reference ivar from this context");
2832 
2833   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2834   assert(IFace && "should not reference ivar from this context");
2835 
2836   // If we're referencing an invalid decl, just return this as a silent
2837   // error node.  The error diagnostic was already emitted on the decl.
2838   if (IV->isInvalidDecl())
2839     return ExprError();
2840 
2841   // Check if referencing a field with __attribute__((deprecated)).
2842   if (DiagnoseUseOfDecl(IV, Loc))
2843     return ExprError();
2844 
2845   // FIXME: This should use a new expr for a direct reference, don't
2846   // turn this into Self->ivar, just return a BareIVarExpr or something.
2847   IdentifierInfo &II = Context.Idents.get("self");
2848   UnqualifiedId SelfName;
2849   SelfName.setImplicitSelfParam(&II);
2850   CXXScopeSpec SelfScopeSpec;
2851   SourceLocation TemplateKWLoc;
2852   ExprResult SelfExpr =
2853       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2854                         /*HasTrailingLParen=*/false,
2855                         /*IsAddressOfOperand=*/false);
2856   if (SelfExpr.isInvalid())
2857     return ExprError();
2858 
2859   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2860   if (SelfExpr.isInvalid())
2861     return ExprError();
2862 
2863   MarkAnyDeclReferenced(Loc, IV, true);
2864 
2865   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2866   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2867       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2868     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2869 
2870   ObjCIvarRefExpr *Result = new (Context)
2871       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2872                       IV->getLocation(), SelfExpr.get(), true, true);
2873 
2874   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2875     if (!isUnevaluatedContext() &&
2876         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2877       getCurFunction()->recordUseOfWeak(Result);
2878   }
2879   if (getLangOpts().ObjCAutoRefCount)
2880     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2881       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2882 
2883   return Result;
2884 }
2885 
2886 /// The parser has read a name in, and Sema has detected that we're currently
2887 /// inside an ObjC method. Perform some additional checks and determine if we
2888 /// should form a reference to an ivar. If so, build an expression referencing
2889 /// that ivar.
2890 ExprResult
2891 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2892                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2893   // FIXME: Integrate this lookup step into LookupParsedName.
2894   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2895   if (Ivar.isInvalid())
2896     return ExprError();
2897   if (Ivar.isUsable())
2898     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2899                             cast<ObjCIvarDecl>(Ivar.get()));
2900 
2901   if (Lookup.empty() && II && AllowBuiltinCreation)
2902     LookupBuiltin(Lookup);
2903 
2904   // Sentinel value saying that we didn't do anything special.
2905   return ExprResult(false);
2906 }
2907 
2908 /// Cast a base object to a member's actual type.
2909 ///
2910 /// There are two relevant checks:
2911 ///
2912 /// C++ [class.access.base]p7:
2913 ///
2914 ///   If a class member access operator [...] is used to access a non-static
2915 ///   data member or non-static member function, the reference is ill-formed if
2916 ///   the left operand [...] cannot be implicitly converted to a pointer to the
2917 ///   naming class of the right operand.
2918 ///
2919 /// C++ [expr.ref]p7:
2920 ///
2921 ///   If E2 is a non-static data member or a non-static member function, the
2922 ///   program is ill-formed if the class of which E2 is directly a member is an
2923 ///   ambiguous base (11.8) of the naming class (11.9.3) of E2.
2924 ///
2925 /// Note that the latter check does not consider access; the access of the
2926 /// "real" base class is checked as appropriate when checking the access of the
2927 /// member name.
2928 ExprResult
2929 Sema::PerformObjectMemberConversion(Expr *From,
2930                                     NestedNameSpecifier *Qualifier,
2931                                     NamedDecl *FoundDecl,
2932                                     NamedDecl *Member) {
2933   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2934   if (!RD)
2935     return From;
2936 
2937   QualType DestRecordType;
2938   QualType DestType;
2939   QualType FromRecordType;
2940   QualType FromType = From->getType();
2941   bool PointerConversions = false;
2942   if (isa<FieldDecl>(Member)) {
2943     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2944     auto FromPtrType = FromType->getAs<PointerType>();
2945     DestRecordType = Context.getAddrSpaceQualType(
2946         DestRecordType, FromPtrType
2947                             ? FromType->getPointeeType().getAddressSpace()
2948                             : FromType.getAddressSpace());
2949 
2950     if (FromPtrType) {
2951       DestType = Context.getPointerType(DestRecordType);
2952       FromRecordType = FromPtrType->getPointeeType();
2953       PointerConversions = true;
2954     } else {
2955       DestType = DestRecordType;
2956       FromRecordType = FromType;
2957     }
2958   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2959     if (Method->isStatic())
2960       return From;
2961 
2962     DestType = Method->getThisType();
2963     DestRecordType = DestType->getPointeeType();
2964 
2965     if (FromType->getAs<PointerType>()) {
2966       FromRecordType = FromType->getPointeeType();
2967       PointerConversions = true;
2968     } else {
2969       FromRecordType = FromType;
2970       DestType = DestRecordType;
2971     }
2972 
2973     LangAS FromAS = FromRecordType.getAddressSpace();
2974     LangAS DestAS = DestRecordType.getAddressSpace();
2975     if (FromAS != DestAS) {
2976       QualType FromRecordTypeWithoutAS =
2977           Context.removeAddrSpaceQualType(FromRecordType);
2978       QualType FromTypeWithDestAS =
2979           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2980       if (PointerConversions)
2981         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2982       From = ImpCastExprToType(From, FromTypeWithDestAS,
2983                                CK_AddressSpaceConversion, From->getValueKind())
2984                  .get();
2985     }
2986   } else {
2987     // No conversion necessary.
2988     return From;
2989   }
2990 
2991   if (DestType->isDependentType() || FromType->isDependentType())
2992     return From;
2993 
2994   // If the unqualified types are the same, no conversion is necessary.
2995   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2996     return From;
2997 
2998   SourceRange FromRange = From->getSourceRange();
2999   SourceLocation FromLoc = FromRange.getBegin();
3000 
3001   ExprValueKind VK = From->getValueKind();
3002 
3003   // C++ [class.member.lookup]p8:
3004   //   [...] Ambiguities can often be resolved by qualifying a name with its
3005   //   class name.
3006   //
3007   // If the member was a qualified name and the qualified referred to a
3008   // specific base subobject type, we'll cast to that intermediate type
3009   // first and then to the object in which the member is declared. That allows
3010   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3011   //
3012   //   class Base { public: int x; };
3013   //   class Derived1 : public Base { };
3014   //   class Derived2 : public Base { };
3015   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
3016   //
3017   //   void VeryDerived::f() {
3018   //     x = 17; // error: ambiguous base subobjects
3019   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
3020   //   }
3021   if (Qualifier && Qualifier->getAsType()) {
3022     QualType QType = QualType(Qualifier->getAsType(), 0);
3023     assert(QType->isRecordType() && "lookup done with non-record type");
3024 
3025     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
3026 
3027     // In C++98, the qualifier type doesn't actually have to be a base
3028     // type of the object type, in which case we just ignore it.
3029     // Otherwise build the appropriate casts.
3030     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3031       CXXCastPath BasePath;
3032       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3033                                        FromLoc, FromRange, &BasePath))
3034         return ExprError();
3035 
3036       if (PointerConversions)
3037         QType = Context.getPointerType(QType);
3038       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3039                                VK, &BasePath).get();
3040 
3041       FromType = QType;
3042       FromRecordType = QRecordType;
3043 
3044       // If the qualifier type was the same as the destination type,
3045       // we're done.
3046       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3047         return From;
3048     }
3049   }
3050 
3051   CXXCastPath BasePath;
3052   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3053                                    FromLoc, FromRange, &BasePath,
3054                                    /*IgnoreAccess=*/true))
3055     return ExprError();
3056 
3057   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3058                            VK, &BasePath);
3059 }
3060 
3061 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3062                                       const LookupResult &R,
3063                                       bool HasTrailingLParen) {
3064   // Only when used directly as the postfix-expression of a call.
3065   if (!HasTrailingLParen)
3066     return false;
3067 
3068   // Never if a scope specifier was provided.
3069   if (SS.isSet())
3070     return false;
3071 
3072   // Only in C++ or ObjC++.
3073   if (!getLangOpts().CPlusPlus)
3074     return false;
3075 
3076   // Turn off ADL when we find certain kinds of declarations during
3077   // normal lookup:
3078   for (NamedDecl *D : R) {
3079     // C++0x [basic.lookup.argdep]p3:
3080     //     -- a declaration of a class member
3081     // Since using decls preserve this property, we check this on the
3082     // original decl.
3083     if (D->isCXXClassMember())
3084       return false;
3085 
3086     // C++0x [basic.lookup.argdep]p3:
3087     //     -- a block-scope function declaration that is not a
3088     //        using-declaration
3089     // NOTE: we also trigger this for function templates (in fact, we
3090     // don't check the decl type at all, since all other decl types
3091     // turn off ADL anyway).
3092     if (isa<UsingShadowDecl>(D))
3093       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3094     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3095       return false;
3096 
3097     // C++0x [basic.lookup.argdep]p3:
3098     //     -- a declaration that is neither a function or a function
3099     //        template
3100     // And also for builtin functions.
3101     if (isa<FunctionDecl>(D)) {
3102       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3103 
3104       // But also builtin functions.
3105       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3106         return false;
3107     } else if (!isa<FunctionTemplateDecl>(D))
3108       return false;
3109   }
3110 
3111   return true;
3112 }
3113 
3114 
3115 /// Diagnoses obvious problems with the use of the given declaration
3116 /// as an expression.  This is only actually called for lookups that
3117 /// were not overloaded, and it doesn't promise that the declaration
3118 /// will in fact be used.
3119 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3120   if (D->isInvalidDecl())
3121     return true;
3122 
3123   if (isa<TypedefNameDecl>(D)) {
3124     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3125     return true;
3126   }
3127 
3128   if (isa<ObjCInterfaceDecl>(D)) {
3129     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3130     return true;
3131   }
3132 
3133   if (isa<NamespaceDecl>(D)) {
3134     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3135     return true;
3136   }
3137 
3138   return false;
3139 }
3140 
3141 // Certain multiversion types should be treated as overloaded even when there is
3142 // only one result.
3143 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3144   assert(R.isSingleResult() && "Expected only a single result");
3145   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3146   return FD &&
3147          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3148 }
3149 
3150 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3151                                           LookupResult &R, bool NeedsADL,
3152                                           bool AcceptInvalidDecl) {
3153   // If this is a single, fully-resolved result and we don't need ADL,
3154   // just build an ordinary singleton decl ref.
3155   if (!NeedsADL && R.isSingleResult() &&
3156       !R.getAsSingle<FunctionTemplateDecl>() &&
3157       !ShouldLookupResultBeMultiVersionOverload(R))
3158     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3159                                     R.getRepresentativeDecl(), nullptr,
3160                                     AcceptInvalidDecl);
3161 
3162   // We only need to check the declaration if there's exactly one
3163   // result, because in the overloaded case the results can only be
3164   // functions and function templates.
3165   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3166       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3167     return ExprError();
3168 
3169   // Otherwise, just build an unresolved lookup expression.  Suppress
3170   // any lookup-related diagnostics; we'll hash these out later, when
3171   // we've picked a target.
3172   R.suppressDiagnostics();
3173 
3174   UnresolvedLookupExpr *ULE
3175     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3176                                    SS.getWithLocInContext(Context),
3177                                    R.getLookupNameInfo(),
3178                                    NeedsADL, R.isOverloadedResult(),
3179                                    R.begin(), R.end());
3180 
3181   return ULE;
3182 }
3183 
3184 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3185                                                ValueDecl *var);
3186 
3187 /// Complete semantic analysis for a reference to the given declaration.
3188 ExprResult Sema::BuildDeclarationNameExpr(
3189     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3190     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3191     bool AcceptInvalidDecl) {
3192   assert(D && "Cannot refer to a NULL declaration");
3193   assert(!isa<FunctionTemplateDecl>(D) &&
3194          "Cannot refer unambiguously to a function template");
3195 
3196   SourceLocation Loc = NameInfo.getLoc();
3197   if (CheckDeclInExpr(*this, Loc, D))
3198     return ExprError();
3199 
3200   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3201     // Specifically diagnose references to class templates that are missing
3202     // a template argument list.
3203     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3204     return ExprError();
3205   }
3206 
3207   // Make sure that we're referring to a value.
3208   if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3209     Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3210     Diag(D->getLocation(), diag::note_declared_at);
3211     return ExprError();
3212   }
3213 
3214   // Check whether this declaration can be used. Note that we suppress
3215   // this check when we're going to perform argument-dependent lookup
3216   // on this function name, because this might not be the function
3217   // that overload resolution actually selects.
3218   if (DiagnoseUseOfDecl(D, Loc))
3219     return ExprError();
3220 
3221   auto *VD = cast<ValueDecl>(D);
3222 
3223   // Only create DeclRefExpr's for valid Decl's.
3224   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3225     return ExprError();
3226 
3227   // Handle members of anonymous structs and unions.  If we got here,
3228   // and the reference is to a class member indirect field, then this
3229   // must be the subject of a pointer-to-member expression.
3230   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3231     if (!indirectField->isCXXClassMember())
3232       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3233                                                       indirectField);
3234 
3235   QualType type = VD->getType();
3236   if (type.isNull())
3237     return ExprError();
3238   ExprValueKind valueKind = VK_PRValue;
3239 
3240   // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3241   // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3242   // is expanded by some outer '...' in the context of the use.
3243   type = type.getNonPackExpansionType();
3244 
3245   switch (D->getKind()) {
3246     // Ignore all the non-ValueDecl kinds.
3247 #define ABSTRACT_DECL(kind)
3248 #define VALUE(type, base)
3249 #define DECL(type, base) case Decl::type:
3250 #include "clang/AST/DeclNodes.inc"
3251     llvm_unreachable("invalid value decl kind");
3252 
3253   // These shouldn't make it here.
3254   case Decl::ObjCAtDefsField:
3255     llvm_unreachable("forming non-member reference to ivar?");
3256 
3257   // Enum constants are always r-values and never references.
3258   // Unresolved using declarations are dependent.
3259   case Decl::EnumConstant:
3260   case Decl::UnresolvedUsingValue:
3261   case Decl::OMPDeclareReduction:
3262   case Decl::OMPDeclareMapper:
3263     valueKind = VK_PRValue;
3264     break;
3265 
3266   // Fields and indirect fields that got here must be for
3267   // pointer-to-member expressions; we just call them l-values for
3268   // internal consistency, because this subexpression doesn't really
3269   // exist in the high-level semantics.
3270   case Decl::Field:
3271   case Decl::IndirectField:
3272   case Decl::ObjCIvar:
3273     assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3274 
3275     // These can't have reference type in well-formed programs, but
3276     // for internal consistency we do this anyway.
3277     type = type.getNonReferenceType();
3278     valueKind = VK_LValue;
3279     break;
3280 
3281   // Non-type template parameters are either l-values or r-values
3282   // depending on the type.
3283   case Decl::NonTypeTemplateParm: {
3284     if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3285       type = reftype->getPointeeType();
3286       valueKind = VK_LValue; // even if the parameter is an r-value reference
3287       break;
3288     }
3289 
3290     // [expr.prim.id.unqual]p2:
3291     //   If the entity is a template parameter object for a template
3292     //   parameter of type T, the type of the expression is const T.
3293     //   [...] The expression is an lvalue if the entity is a [...] template
3294     //   parameter object.
3295     if (type->isRecordType()) {
3296       type = type.getUnqualifiedType().withConst();
3297       valueKind = VK_LValue;
3298       break;
3299     }
3300 
3301     // For non-references, we need to strip qualifiers just in case
3302     // the template parameter was declared as 'const int' or whatever.
3303     valueKind = VK_PRValue;
3304     type = type.getUnqualifiedType();
3305     break;
3306   }
3307 
3308   case Decl::Var:
3309   case Decl::VarTemplateSpecialization:
3310   case Decl::VarTemplatePartialSpecialization:
3311   case Decl::Decomposition:
3312   case Decl::OMPCapturedExpr:
3313     // In C, "extern void blah;" is valid and is an r-value.
3314     if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3315         type->isVoidType()) {
3316       valueKind = VK_PRValue;
3317       break;
3318     }
3319     LLVM_FALLTHROUGH;
3320 
3321   case Decl::ImplicitParam:
3322   case Decl::ParmVar: {
3323     // These are always l-values.
3324     valueKind = VK_LValue;
3325     type = type.getNonReferenceType();
3326 
3327     // FIXME: Does the addition of const really only apply in
3328     // potentially-evaluated contexts? Since the variable isn't actually
3329     // captured in an unevaluated context, it seems that the answer is no.
3330     if (!isUnevaluatedContext()) {
3331       QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3332       if (!CapturedType.isNull())
3333         type = CapturedType;
3334     }
3335 
3336     break;
3337   }
3338 
3339   case Decl::Binding: {
3340     // These are always lvalues.
3341     valueKind = VK_LValue;
3342     type = type.getNonReferenceType();
3343     // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3344     // decides how that's supposed to work.
3345     auto *BD = cast<BindingDecl>(VD);
3346     if (BD->getDeclContext() != CurContext) {
3347       auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3348       if (DD && DD->hasLocalStorage())
3349         diagnoseUncapturableValueReference(*this, Loc, BD);
3350     }
3351     break;
3352   }
3353 
3354   case Decl::Function: {
3355     if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3356       if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3357         type = Context.BuiltinFnTy;
3358         valueKind = VK_PRValue;
3359         break;
3360       }
3361     }
3362 
3363     const FunctionType *fty = type->castAs<FunctionType>();
3364 
3365     // If we're referring to a function with an __unknown_anytype
3366     // result type, make the entire expression __unknown_anytype.
3367     if (fty->getReturnType() == Context.UnknownAnyTy) {
3368       type = Context.UnknownAnyTy;
3369       valueKind = VK_PRValue;
3370       break;
3371     }
3372 
3373     // Functions are l-values in C++.
3374     if (getLangOpts().CPlusPlus) {
3375       valueKind = VK_LValue;
3376       break;
3377     }
3378 
3379     // C99 DR 316 says that, if a function type comes from a
3380     // function definition (without a prototype), that type is only
3381     // used for checking compatibility. Therefore, when referencing
3382     // the function, we pretend that we don't have the full function
3383     // type.
3384     if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3385       type = Context.getFunctionNoProtoType(fty->getReturnType(),
3386                                             fty->getExtInfo());
3387 
3388     // Functions are r-values in C.
3389     valueKind = VK_PRValue;
3390     break;
3391   }
3392 
3393   case Decl::CXXDeductionGuide:
3394     llvm_unreachable("building reference to deduction guide");
3395 
3396   case Decl::MSProperty:
3397   case Decl::MSGuid:
3398   case Decl::TemplateParamObject:
3399     // FIXME: Should MSGuidDecl and template parameter objects be subject to
3400     // capture in OpenMP, or duplicated between host and device?
3401     valueKind = VK_LValue;
3402     break;
3403 
3404   case Decl::CXXMethod:
3405     // If we're referring to a method with an __unknown_anytype
3406     // result type, make the entire expression __unknown_anytype.
3407     // This should only be possible with a type written directly.
3408     if (const FunctionProtoType *proto =
3409             dyn_cast<FunctionProtoType>(VD->getType()))
3410       if (proto->getReturnType() == Context.UnknownAnyTy) {
3411         type = Context.UnknownAnyTy;
3412         valueKind = VK_PRValue;
3413         break;
3414       }
3415 
3416     // C++ methods are l-values if static, r-values if non-static.
3417     if (cast<CXXMethodDecl>(VD)->isStatic()) {
3418       valueKind = VK_LValue;
3419       break;
3420     }
3421     LLVM_FALLTHROUGH;
3422 
3423   case Decl::CXXConversion:
3424   case Decl::CXXDestructor:
3425   case Decl::CXXConstructor:
3426     valueKind = VK_PRValue;
3427     break;
3428   }
3429 
3430   return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3431                           /*FIXME: TemplateKWLoc*/ SourceLocation(),
3432                           TemplateArgs);
3433 }
3434 
3435 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3436                                     SmallString<32> &Target) {
3437   Target.resize(CharByteWidth * (Source.size() + 1));
3438   char *ResultPtr = &Target[0];
3439   const llvm::UTF8 *ErrorPtr;
3440   bool success =
3441       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3442   (void)success;
3443   assert(success);
3444   Target.resize(ResultPtr - &Target[0]);
3445 }
3446 
3447 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3448                                      PredefinedExpr::IdentKind IK) {
3449   // Pick the current block, lambda, captured statement or function.
3450   Decl *currentDecl = nullptr;
3451   if (const BlockScopeInfo *BSI = getCurBlock())
3452     currentDecl = BSI->TheDecl;
3453   else if (const LambdaScopeInfo *LSI = getCurLambda())
3454     currentDecl = LSI->CallOperator;
3455   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3456     currentDecl = CSI->TheCapturedDecl;
3457   else
3458     currentDecl = getCurFunctionOrMethodDecl();
3459 
3460   if (!currentDecl) {
3461     Diag(Loc, diag::ext_predef_outside_function);
3462     currentDecl = Context.getTranslationUnitDecl();
3463   }
3464 
3465   QualType ResTy;
3466   StringLiteral *SL = nullptr;
3467   if (cast<DeclContext>(currentDecl)->isDependentContext())
3468     ResTy = Context.DependentTy;
3469   else {
3470     // Pre-defined identifiers are of type char[x], where x is the length of
3471     // the string.
3472     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3473     unsigned Length = Str.length();
3474 
3475     llvm::APInt LengthI(32, Length + 1);
3476     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3477       ResTy =
3478           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3479       SmallString<32> RawChars;
3480       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3481                               Str, RawChars);
3482       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3483                                            ArrayType::Normal,
3484                                            /*IndexTypeQuals*/ 0);
3485       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3486                                  /*Pascal*/ false, ResTy, Loc);
3487     } else {
3488       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3489       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3490                                            ArrayType::Normal,
3491                                            /*IndexTypeQuals*/ 0);
3492       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3493                                  /*Pascal*/ false, ResTy, Loc);
3494     }
3495   }
3496 
3497   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3498 }
3499 
3500 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3501                                                SourceLocation LParen,
3502                                                SourceLocation RParen,
3503                                                TypeSourceInfo *TSI) {
3504   return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3505 }
3506 
3507 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3508                                                SourceLocation LParen,
3509                                                SourceLocation RParen,
3510                                                ParsedType ParsedTy) {
3511   TypeSourceInfo *TSI = nullptr;
3512   QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3513 
3514   if (Ty.isNull())
3515     return ExprError();
3516   if (!TSI)
3517     TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3518 
3519   return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3520 }
3521 
3522 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3523   PredefinedExpr::IdentKind IK;
3524 
3525   switch (Kind) {
3526   default: llvm_unreachable("Unknown simple primary expr!");
3527   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3528   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3529   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3530   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3531   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3532   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3533   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3534   }
3535 
3536   return BuildPredefinedExpr(Loc, IK);
3537 }
3538 
3539 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3540   SmallString<16> CharBuffer;
3541   bool Invalid = false;
3542   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3543   if (Invalid)
3544     return ExprError();
3545 
3546   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3547                             PP, Tok.getKind());
3548   if (Literal.hadError())
3549     return ExprError();
3550 
3551   QualType Ty;
3552   if (Literal.isWide())
3553     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3554   else if (Literal.isUTF8() && getLangOpts().Char8)
3555     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3556   else if (Literal.isUTF16())
3557     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3558   else if (Literal.isUTF32())
3559     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3560   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3561     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3562   else
3563     Ty = Context.CharTy;  // 'x' -> char in C++
3564 
3565   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3566   if (Literal.isWide())
3567     Kind = CharacterLiteral::Wide;
3568   else if (Literal.isUTF16())
3569     Kind = CharacterLiteral::UTF16;
3570   else if (Literal.isUTF32())
3571     Kind = CharacterLiteral::UTF32;
3572   else if (Literal.isUTF8())
3573     Kind = CharacterLiteral::UTF8;
3574 
3575   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3576                                              Tok.getLocation());
3577 
3578   if (Literal.getUDSuffix().empty())
3579     return Lit;
3580 
3581   // We're building a user-defined literal.
3582   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3583   SourceLocation UDSuffixLoc =
3584     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3585 
3586   // Make sure we're allowed user-defined literals here.
3587   if (!UDLScope)
3588     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3589 
3590   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3591   //   operator "" X (ch)
3592   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3593                                         Lit, Tok.getLocation());
3594 }
3595 
3596 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3597   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3598   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3599                                 Context.IntTy, Loc);
3600 }
3601 
3602 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3603                                   QualType Ty, SourceLocation Loc) {
3604   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3605 
3606   using llvm::APFloat;
3607   APFloat Val(Format);
3608 
3609   APFloat::opStatus result = Literal.GetFloatValue(Val);
3610 
3611   // Overflow is always an error, but underflow is only an error if
3612   // we underflowed to zero (APFloat reports denormals as underflow).
3613   if ((result & APFloat::opOverflow) ||
3614       ((result & APFloat::opUnderflow) && Val.isZero())) {
3615     unsigned diagnostic;
3616     SmallString<20> buffer;
3617     if (result & APFloat::opOverflow) {
3618       diagnostic = diag::warn_float_overflow;
3619       APFloat::getLargest(Format).toString(buffer);
3620     } else {
3621       diagnostic = diag::warn_float_underflow;
3622       APFloat::getSmallest(Format).toString(buffer);
3623     }
3624 
3625     S.Diag(Loc, diagnostic)
3626       << Ty
3627       << StringRef(buffer.data(), buffer.size());
3628   }
3629 
3630   bool isExact = (result == APFloat::opOK);
3631   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3632 }
3633 
3634 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3635   assert(E && "Invalid expression");
3636 
3637   if (E->isValueDependent())
3638     return false;
3639 
3640   QualType QT = E->getType();
3641   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3642     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3643     return true;
3644   }
3645 
3646   llvm::APSInt ValueAPS;
3647   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3648 
3649   if (R.isInvalid())
3650     return true;
3651 
3652   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3653   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3654     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3655         << toString(ValueAPS, 10) << ValueIsPositive;
3656     return true;
3657   }
3658 
3659   return false;
3660 }
3661 
3662 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3663   // Fast path for a single digit (which is quite common).  A single digit
3664   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3665   if (Tok.getLength() == 1) {
3666     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3667     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3668   }
3669 
3670   SmallString<128> SpellingBuffer;
3671   // NumericLiteralParser wants to overread by one character.  Add padding to
3672   // the buffer in case the token is copied to the buffer.  If getSpelling()
3673   // returns a StringRef to the memory buffer, it should have a null char at
3674   // the EOF, so it is also safe.
3675   SpellingBuffer.resize(Tok.getLength() + 1);
3676 
3677   // Get the spelling of the token, which eliminates trigraphs, etc.
3678   bool Invalid = false;
3679   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3680   if (Invalid)
3681     return ExprError();
3682 
3683   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3684                                PP.getSourceManager(), PP.getLangOpts(),
3685                                PP.getTargetInfo(), PP.getDiagnostics());
3686   if (Literal.hadError)
3687     return ExprError();
3688 
3689   if (Literal.hasUDSuffix()) {
3690     // We're building a user-defined literal.
3691     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3692     SourceLocation UDSuffixLoc =
3693       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3694 
3695     // Make sure we're allowed user-defined literals here.
3696     if (!UDLScope)
3697       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3698 
3699     QualType CookedTy;
3700     if (Literal.isFloatingLiteral()) {
3701       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3702       // long double, the literal is treated as a call of the form
3703       //   operator "" X (f L)
3704       CookedTy = Context.LongDoubleTy;
3705     } else {
3706       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3707       // unsigned long long, the literal is treated as a call of the form
3708       //   operator "" X (n ULL)
3709       CookedTy = Context.UnsignedLongLongTy;
3710     }
3711 
3712     DeclarationName OpName =
3713       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3714     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3715     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3716 
3717     SourceLocation TokLoc = Tok.getLocation();
3718 
3719     // Perform literal operator lookup to determine if we're building a raw
3720     // literal or a cooked one.
3721     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3722     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3723                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3724                                   /*AllowStringTemplatePack*/ false,
3725                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3726     case LOLR_ErrorNoDiagnostic:
3727       // Lookup failure for imaginary constants isn't fatal, there's still the
3728       // GNU extension producing _Complex types.
3729       break;
3730     case LOLR_Error:
3731       return ExprError();
3732     case LOLR_Cooked: {
3733       Expr *Lit;
3734       if (Literal.isFloatingLiteral()) {
3735         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3736       } else {
3737         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3738         if (Literal.GetIntegerValue(ResultVal))
3739           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3740               << /* Unsigned */ 1;
3741         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3742                                      Tok.getLocation());
3743       }
3744       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3745     }
3746 
3747     case LOLR_Raw: {
3748       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3749       // literal is treated as a call of the form
3750       //   operator "" X ("n")
3751       unsigned Length = Literal.getUDSuffixOffset();
3752       QualType StrTy = Context.getConstantArrayType(
3753           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3754           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3755       Expr *Lit = StringLiteral::Create(
3756           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3757           /*Pascal*/false, StrTy, &TokLoc, 1);
3758       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3759     }
3760 
3761     case LOLR_Template: {
3762       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3763       // template), L is treated as a call fo the form
3764       //   operator "" X <'c1', 'c2', ... 'ck'>()
3765       // where n is the source character sequence c1 c2 ... ck.
3766       TemplateArgumentListInfo ExplicitArgs;
3767       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3768       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3769       llvm::APSInt Value(CharBits, CharIsUnsigned);
3770       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3771         Value = TokSpelling[I];
3772         TemplateArgument Arg(Context, Value, Context.CharTy);
3773         TemplateArgumentLocInfo ArgInfo;
3774         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3775       }
3776       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3777                                       &ExplicitArgs);
3778     }
3779     case LOLR_StringTemplatePack:
3780       llvm_unreachable("unexpected literal operator lookup result");
3781     }
3782   }
3783 
3784   Expr *Res;
3785 
3786   if (Literal.isFixedPointLiteral()) {
3787     QualType Ty;
3788 
3789     if (Literal.isAccum) {
3790       if (Literal.isHalf) {
3791         Ty = Context.ShortAccumTy;
3792       } else if (Literal.isLong) {
3793         Ty = Context.LongAccumTy;
3794       } else {
3795         Ty = Context.AccumTy;
3796       }
3797     } else if (Literal.isFract) {
3798       if (Literal.isHalf) {
3799         Ty = Context.ShortFractTy;
3800       } else if (Literal.isLong) {
3801         Ty = Context.LongFractTy;
3802       } else {
3803         Ty = Context.FractTy;
3804       }
3805     }
3806 
3807     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3808 
3809     bool isSigned = !Literal.isUnsigned;
3810     unsigned scale = Context.getFixedPointScale(Ty);
3811     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3812 
3813     llvm::APInt Val(bit_width, 0, isSigned);
3814     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3815     bool ValIsZero = Val.isZero() && !Overflowed;
3816 
3817     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3818     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3819       // Clause 6.4.4 - The value of a constant shall be in the range of
3820       // representable values for its type, with exception for constants of a
3821       // fract type with a value of exactly 1; such a constant shall denote
3822       // the maximal value for the type.
3823       --Val;
3824     else if (Val.ugt(MaxVal) || Overflowed)
3825       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3826 
3827     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3828                                               Tok.getLocation(), scale);
3829   } else if (Literal.isFloatingLiteral()) {
3830     QualType Ty;
3831     if (Literal.isHalf){
3832       if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3833         Ty = Context.HalfTy;
3834       else {
3835         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3836         return ExprError();
3837       }
3838     } else if (Literal.isFloat)
3839       Ty = Context.FloatTy;
3840     else if (Literal.isLong)
3841       Ty = Context.LongDoubleTy;
3842     else if (Literal.isFloat16)
3843       Ty = Context.Float16Ty;
3844     else if (Literal.isFloat128)
3845       Ty = Context.Float128Ty;
3846     else
3847       Ty = Context.DoubleTy;
3848 
3849     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3850 
3851     if (Ty == Context.DoubleTy) {
3852       if (getLangOpts().SinglePrecisionConstants) {
3853         if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3854           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3855         }
3856       } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3857                                              "cl_khr_fp64", getLangOpts())) {
3858         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3859         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3860             << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3861         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3862       }
3863     }
3864   } else if (!Literal.isIntegerLiteral()) {
3865     return ExprError();
3866   } else {
3867     QualType Ty;
3868 
3869     // 'long long' is a C99 or C++11 feature.
3870     if (!getLangOpts().C99 && Literal.isLongLong) {
3871       if (getLangOpts().CPlusPlus)
3872         Diag(Tok.getLocation(),
3873              getLangOpts().CPlusPlus11 ?
3874              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3875       else
3876         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3877     }
3878 
3879     // 'z/uz' literals are a C++2b feature.
3880     if (Literal.isSizeT)
3881       Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3882                                   ? getLangOpts().CPlusPlus2b
3883                                         ? diag::warn_cxx20_compat_size_t_suffix
3884                                         : diag::ext_cxx2b_size_t_suffix
3885                                   : diag::err_cxx2b_size_t_suffix);
3886 
3887     // Get the value in the widest-possible width.
3888     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3889     llvm::APInt ResultVal(MaxWidth, 0);
3890 
3891     if (Literal.GetIntegerValue(ResultVal)) {
3892       // If this value didn't fit into uintmax_t, error and force to ull.
3893       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3894           << /* Unsigned */ 1;
3895       Ty = Context.UnsignedLongLongTy;
3896       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3897              "long long is not intmax_t?");
3898     } else {
3899       // If this value fits into a ULL, try to figure out what else it fits into
3900       // according to the rules of C99 6.4.4.1p5.
3901 
3902       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3903       // be an unsigned int.
3904       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3905 
3906       // Check from smallest to largest, picking the smallest type we can.
3907       unsigned Width = 0;
3908 
3909       // Microsoft specific integer suffixes are explicitly sized.
3910       if (Literal.MicrosoftInteger) {
3911         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3912           Width = 8;
3913           Ty = Context.CharTy;
3914         } else {
3915           Width = Literal.MicrosoftInteger;
3916           Ty = Context.getIntTypeForBitwidth(Width,
3917                                              /*Signed=*/!Literal.isUnsigned);
3918         }
3919       }
3920 
3921       // Check C++2b size_t literals.
3922       if (Literal.isSizeT) {
3923         assert(!Literal.MicrosoftInteger &&
3924                "size_t literals can't be Microsoft literals");
3925         unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3926             Context.getTargetInfo().getSizeType());
3927 
3928         // Does it fit in size_t?
3929         if (ResultVal.isIntN(SizeTSize)) {
3930           // Does it fit in ssize_t?
3931           if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3932             Ty = Context.getSignedSizeType();
3933           else if (AllowUnsigned)
3934             Ty = Context.getSizeType();
3935           Width = SizeTSize;
3936         }
3937       }
3938 
3939       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3940           !Literal.isSizeT) {
3941         // Are int/unsigned possibilities?
3942         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3943 
3944         // Does it fit in a unsigned int?
3945         if (ResultVal.isIntN(IntSize)) {
3946           // Does it fit in a signed int?
3947           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3948             Ty = Context.IntTy;
3949           else if (AllowUnsigned)
3950             Ty = Context.UnsignedIntTy;
3951           Width = IntSize;
3952         }
3953       }
3954 
3955       // Are long/unsigned long possibilities?
3956       if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
3957         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3958 
3959         // Does it fit in a unsigned long?
3960         if (ResultVal.isIntN(LongSize)) {
3961           // Does it fit in a signed long?
3962           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3963             Ty = Context.LongTy;
3964           else if (AllowUnsigned)
3965             Ty = Context.UnsignedLongTy;
3966           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3967           // is compatible.
3968           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3969             const unsigned LongLongSize =
3970                 Context.getTargetInfo().getLongLongWidth();
3971             Diag(Tok.getLocation(),
3972                  getLangOpts().CPlusPlus
3973                      ? Literal.isLong
3974                            ? diag::warn_old_implicitly_unsigned_long_cxx
3975                            : /*C++98 UB*/ diag::
3976                                  ext_old_implicitly_unsigned_long_cxx
3977                      : diag::warn_old_implicitly_unsigned_long)
3978                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3979                                             : /*will be ill-formed*/ 1);
3980             Ty = Context.UnsignedLongTy;
3981           }
3982           Width = LongSize;
3983         }
3984       }
3985 
3986       // Check long long if needed.
3987       if (Ty.isNull() && !Literal.isSizeT) {
3988         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3989 
3990         // Does it fit in a unsigned long long?
3991         if (ResultVal.isIntN(LongLongSize)) {
3992           // Does it fit in a signed long long?
3993           // To be compatible with MSVC, hex integer literals ending with the
3994           // LL or i64 suffix are always signed in Microsoft mode.
3995           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3996               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3997             Ty = Context.LongLongTy;
3998           else if (AllowUnsigned)
3999             Ty = Context.UnsignedLongLongTy;
4000           Width = LongLongSize;
4001         }
4002       }
4003 
4004       // If we still couldn't decide a type, we either have 'size_t' literal
4005       // that is out of range, or a decimal literal that does not fit in a
4006       // signed long long and has no U suffix.
4007       if (Ty.isNull()) {
4008         if (Literal.isSizeT)
4009           Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4010               << Literal.isUnsigned;
4011         else
4012           Diag(Tok.getLocation(),
4013                diag::ext_integer_literal_too_large_for_signed);
4014         Ty = Context.UnsignedLongLongTy;
4015         Width = Context.getTargetInfo().getLongLongWidth();
4016       }
4017 
4018       if (ResultVal.getBitWidth() != Width)
4019         ResultVal = ResultVal.trunc(Width);
4020     }
4021     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4022   }
4023 
4024   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4025   if (Literal.isImaginary) {
4026     Res = new (Context) ImaginaryLiteral(Res,
4027                                         Context.getComplexType(Res->getType()));
4028 
4029     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4030   }
4031   return Res;
4032 }
4033 
4034 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4035   assert(E && "ActOnParenExpr() missing expr");
4036   QualType ExprTy = E->getType();
4037   if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4038       !E->isLValue() && ExprTy->hasFloatingRepresentation())
4039     return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4040   return new (Context) ParenExpr(L, R, E);
4041 }
4042 
4043 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4044                                          SourceLocation Loc,
4045                                          SourceRange ArgRange) {
4046   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4047   // scalar or vector data type argument..."
4048   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4049   // type (C99 6.2.5p18) or void.
4050   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4051     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4052       << T << ArgRange;
4053     return true;
4054   }
4055 
4056   assert((T->isVoidType() || !T->isIncompleteType()) &&
4057          "Scalar types should always be complete");
4058   return false;
4059 }
4060 
4061 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4062                                            SourceLocation Loc,
4063                                            SourceRange ArgRange,
4064                                            UnaryExprOrTypeTrait TraitKind) {
4065   // Invalid types must be hard errors for SFINAE in C++.
4066   if (S.LangOpts.CPlusPlus)
4067     return true;
4068 
4069   // C99 6.5.3.4p1:
4070   if (T->isFunctionType() &&
4071       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4072        TraitKind == UETT_PreferredAlignOf)) {
4073     // sizeof(function)/alignof(function) is allowed as an extension.
4074     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4075         << getTraitSpelling(TraitKind) << ArgRange;
4076     return false;
4077   }
4078 
4079   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4080   // this is an error (OpenCL v1.1 s6.3.k)
4081   if (T->isVoidType()) {
4082     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4083                                         : diag::ext_sizeof_alignof_void_type;
4084     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4085     return false;
4086   }
4087 
4088   return true;
4089 }
4090 
4091 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4092                                              SourceLocation Loc,
4093                                              SourceRange ArgRange,
4094                                              UnaryExprOrTypeTrait TraitKind) {
4095   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4096   // runtime doesn't allow it.
4097   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4098     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4099       << T << (TraitKind == UETT_SizeOf)
4100       << ArgRange;
4101     return true;
4102   }
4103 
4104   return false;
4105 }
4106 
4107 /// Check whether E is a pointer from a decayed array type (the decayed
4108 /// pointer type is equal to T) and emit a warning if it is.
4109 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4110                                      Expr *E) {
4111   // Don't warn if the operation changed the type.
4112   if (T != E->getType())
4113     return;
4114 
4115   // Now look for array decays.
4116   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4117   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4118     return;
4119 
4120   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4121                                              << ICE->getType()
4122                                              << ICE->getSubExpr()->getType();
4123 }
4124 
4125 /// Check the constraints on expression operands to unary type expression
4126 /// and type traits.
4127 ///
4128 /// Completes any types necessary and validates the constraints on the operand
4129 /// expression. The logic mostly mirrors the type-based overload, but may modify
4130 /// the expression as it completes the type for that expression through template
4131 /// instantiation, etc.
4132 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4133                                             UnaryExprOrTypeTrait ExprKind) {
4134   QualType ExprTy = E->getType();
4135   assert(!ExprTy->isReferenceType());
4136 
4137   bool IsUnevaluatedOperand =
4138       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4139        ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4140   if (IsUnevaluatedOperand) {
4141     ExprResult Result = CheckUnevaluatedOperand(E);
4142     if (Result.isInvalid())
4143       return true;
4144     E = Result.get();
4145   }
4146 
4147   // The operand for sizeof and alignof is in an unevaluated expression context,
4148   // so side effects could result in unintended consequences.
4149   // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4150   // used to build SFINAE gadgets.
4151   // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4152   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4153       !E->isInstantiationDependent() &&
4154       E->HasSideEffects(Context, false))
4155     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4156 
4157   if (ExprKind == UETT_VecStep)
4158     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4159                                         E->getSourceRange());
4160 
4161   // Explicitly list some types as extensions.
4162   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4163                                       E->getSourceRange(), ExprKind))
4164     return false;
4165 
4166   // 'alignof' applied to an expression only requires the base element type of
4167   // the expression to be complete. 'sizeof' requires the expression's type to
4168   // be complete (and will attempt to complete it if it's an array of unknown
4169   // bound).
4170   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4171     if (RequireCompleteSizedType(
4172             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4173             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4174             getTraitSpelling(ExprKind), E->getSourceRange()))
4175       return true;
4176   } else {
4177     if (RequireCompleteSizedExprType(
4178             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4179             getTraitSpelling(ExprKind), E->getSourceRange()))
4180       return true;
4181   }
4182 
4183   // Completing the expression's type may have changed it.
4184   ExprTy = E->getType();
4185   assert(!ExprTy->isReferenceType());
4186 
4187   if (ExprTy->isFunctionType()) {
4188     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4189         << getTraitSpelling(ExprKind) << E->getSourceRange();
4190     return true;
4191   }
4192 
4193   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4194                                        E->getSourceRange(), ExprKind))
4195     return true;
4196 
4197   if (ExprKind == UETT_SizeOf) {
4198     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4199       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4200         QualType OType = PVD->getOriginalType();
4201         QualType Type = PVD->getType();
4202         if (Type->isPointerType() && OType->isArrayType()) {
4203           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4204             << Type << OType;
4205           Diag(PVD->getLocation(), diag::note_declared_at);
4206         }
4207       }
4208     }
4209 
4210     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4211     // decays into a pointer and returns an unintended result. This is most
4212     // likely a typo for "sizeof(array) op x".
4213     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4214       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4215                                BO->getLHS());
4216       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4217                                BO->getRHS());
4218     }
4219   }
4220 
4221   return false;
4222 }
4223 
4224 /// Check the constraints on operands to unary expression and type
4225 /// traits.
4226 ///
4227 /// This will complete any types necessary, and validate the various constraints
4228 /// on those operands.
4229 ///
4230 /// The UsualUnaryConversions() function is *not* called by this routine.
4231 /// C99 6.3.2.1p[2-4] all state:
4232 ///   Except when it is the operand of the sizeof operator ...
4233 ///
4234 /// C++ [expr.sizeof]p4
4235 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4236 ///   standard conversions are not applied to the operand of sizeof.
4237 ///
4238 /// This policy is followed for all of the unary trait expressions.
4239 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4240                                             SourceLocation OpLoc,
4241                                             SourceRange ExprRange,
4242                                             UnaryExprOrTypeTrait ExprKind) {
4243   if (ExprType->isDependentType())
4244     return false;
4245 
4246   // C++ [expr.sizeof]p2:
4247   //     When applied to a reference or a reference type, the result
4248   //     is the size of the referenced type.
4249   // C++11 [expr.alignof]p3:
4250   //     When alignof is applied to a reference type, the result
4251   //     shall be the alignment of the referenced type.
4252   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4253     ExprType = Ref->getPointeeType();
4254 
4255   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4256   //   When alignof or _Alignof is applied to an array type, the result
4257   //   is the alignment of the element type.
4258   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4259       ExprKind == UETT_OpenMPRequiredSimdAlign)
4260     ExprType = Context.getBaseElementType(ExprType);
4261 
4262   if (ExprKind == UETT_VecStep)
4263     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4264 
4265   // Explicitly list some types as extensions.
4266   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4267                                       ExprKind))
4268     return false;
4269 
4270   if (RequireCompleteSizedType(
4271           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4272           getTraitSpelling(ExprKind), ExprRange))
4273     return true;
4274 
4275   if (ExprType->isFunctionType()) {
4276     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4277         << getTraitSpelling(ExprKind) << ExprRange;
4278     return true;
4279   }
4280 
4281   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4282                                        ExprKind))
4283     return true;
4284 
4285   return false;
4286 }
4287 
4288 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4289   // Cannot know anything else if the expression is dependent.
4290   if (E->isTypeDependent())
4291     return false;
4292 
4293   if (E->getObjectKind() == OK_BitField) {
4294     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4295        << 1 << E->getSourceRange();
4296     return true;
4297   }
4298 
4299   ValueDecl *D = nullptr;
4300   Expr *Inner = E->IgnoreParens();
4301   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4302     D = DRE->getDecl();
4303   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4304     D = ME->getMemberDecl();
4305   }
4306 
4307   // If it's a field, require the containing struct to have a
4308   // complete definition so that we can compute the layout.
4309   //
4310   // This can happen in C++11 onwards, either by naming the member
4311   // in a way that is not transformed into a member access expression
4312   // (in an unevaluated operand, for instance), or by naming the member
4313   // in a trailing-return-type.
4314   //
4315   // For the record, since __alignof__ on expressions is a GCC
4316   // extension, GCC seems to permit this but always gives the
4317   // nonsensical answer 0.
4318   //
4319   // We don't really need the layout here --- we could instead just
4320   // directly check for all the appropriate alignment-lowing
4321   // attributes --- but that would require duplicating a lot of
4322   // logic that just isn't worth duplicating for such a marginal
4323   // use-case.
4324   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4325     // Fast path this check, since we at least know the record has a
4326     // definition if we can find a member of it.
4327     if (!FD->getParent()->isCompleteDefinition()) {
4328       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4329         << E->getSourceRange();
4330       return true;
4331     }
4332 
4333     // Otherwise, if it's a field, and the field doesn't have
4334     // reference type, then it must have a complete type (or be a
4335     // flexible array member, which we explicitly want to
4336     // white-list anyway), which makes the following checks trivial.
4337     if (!FD->getType()->isReferenceType())
4338       return false;
4339   }
4340 
4341   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4342 }
4343 
4344 bool Sema::CheckVecStepExpr(Expr *E) {
4345   E = E->IgnoreParens();
4346 
4347   // Cannot know anything else if the expression is dependent.
4348   if (E->isTypeDependent())
4349     return false;
4350 
4351   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4352 }
4353 
4354 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4355                                         CapturingScopeInfo *CSI) {
4356   assert(T->isVariablyModifiedType());
4357   assert(CSI != nullptr);
4358 
4359   // We're going to walk down into the type and look for VLA expressions.
4360   do {
4361     const Type *Ty = T.getTypePtr();
4362     switch (Ty->getTypeClass()) {
4363 #define TYPE(Class, Base)
4364 #define ABSTRACT_TYPE(Class, Base)
4365 #define NON_CANONICAL_TYPE(Class, Base)
4366 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4367 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4368 #include "clang/AST/TypeNodes.inc"
4369       T = QualType();
4370       break;
4371     // These types are never variably-modified.
4372     case Type::Builtin:
4373     case Type::Complex:
4374     case Type::Vector:
4375     case Type::ExtVector:
4376     case Type::ConstantMatrix:
4377     case Type::Record:
4378     case Type::Enum:
4379     case Type::Elaborated:
4380     case Type::TemplateSpecialization:
4381     case Type::ObjCObject:
4382     case Type::ObjCInterface:
4383     case Type::ObjCObjectPointer:
4384     case Type::ObjCTypeParam:
4385     case Type::Pipe:
4386     case Type::BitInt:
4387       llvm_unreachable("type class is never variably-modified!");
4388     case Type::Adjusted:
4389       T = cast<AdjustedType>(Ty)->getOriginalType();
4390       break;
4391     case Type::Decayed:
4392       T = cast<DecayedType>(Ty)->getPointeeType();
4393       break;
4394     case Type::Pointer:
4395       T = cast<PointerType>(Ty)->getPointeeType();
4396       break;
4397     case Type::BlockPointer:
4398       T = cast<BlockPointerType>(Ty)->getPointeeType();
4399       break;
4400     case Type::LValueReference:
4401     case Type::RValueReference:
4402       T = cast<ReferenceType>(Ty)->getPointeeType();
4403       break;
4404     case Type::MemberPointer:
4405       T = cast<MemberPointerType>(Ty)->getPointeeType();
4406       break;
4407     case Type::ConstantArray:
4408     case Type::IncompleteArray:
4409       // Losing element qualification here is fine.
4410       T = cast<ArrayType>(Ty)->getElementType();
4411       break;
4412     case Type::VariableArray: {
4413       // Losing element qualification here is fine.
4414       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4415 
4416       // Unknown size indication requires no size computation.
4417       // Otherwise, evaluate and record it.
4418       auto Size = VAT->getSizeExpr();
4419       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4420           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4421         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4422 
4423       T = VAT->getElementType();
4424       break;
4425     }
4426     case Type::FunctionProto:
4427     case Type::FunctionNoProto:
4428       T = cast<FunctionType>(Ty)->getReturnType();
4429       break;
4430     case Type::Paren:
4431     case Type::TypeOf:
4432     case Type::UnaryTransform:
4433     case Type::Attributed:
4434     case Type::SubstTemplateTypeParm:
4435     case Type::MacroQualified:
4436       // Keep walking after single level desugaring.
4437       T = T.getSingleStepDesugaredType(Context);
4438       break;
4439     case Type::Typedef:
4440       T = cast<TypedefType>(Ty)->desugar();
4441       break;
4442     case Type::Decltype:
4443       T = cast<DecltypeType>(Ty)->desugar();
4444       break;
4445     case Type::Using:
4446       T = cast<UsingType>(Ty)->desugar();
4447       break;
4448     case Type::Auto:
4449     case Type::DeducedTemplateSpecialization:
4450       T = cast<DeducedType>(Ty)->getDeducedType();
4451       break;
4452     case Type::TypeOfExpr:
4453       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4454       break;
4455     case Type::Atomic:
4456       T = cast<AtomicType>(Ty)->getValueType();
4457       break;
4458     }
4459   } while (!T.isNull() && T->isVariablyModifiedType());
4460 }
4461 
4462 /// Build a sizeof or alignof expression given a type operand.
4463 ExprResult
4464 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4465                                      SourceLocation OpLoc,
4466                                      UnaryExprOrTypeTrait ExprKind,
4467                                      SourceRange R) {
4468   if (!TInfo)
4469     return ExprError();
4470 
4471   QualType T = TInfo->getType();
4472 
4473   if (!T->isDependentType() &&
4474       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4475     return ExprError();
4476 
4477   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4478     if (auto *TT = T->getAs<TypedefType>()) {
4479       for (auto I = FunctionScopes.rbegin(),
4480                 E = std::prev(FunctionScopes.rend());
4481            I != E; ++I) {
4482         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4483         if (CSI == nullptr)
4484           break;
4485         DeclContext *DC = nullptr;
4486         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4487           DC = LSI->CallOperator;
4488         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4489           DC = CRSI->TheCapturedDecl;
4490         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4491           DC = BSI->TheDecl;
4492         if (DC) {
4493           if (DC->containsDecl(TT->getDecl()))
4494             break;
4495           captureVariablyModifiedType(Context, T, CSI);
4496         }
4497       }
4498     }
4499   }
4500 
4501   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4502   if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4503       TInfo->getType()->isVariablyModifiedType())
4504     TInfo = TransformToPotentiallyEvaluated(TInfo);
4505 
4506   return new (Context) UnaryExprOrTypeTraitExpr(
4507       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4508 }
4509 
4510 /// Build a sizeof or alignof expression given an expression
4511 /// operand.
4512 ExprResult
4513 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4514                                      UnaryExprOrTypeTrait ExprKind) {
4515   ExprResult PE = CheckPlaceholderExpr(E);
4516   if (PE.isInvalid())
4517     return ExprError();
4518 
4519   E = PE.get();
4520 
4521   // Verify that the operand is valid.
4522   bool isInvalid = false;
4523   if (E->isTypeDependent()) {
4524     // Delay type-checking for type-dependent expressions.
4525   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4526     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4527   } else if (ExprKind == UETT_VecStep) {
4528     isInvalid = CheckVecStepExpr(E);
4529   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4530       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4531       isInvalid = true;
4532   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4533     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4534     isInvalid = true;
4535   } else {
4536     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4537   }
4538 
4539   if (isInvalid)
4540     return ExprError();
4541 
4542   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4543     PE = TransformToPotentiallyEvaluated(E);
4544     if (PE.isInvalid()) return ExprError();
4545     E = PE.get();
4546   }
4547 
4548   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4549   return new (Context) UnaryExprOrTypeTraitExpr(
4550       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4551 }
4552 
4553 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4554 /// expr and the same for @c alignof and @c __alignof
4555 /// Note that the ArgRange is invalid if isType is false.
4556 ExprResult
4557 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4558                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4559                                     void *TyOrEx, SourceRange ArgRange) {
4560   // If error parsing type, ignore.
4561   if (!TyOrEx) return ExprError();
4562 
4563   if (IsType) {
4564     TypeSourceInfo *TInfo;
4565     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4566     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4567   }
4568 
4569   Expr *ArgEx = (Expr *)TyOrEx;
4570   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4571   return Result;
4572 }
4573 
4574 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4575                                      bool IsReal) {
4576   if (V.get()->isTypeDependent())
4577     return S.Context.DependentTy;
4578 
4579   // _Real and _Imag are only l-values for normal l-values.
4580   if (V.get()->getObjectKind() != OK_Ordinary) {
4581     V = S.DefaultLvalueConversion(V.get());
4582     if (V.isInvalid())
4583       return QualType();
4584   }
4585 
4586   // These operators return the element type of a complex type.
4587   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4588     return CT->getElementType();
4589 
4590   // Otherwise they pass through real integer and floating point types here.
4591   if (V.get()->getType()->isArithmeticType())
4592     return V.get()->getType();
4593 
4594   // Test for placeholders.
4595   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4596   if (PR.isInvalid()) return QualType();
4597   if (PR.get() != V.get()) {
4598     V = PR;
4599     return CheckRealImagOperand(S, V, Loc, IsReal);
4600   }
4601 
4602   // Reject anything else.
4603   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4604     << (IsReal ? "__real" : "__imag");
4605   return QualType();
4606 }
4607 
4608 
4609 
4610 ExprResult
4611 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4612                           tok::TokenKind Kind, Expr *Input) {
4613   UnaryOperatorKind Opc;
4614   switch (Kind) {
4615   default: llvm_unreachable("Unknown unary op!");
4616   case tok::plusplus:   Opc = UO_PostInc; break;
4617   case tok::minusminus: Opc = UO_PostDec; break;
4618   }
4619 
4620   // Since this might is a postfix expression, get rid of ParenListExprs.
4621   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4622   if (Result.isInvalid()) return ExprError();
4623   Input = Result.get();
4624 
4625   return BuildUnaryOp(S, OpLoc, Opc, Input);
4626 }
4627 
4628 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4629 ///
4630 /// \return true on error
4631 static bool checkArithmeticOnObjCPointer(Sema &S,
4632                                          SourceLocation opLoc,
4633                                          Expr *op) {
4634   assert(op->getType()->isObjCObjectPointerType());
4635   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4636       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4637     return false;
4638 
4639   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4640     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4641     << op->getSourceRange();
4642   return true;
4643 }
4644 
4645 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4646   auto *BaseNoParens = Base->IgnoreParens();
4647   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4648     return MSProp->getPropertyDecl()->getType()->isArrayType();
4649   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4650 }
4651 
4652 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4653 // Typically this is DependentTy, but can sometimes be more precise.
4654 //
4655 // There are cases when we could determine a non-dependent type:
4656 //  - LHS and RHS may have non-dependent types despite being type-dependent
4657 //    (e.g. unbounded array static members of the current instantiation)
4658 //  - one may be a dependent-sized array with known element type
4659 //  - one may be a dependent-typed valid index (enum in current instantiation)
4660 //
4661 // We *always* return a dependent type, in such cases it is DependentTy.
4662 // This avoids creating type-dependent expressions with non-dependent types.
4663 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4664 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4665                                                const ASTContext &Ctx) {
4666   assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4667   QualType LTy = LHS->getType(), RTy = RHS->getType();
4668   QualType Result = Ctx.DependentTy;
4669   if (RTy->isIntegralOrUnscopedEnumerationType()) {
4670     if (const PointerType *PT = LTy->getAs<PointerType>())
4671       Result = PT->getPointeeType();
4672     else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4673       Result = AT->getElementType();
4674   } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4675     if (const PointerType *PT = RTy->getAs<PointerType>())
4676       Result = PT->getPointeeType();
4677     else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4678       Result = AT->getElementType();
4679   }
4680   // Ensure we return a dependent type.
4681   return Result->isDependentType() ? Result : Ctx.DependentTy;
4682 }
4683 
4684 ExprResult
4685 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4686                               Expr *idx, SourceLocation rbLoc) {
4687   if (base && !base->getType().isNull() &&
4688       base->hasPlaceholderType(BuiltinType::OMPArraySection))
4689     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4690                                     SourceLocation(), /*Length*/ nullptr,
4691                                     /*Stride=*/nullptr, rbLoc);
4692 
4693   // Since this might be a postfix expression, get rid of ParenListExprs.
4694   if (isa<ParenListExpr>(base)) {
4695     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4696     if (result.isInvalid()) return ExprError();
4697     base = result.get();
4698   }
4699 
4700   // Check if base and idx form a MatrixSubscriptExpr.
4701   //
4702   // Helper to check for comma expressions, which are not allowed as indices for
4703   // matrix subscript expressions.
4704   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4705     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4706       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4707           << SourceRange(base->getBeginLoc(), rbLoc);
4708       return true;
4709     }
4710     return false;
4711   };
4712   // The matrix subscript operator ([][])is considered a single operator.
4713   // Separating the index expressions by parenthesis is not allowed.
4714   if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4715       !isa<MatrixSubscriptExpr>(base)) {
4716     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4717         << SourceRange(base->getBeginLoc(), rbLoc);
4718     return ExprError();
4719   }
4720   // If the base is a MatrixSubscriptExpr, try to create a new
4721   // MatrixSubscriptExpr.
4722   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4723   if (matSubscriptE) {
4724     if (CheckAndReportCommaError(idx))
4725       return ExprError();
4726 
4727     assert(matSubscriptE->isIncomplete() &&
4728            "base has to be an incomplete matrix subscript");
4729     return CreateBuiltinMatrixSubscriptExpr(
4730         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4731   }
4732 
4733   // Handle any non-overload placeholder types in the base and index
4734   // expressions.  We can't handle overloads here because the other
4735   // operand might be an overloadable type, in which case the overload
4736   // resolution for the operator overload should get the first crack
4737   // at the overload.
4738   bool IsMSPropertySubscript = false;
4739   if (base->getType()->isNonOverloadPlaceholderType()) {
4740     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4741     if (!IsMSPropertySubscript) {
4742       ExprResult result = CheckPlaceholderExpr(base);
4743       if (result.isInvalid())
4744         return ExprError();
4745       base = result.get();
4746     }
4747   }
4748 
4749   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4750   if (base->getType()->isMatrixType()) {
4751     if (CheckAndReportCommaError(idx))
4752       return ExprError();
4753 
4754     return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4755   }
4756 
4757   // A comma-expression as the index is deprecated in C++2a onwards.
4758   if (getLangOpts().CPlusPlus20 &&
4759       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4760        (isa<CXXOperatorCallExpr>(idx) &&
4761         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4762     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4763         << SourceRange(base->getBeginLoc(), rbLoc);
4764   }
4765 
4766   if (idx->getType()->isNonOverloadPlaceholderType()) {
4767     ExprResult result = CheckPlaceholderExpr(idx);
4768     if (result.isInvalid()) return ExprError();
4769     idx = result.get();
4770   }
4771 
4772   // Build an unanalyzed expression if either operand is type-dependent.
4773   if (getLangOpts().CPlusPlus &&
4774       (base->isTypeDependent() || idx->isTypeDependent())) {
4775     return new (Context) ArraySubscriptExpr(
4776         base, idx, getDependentArraySubscriptType(base, idx, getASTContext()),
4777         VK_LValue, OK_Ordinary, rbLoc);
4778   }
4779 
4780   // MSDN, property (C++)
4781   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4782   // This attribute can also be used in the declaration of an empty array in a
4783   // class or structure definition. For example:
4784   // __declspec(property(get=GetX, put=PutX)) int x[];
4785   // The above statement indicates that x[] can be used with one or more array
4786   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4787   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4788   if (IsMSPropertySubscript) {
4789     // Build MS property subscript expression if base is MS property reference
4790     // or MS property subscript.
4791     return new (Context) MSPropertySubscriptExpr(
4792         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4793   }
4794 
4795   // Use C++ overloaded-operator rules if either operand has record
4796   // type.  The spec says to do this if either type is *overloadable*,
4797   // but enum types can't declare subscript operators or conversion
4798   // operators, so there's nothing interesting for overload resolution
4799   // to do if there aren't any record types involved.
4800   //
4801   // ObjC pointers have their own subscripting logic that is not tied
4802   // to overload resolution and so should not take this path.
4803   if (getLangOpts().CPlusPlus &&
4804       (base->getType()->isRecordType() ||
4805        (!base->getType()->isObjCObjectPointerType() &&
4806         idx->getType()->isRecordType()))) {
4807     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4808   }
4809 
4810   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4811 
4812   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4813     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4814 
4815   return Res;
4816 }
4817 
4818 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4819   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4820   InitializationKind Kind =
4821       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4822   InitializationSequence InitSeq(*this, Entity, Kind, E);
4823   return InitSeq.Perform(*this, Entity, Kind, E);
4824 }
4825 
4826 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4827                                                   Expr *ColumnIdx,
4828                                                   SourceLocation RBLoc) {
4829   ExprResult BaseR = CheckPlaceholderExpr(Base);
4830   if (BaseR.isInvalid())
4831     return BaseR;
4832   Base = BaseR.get();
4833 
4834   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4835   if (RowR.isInvalid())
4836     return RowR;
4837   RowIdx = RowR.get();
4838 
4839   if (!ColumnIdx)
4840     return new (Context) MatrixSubscriptExpr(
4841         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4842 
4843   // Build an unanalyzed expression if any of the operands is type-dependent.
4844   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4845       ColumnIdx->isTypeDependent())
4846     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4847                                              Context.DependentTy, RBLoc);
4848 
4849   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4850   if (ColumnR.isInvalid())
4851     return ColumnR;
4852   ColumnIdx = ColumnR.get();
4853 
4854   // Check that IndexExpr is an integer expression. If it is a constant
4855   // expression, check that it is less than Dim (= the number of elements in the
4856   // corresponding dimension).
4857   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4858                           bool IsColumnIdx) -> Expr * {
4859     if (!IndexExpr->getType()->isIntegerType() &&
4860         !IndexExpr->isTypeDependent()) {
4861       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4862           << IsColumnIdx;
4863       return nullptr;
4864     }
4865 
4866     if (Optional<llvm::APSInt> Idx =
4867             IndexExpr->getIntegerConstantExpr(Context)) {
4868       if ((*Idx < 0 || *Idx >= Dim)) {
4869         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4870             << IsColumnIdx << Dim;
4871         return nullptr;
4872       }
4873     }
4874 
4875     ExprResult ConvExpr =
4876         tryConvertExprToType(IndexExpr, Context.getSizeType());
4877     assert(!ConvExpr.isInvalid() &&
4878            "should be able to convert any integer type to size type");
4879     return ConvExpr.get();
4880   };
4881 
4882   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4883   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4884   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4885   if (!RowIdx || !ColumnIdx)
4886     return ExprError();
4887 
4888   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4889                                            MTy->getElementType(), RBLoc);
4890 }
4891 
4892 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4893   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4894   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4895 
4896   // For expressions like `&(*s).b`, the base is recorded and what should be
4897   // checked.
4898   const MemberExpr *Member = nullptr;
4899   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4900     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4901 
4902   LastRecord.PossibleDerefs.erase(StrippedExpr);
4903 }
4904 
4905 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4906   if (isUnevaluatedContext())
4907     return;
4908 
4909   QualType ResultTy = E->getType();
4910   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4911 
4912   // Bail if the element is an array since it is not memory access.
4913   if (isa<ArrayType>(ResultTy))
4914     return;
4915 
4916   if (ResultTy->hasAttr(attr::NoDeref)) {
4917     LastRecord.PossibleDerefs.insert(E);
4918     return;
4919   }
4920 
4921   // Check if the base type is a pointer to a member access of a struct
4922   // marked with noderef.
4923   const Expr *Base = E->getBase();
4924   QualType BaseTy = Base->getType();
4925   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4926     // Not a pointer access
4927     return;
4928 
4929   const MemberExpr *Member = nullptr;
4930   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4931          Member->isArrow())
4932     Base = Member->getBase();
4933 
4934   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4935     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4936       LastRecord.PossibleDerefs.insert(E);
4937   }
4938 }
4939 
4940 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4941                                           Expr *LowerBound,
4942                                           SourceLocation ColonLocFirst,
4943                                           SourceLocation ColonLocSecond,
4944                                           Expr *Length, Expr *Stride,
4945                                           SourceLocation RBLoc) {
4946   if (Base->hasPlaceholderType() &&
4947       !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
4948     ExprResult Result = CheckPlaceholderExpr(Base);
4949     if (Result.isInvalid())
4950       return ExprError();
4951     Base = Result.get();
4952   }
4953   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4954     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4955     if (Result.isInvalid())
4956       return ExprError();
4957     Result = DefaultLvalueConversion(Result.get());
4958     if (Result.isInvalid())
4959       return ExprError();
4960     LowerBound = Result.get();
4961   }
4962   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4963     ExprResult Result = CheckPlaceholderExpr(Length);
4964     if (Result.isInvalid())
4965       return ExprError();
4966     Result = DefaultLvalueConversion(Result.get());
4967     if (Result.isInvalid())
4968       return ExprError();
4969     Length = Result.get();
4970   }
4971   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4972     ExprResult Result = CheckPlaceholderExpr(Stride);
4973     if (Result.isInvalid())
4974       return ExprError();
4975     Result = DefaultLvalueConversion(Result.get());
4976     if (Result.isInvalid())
4977       return ExprError();
4978     Stride = Result.get();
4979   }
4980 
4981   // Build an unanalyzed expression if either operand is type-dependent.
4982   if (Base->isTypeDependent() ||
4983       (LowerBound &&
4984        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4985       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4986       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4987     return new (Context) OMPArraySectionExpr(
4988         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4989         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4990   }
4991 
4992   // Perform default conversions.
4993   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4994   QualType ResultTy;
4995   if (OriginalTy->isAnyPointerType()) {
4996     ResultTy = OriginalTy->getPointeeType();
4997   } else if (OriginalTy->isArrayType()) {
4998     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4999   } else {
5000     return ExprError(
5001         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5002         << Base->getSourceRange());
5003   }
5004   // C99 6.5.2.1p1
5005   if (LowerBound) {
5006     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5007                                                       LowerBound);
5008     if (Res.isInvalid())
5009       return ExprError(Diag(LowerBound->getExprLoc(),
5010                             diag::err_omp_typecheck_section_not_integer)
5011                        << 0 << LowerBound->getSourceRange());
5012     LowerBound = Res.get();
5013 
5014     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5015         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5016       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5017           << 0 << LowerBound->getSourceRange();
5018   }
5019   if (Length) {
5020     auto Res =
5021         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5022     if (Res.isInvalid())
5023       return ExprError(Diag(Length->getExprLoc(),
5024                             diag::err_omp_typecheck_section_not_integer)
5025                        << 1 << Length->getSourceRange());
5026     Length = Res.get();
5027 
5028     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5029         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5030       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5031           << 1 << Length->getSourceRange();
5032   }
5033   if (Stride) {
5034     ExprResult Res =
5035         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5036     if (Res.isInvalid())
5037       return ExprError(Diag(Stride->getExprLoc(),
5038                             diag::err_omp_typecheck_section_not_integer)
5039                        << 1 << Stride->getSourceRange());
5040     Stride = Res.get();
5041 
5042     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5043         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5044       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5045           << 1 << Stride->getSourceRange();
5046   }
5047 
5048   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5049   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5050   // type. Note that functions are not objects, and that (in C99 parlance)
5051   // incomplete types are not object types.
5052   if (ResultTy->isFunctionType()) {
5053     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5054         << ResultTy << Base->getSourceRange();
5055     return ExprError();
5056   }
5057 
5058   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5059                           diag::err_omp_section_incomplete_type, Base))
5060     return ExprError();
5061 
5062   if (LowerBound && !OriginalTy->isAnyPointerType()) {
5063     Expr::EvalResult Result;
5064     if (LowerBound->EvaluateAsInt(Result, Context)) {
5065       // OpenMP 5.0, [2.1.5 Array Sections]
5066       // The array section must be a subset of the original array.
5067       llvm::APSInt LowerBoundValue = Result.Val.getInt();
5068       if (LowerBoundValue.isNegative()) {
5069         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5070             << LowerBound->getSourceRange();
5071         return ExprError();
5072       }
5073     }
5074   }
5075 
5076   if (Length) {
5077     Expr::EvalResult Result;
5078     if (Length->EvaluateAsInt(Result, Context)) {
5079       // OpenMP 5.0, [2.1.5 Array Sections]
5080       // The length must evaluate to non-negative integers.
5081       llvm::APSInt LengthValue = Result.Val.getInt();
5082       if (LengthValue.isNegative()) {
5083         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5084             << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5085             << Length->getSourceRange();
5086         return ExprError();
5087       }
5088     }
5089   } else if (ColonLocFirst.isValid() &&
5090              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5091                                       !OriginalTy->isVariableArrayType()))) {
5092     // OpenMP 5.0, [2.1.5 Array Sections]
5093     // When the size of the array dimension is not known, the length must be
5094     // specified explicitly.
5095     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5096         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5097     return ExprError();
5098   }
5099 
5100   if (Stride) {
5101     Expr::EvalResult Result;
5102     if (Stride->EvaluateAsInt(Result, Context)) {
5103       // OpenMP 5.0, [2.1.5 Array Sections]
5104       // The stride must evaluate to a positive integer.
5105       llvm::APSInt StrideValue = Result.Val.getInt();
5106       if (!StrideValue.isStrictlyPositive()) {
5107         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5108             << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5109             << Stride->getSourceRange();
5110         return ExprError();
5111       }
5112     }
5113   }
5114 
5115   if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5116     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5117     if (Result.isInvalid())
5118       return ExprError();
5119     Base = Result.get();
5120   }
5121   return new (Context) OMPArraySectionExpr(
5122       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5123       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5124 }
5125 
5126 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5127                                           SourceLocation RParenLoc,
5128                                           ArrayRef<Expr *> Dims,
5129                                           ArrayRef<SourceRange> Brackets) {
5130   if (Base->hasPlaceholderType()) {
5131     ExprResult Result = CheckPlaceholderExpr(Base);
5132     if (Result.isInvalid())
5133       return ExprError();
5134     Result = DefaultLvalueConversion(Result.get());
5135     if (Result.isInvalid())
5136       return ExprError();
5137     Base = Result.get();
5138   }
5139   QualType BaseTy = Base->getType();
5140   // Delay analysis of the types/expressions if instantiation/specialization is
5141   // required.
5142   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5143     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5144                                        LParenLoc, RParenLoc, Dims, Brackets);
5145   if (!BaseTy->isPointerType() ||
5146       (!Base->isTypeDependent() &&
5147        BaseTy->getPointeeType()->isIncompleteType()))
5148     return ExprError(Diag(Base->getExprLoc(),
5149                           diag::err_omp_non_pointer_type_array_shaping_base)
5150                      << Base->getSourceRange());
5151 
5152   SmallVector<Expr *, 4> NewDims;
5153   bool ErrorFound = false;
5154   for (Expr *Dim : Dims) {
5155     if (Dim->hasPlaceholderType()) {
5156       ExprResult Result = CheckPlaceholderExpr(Dim);
5157       if (Result.isInvalid()) {
5158         ErrorFound = true;
5159         continue;
5160       }
5161       Result = DefaultLvalueConversion(Result.get());
5162       if (Result.isInvalid()) {
5163         ErrorFound = true;
5164         continue;
5165       }
5166       Dim = Result.get();
5167     }
5168     if (!Dim->isTypeDependent()) {
5169       ExprResult Result =
5170           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5171       if (Result.isInvalid()) {
5172         ErrorFound = true;
5173         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5174             << Dim->getSourceRange();
5175         continue;
5176       }
5177       Dim = Result.get();
5178       Expr::EvalResult EvResult;
5179       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5180         // OpenMP 5.0, [2.1.4 Array Shaping]
5181         // Each si is an integral type expression that must evaluate to a
5182         // positive integer.
5183         llvm::APSInt Value = EvResult.Val.getInt();
5184         if (!Value.isStrictlyPositive()) {
5185           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5186               << toString(Value, /*Radix=*/10, /*Signed=*/true)
5187               << Dim->getSourceRange();
5188           ErrorFound = true;
5189           continue;
5190         }
5191       }
5192     }
5193     NewDims.push_back(Dim);
5194   }
5195   if (ErrorFound)
5196     return ExprError();
5197   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5198                                      LParenLoc, RParenLoc, NewDims, Brackets);
5199 }
5200 
5201 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5202                                       SourceLocation LLoc, SourceLocation RLoc,
5203                                       ArrayRef<OMPIteratorData> Data) {
5204   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5205   bool IsCorrect = true;
5206   for (const OMPIteratorData &D : Data) {
5207     TypeSourceInfo *TInfo = nullptr;
5208     SourceLocation StartLoc;
5209     QualType DeclTy;
5210     if (!D.Type.getAsOpaquePtr()) {
5211       // OpenMP 5.0, 2.1.6 Iterators
5212       // In an iterator-specifier, if the iterator-type is not specified then
5213       // the type of that iterator is of int type.
5214       DeclTy = Context.IntTy;
5215       StartLoc = D.DeclIdentLoc;
5216     } else {
5217       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5218       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5219     }
5220 
5221     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5222                              DeclTy->containsUnexpandedParameterPack() ||
5223                              DeclTy->isInstantiationDependentType();
5224     if (!IsDeclTyDependent) {
5225       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5226         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5227         // The iterator-type must be an integral or pointer type.
5228         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5229             << DeclTy;
5230         IsCorrect = false;
5231         continue;
5232       }
5233       if (DeclTy.isConstant(Context)) {
5234         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5235         // The iterator-type must not be const qualified.
5236         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5237             << DeclTy;
5238         IsCorrect = false;
5239         continue;
5240       }
5241     }
5242 
5243     // Iterator declaration.
5244     assert(D.DeclIdent && "Identifier expected.");
5245     // Always try to create iterator declarator to avoid extra error messages
5246     // about unknown declarations use.
5247     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5248                                D.DeclIdent, DeclTy, TInfo, SC_None);
5249     VD->setImplicit();
5250     if (S) {
5251       // Check for conflicting previous declaration.
5252       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5253       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5254                             ForVisibleRedeclaration);
5255       Previous.suppressDiagnostics();
5256       LookupName(Previous, S);
5257 
5258       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5259                            /*AllowInlineNamespace=*/false);
5260       if (!Previous.empty()) {
5261         NamedDecl *Old = Previous.getRepresentativeDecl();
5262         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5263         Diag(Old->getLocation(), diag::note_previous_definition);
5264       } else {
5265         PushOnScopeChains(VD, S);
5266       }
5267     } else {
5268       CurContext->addDecl(VD);
5269     }
5270     Expr *Begin = D.Range.Begin;
5271     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5272       ExprResult BeginRes =
5273           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5274       Begin = BeginRes.get();
5275     }
5276     Expr *End = D.Range.End;
5277     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5278       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5279       End = EndRes.get();
5280     }
5281     Expr *Step = D.Range.Step;
5282     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5283       if (!Step->getType()->isIntegralType(Context)) {
5284         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5285             << Step << Step->getSourceRange();
5286         IsCorrect = false;
5287         continue;
5288       }
5289       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5290       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5291       // If the step expression of a range-specification equals zero, the
5292       // behavior is unspecified.
5293       if (Result && Result->isZero()) {
5294         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5295             << Step << Step->getSourceRange();
5296         IsCorrect = false;
5297         continue;
5298       }
5299     }
5300     if (!Begin || !End || !IsCorrect) {
5301       IsCorrect = false;
5302       continue;
5303     }
5304     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5305     IDElem.IteratorDecl = VD;
5306     IDElem.AssignmentLoc = D.AssignLoc;
5307     IDElem.Range.Begin = Begin;
5308     IDElem.Range.End = End;
5309     IDElem.Range.Step = Step;
5310     IDElem.ColonLoc = D.ColonLoc;
5311     IDElem.SecondColonLoc = D.SecColonLoc;
5312   }
5313   if (!IsCorrect) {
5314     // Invalidate all created iterator declarations if error is found.
5315     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5316       if (Decl *ID = D.IteratorDecl)
5317         ID->setInvalidDecl();
5318     }
5319     return ExprError();
5320   }
5321   SmallVector<OMPIteratorHelperData, 4> Helpers;
5322   if (!CurContext->isDependentContext()) {
5323     // Build number of ityeration for each iteration range.
5324     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5325     // ((Begini-Stepi-1-Endi) / -Stepi);
5326     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5327       // (Endi - Begini)
5328       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5329                                           D.Range.Begin);
5330       if(!Res.isUsable()) {
5331         IsCorrect = false;
5332         continue;
5333       }
5334       ExprResult St, St1;
5335       if (D.Range.Step) {
5336         St = D.Range.Step;
5337         // (Endi - Begini) + Stepi
5338         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5339         if (!Res.isUsable()) {
5340           IsCorrect = false;
5341           continue;
5342         }
5343         // (Endi - Begini) + Stepi - 1
5344         Res =
5345             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5346                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5347         if (!Res.isUsable()) {
5348           IsCorrect = false;
5349           continue;
5350         }
5351         // ((Endi - Begini) + Stepi - 1) / Stepi
5352         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5353         if (!Res.isUsable()) {
5354           IsCorrect = false;
5355           continue;
5356         }
5357         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5358         // (Begini - Endi)
5359         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5360                                              D.Range.Begin, D.Range.End);
5361         if (!Res1.isUsable()) {
5362           IsCorrect = false;
5363           continue;
5364         }
5365         // (Begini - Endi) - Stepi
5366         Res1 =
5367             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5368         if (!Res1.isUsable()) {
5369           IsCorrect = false;
5370           continue;
5371         }
5372         // (Begini - Endi) - Stepi - 1
5373         Res1 =
5374             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5375                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5376         if (!Res1.isUsable()) {
5377           IsCorrect = false;
5378           continue;
5379         }
5380         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5381         Res1 =
5382             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5383         if (!Res1.isUsable()) {
5384           IsCorrect = false;
5385           continue;
5386         }
5387         // Stepi > 0.
5388         ExprResult CmpRes =
5389             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5390                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5391         if (!CmpRes.isUsable()) {
5392           IsCorrect = false;
5393           continue;
5394         }
5395         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5396                                  Res.get(), Res1.get());
5397         if (!Res.isUsable()) {
5398           IsCorrect = false;
5399           continue;
5400         }
5401       }
5402       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5403       if (!Res.isUsable()) {
5404         IsCorrect = false;
5405         continue;
5406       }
5407 
5408       // Build counter update.
5409       // Build counter.
5410       auto *CounterVD =
5411           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5412                           D.IteratorDecl->getBeginLoc(), nullptr,
5413                           Res.get()->getType(), nullptr, SC_None);
5414       CounterVD->setImplicit();
5415       ExprResult RefRes =
5416           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5417                            D.IteratorDecl->getBeginLoc());
5418       // Build counter update.
5419       // I = Begini + counter * Stepi;
5420       ExprResult UpdateRes;
5421       if (D.Range.Step) {
5422         UpdateRes = CreateBuiltinBinOp(
5423             D.AssignmentLoc, BO_Mul,
5424             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5425       } else {
5426         UpdateRes = DefaultLvalueConversion(RefRes.get());
5427       }
5428       if (!UpdateRes.isUsable()) {
5429         IsCorrect = false;
5430         continue;
5431       }
5432       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5433                                      UpdateRes.get());
5434       if (!UpdateRes.isUsable()) {
5435         IsCorrect = false;
5436         continue;
5437       }
5438       ExprResult VDRes =
5439           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5440                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5441                            D.IteratorDecl->getBeginLoc());
5442       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5443                                      UpdateRes.get());
5444       if (!UpdateRes.isUsable()) {
5445         IsCorrect = false;
5446         continue;
5447       }
5448       UpdateRes =
5449           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5450       if (!UpdateRes.isUsable()) {
5451         IsCorrect = false;
5452         continue;
5453       }
5454       ExprResult CounterUpdateRes =
5455           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5456       if (!CounterUpdateRes.isUsable()) {
5457         IsCorrect = false;
5458         continue;
5459       }
5460       CounterUpdateRes =
5461           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5462       if (!CounterUpdateRes.isUsable()) {
5463         IsCorrect = false;
5464         continue;
5465       }
5466       OMPIteratorHelperData &HD = Helpers.emplace_back();
5467       HD.CounterVD = CounterVD;
5468       HD.Upper = Res.get();
5469       HD.Update = UpdateRes.get();
5470       HD.CounterUpdate = CounterUpdateRes.get();
5471     }
5472   } else {
5473     Helpers.assign(ID.size(), {});
5474   }
5475   if (!IsCorrect) {
5476     // Invalidate all created iterator declarations if error is found.
5477     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5478       if (Decl *ID = D.IteratorDecl)
5479         ID->setInvalidDecl();
5480     }
5481     return ExprError();
5482   }
5483   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5484                                  LLoc, RLoc, ID, Helpers);
5485 }
5486 
5487 ExprResult
5488 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5489                                       Expr *Idx, SourceLocation RLoc) {
5490   Expr *LHSExp = Base;
5491   Expr *RHSExp = Idx;
5492 
5493   ExprValueKind VK = VK_LValue;
5494   ExprObjectKind OK = OK_Ordinary;
5495 
5496   // Per C++ core issue 1213, the result is an xvalue if either operand is
5497   // a non-lvalue array, and an lvalue otherwise.
5498   if (getLangOpts().CPlusPlus11) {
5499     for (auto *Op : {LHSExp, RHSExp}) {
5500       Op = Op->IgnoreImplicit();
5501       if (Op->getType()->isArrayType() && !Op->isLValue())
5502         VK = VK_XValue;
5503     }
5504   }
5505 
5506   // Perform default conversions.
5507   if (!LHSExp->getType()->getAs<VectorType>()) {
5508     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5509     if (Result.isInvalid())
5510       return ExprError();
5511     LHSExp = Result.get();
5512   }
5513   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5514   if (Result.isInvalid())
5515     return ExprError();
5516   RHSExp = Result.get();
5517 
5518   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5519 
5520   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5521   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5522   // in the subscript position. As a result, we need to derive the array base
5523   // and index from the expression types.
5524   Expr *BaseExpr, *IndexExpr;
5525   QualType ResultType;
5526   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5527     BaseExpr = LHSExp;
5528     IndexExpr = RHSExp;
5529     ResultType =
5530         getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5531   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5532     BaseExpr = LHSExp;
5533     IndexExpr = RHSExp;
5534     ResultType = PTy->getPointeeType();
5535   } else if (const ObjCObjectPointerType *PTy =
5536                LHSTy->getAs<ObjCObjectPointerType>()) {
5537     BaseExpr = LHSExp;
5538     IndexExpr = RHSExp;
5539 
5540     // Use custom logic if this should be the pseudo-object subscript
5541     // expression.
5542     if (!LangOpts.isSubscriptPointerArithmetic())
5543       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5544                                           nullptr);
5545 
5546     ResultType = PTy->getPointeeType();
5547   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5548      // Handle the uncommon case of "123[Ptr]".
5549     BaseExpr = RHSExp;
5550     IndexExpr = LHSExp;
5551     ResultType = PTy->getPointeeType();
5552   } else if (const ObjCObjectPointerType *PTy =
5553                RHSTy->getAs<ObjCObjectPointerType>()) {
5554      // Handle the uncommon case of "123[Ptr]".
5555     BaseExpr = RHSExp;
5556     IndexExpr = LHSExp;
5557     ResultType = PTy->getPointeeType();
5558     if (!LangOpts.isSubscriptPointerArithmetic()) {
5559       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5560         << ResultType << BaseExpr->getSourceRange();
5561       return ExprError();
5562     }
5563   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5564     BaseExpr = LHSExp;    // vectors: V[123]
5565     IndexExpr = RHSExp;
5566     // We apply C++ DR1213 to vector subscripting too.
5567     if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5568       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5569       if (Materialized.isInvalid())
5570         return ExprError();
5571       LHSExp = Materialized.get();
5572     }
5573     VK = LHSExp->getValueKind();
5574     if (VK != VK_PRValue)
5575       OK = OK_VectorComponent;
5576 
5577     ResultType = VTy->getElementType();
5578     QualType BaseType = BaseExpr->getType();
5579     Qualifiers BaseQuals = BaseType.getQualifiers();
5580     Qualifiers MemberQuals = ResultType.getQualifiers();
5581     Qualifiers Combined = BaseQuals + MemberQuals;
5582     if (Combined != MemberQuals)
5583       ResultType = Context.getQualifiedType(ResultType, Combined);
5584   } else if (LHSTy->isArrayType()) {
5585     // If we see an array that wasn't promoted by
5586     // DefaultFunctionArrayLvalueConversion, it must be an array that
5587     // wasn't promoted because of the C90 rule that doesn't
5588     // allow promoting non-lvalue arrays.  Warn, then
5589     // force the promotion here.
5590     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5591         << LHSExp->getSourceRange();
5592     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5593                                CK_ArrayToPointerDecay).get();
5594     LHSTy = LHSExp->getType();
5595 
5596     BaseExpr = LHSExp;
5597     IndexExpr = RHSExp;
5598     ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5599   } else if (RHSTy->isArrayType()) {
5600     // Same as previous, except for 123[f().a] case
5601     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5602         << RHSExp->getSourceRange();
5603     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5604                                CK_ArrayToPointerDecay).get();
5605     RHSTy = RHSExp->getType();
5606 
5607     BaseExpr = RHSExp;
5608     IndexExpr = LHSExp;
5609     ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5610   } else {
5611     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5612        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5613   }
5614   // C99 6.5.2.1p1
5615   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5616     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5617                      << IndexExpr->getSourceRange());
5618 
5619   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5620        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5621          && !IndexExpr->isTypeDependent())
5622     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5623 
5624   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5625   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5626   // type. Note that Functions are not objects, and that (in C99 parlance)
5627   // incomplete types are not object types.
5628   if (ResultType->isFunctionType()) {
5629     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5630         << ResultType << BaseExpr->getSourceRange();
5631     return ExprError();
5632   }
5633 
5634   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5635     // GNU extension: subscripting on pointer to void
5636     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5637       << BaseExpr->getSourceRange();
5638 
5639     // C forbids expressions of unqualified void type from being l-values.
5640     // See IsCForbiddenLValueType.
5641     if (!ResultType.hasQualifiers())
5642       VK = VK_PRValue;
5643   } else if (!ResultType->isDependentType() &&
5644              RequireCompleteSizedType(
5645                  LLoc, ResultType,
5646                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5647     return ExprError();
5648 
5649   assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5650          !ResultType.isCForbiddenLValueType());
5651 
5652   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5653       FunctionScopes.size() > 1) {
5654     if (auto *TT =
5655             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5656       for (auto I = FunctionScopes.rbegin(),
5657                 E = std::prev(FunctionScopes.rend());
5658            I != E; ++I) {
5659         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5660         if (CSI == nullptr)
5661           break;
5662         DeclContext *DC = nullptr;
5663         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5664           DC = LSI->CallOperator;
5665         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5666           DC = CRSI->TheCapturedDecl;
5667         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5668           DC = BSI->TheDecl;
5669         if (DC) {
5670           if (DC->containsDecl(TT->getDecl()))
5671             break;
5672           captureVariablyModifiedType(
5673               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5674         }
5675       }
5676     }
5677   }
5678 
5679   return new (Context)
5680       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5681 }
5682 
5683 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5684                                   ParmVarDecl *Param) {
5685   if (Param->hasUnparsedDefaultArg()) {
5686     // If we've already cleared out the location for the default argument,
5687     // that means we're parsing it right now.
5688     if (!UnparsedDefaultArgLocs.count(Param)) {
5689       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5690       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5691       Param->setInvalidDecl();
5692       return true;
5693     }
5694 
5695     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5696         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5697     Diag(UnparsedDefaultArgLocs[Param],
5698          diag::note_default_argument_declared_here);
5699     return true;
5700   }
5701 
5702   if (Param->hasUninstantiatedDefaultArg() &&
5703       InstantiateDefaultArgument(CallLoc, FD, Param))
5704     return true;
5705 
5706   assert(Param->hasInit() && "default argument but no initializer?");
5707 
5708   // If the default expression creates temporaries, we need to
5709   // push them to the current stack of expression temporaries so they'll
5710   // be properly destroyed.
5711   // FIXME: We should really be rebuilding the default argument with new
5712   // bound temporaries; see the comment in PR5810.
5713   // We don't need to do that with block decls, though, because
5714   // blocks in default argument expression can never capture anything.
5715   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5716     // Set the "needs cleanups" bit regardless of whether there are
5717     // any explicit objects.
5718     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5719 
5720     // Append all the objects to the cleanup list.  Right now, this
5721     // should always be a no-op, because blocks in default argument
5722     // expressions should never be able to capture anything.
5723     assert(!Init->getNumObjects() &&
5724            "default argument expression has capturing blocks?");
5725   }
5726 
5727   // We already type-checked the argument, so we know it works.
5728   // Just mark all of the declarations in this potentially-evaluated expression
5729   // as being "referenced".
5730   EnterExpressionEvaluationContext EvalContext(
5731       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5732   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5733                                    /*SkipLocalVariables=*/true);
5734   return false;
5735 }
5736 
5737 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5738                                         FunctionDecl *FD, ParmVarDecl *Param) {
5739   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5740   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5741     return ExprError();
5742   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5743 }
5744 
5745 Sema::VariadicCallType
5746 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5747                           Expr *Fn) {
5748   if (Proto && Proto->isVariadic()) {
5749     if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5750       return VariadicConstructor;
5751     else if (Fn && Fn->getType()->isBlockPointerType())
5752       return VariadicBlock;
5753     else if (FDecl) {
5754       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5755         if (Method->isInstance())
5756           return VariadicMethod;
5757     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5758       return VariadicMethod;
5759     return VariadicFunction;
5760   }
5761   return VariadicDoesNotApply;
5762 }
5763 
5764 namespace {
5765 class FunctionCallCCC final : public FunctionCallFilterCCC {
5766 public:
5767   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5768                   unsigned NumArgs, MemberExpr *ME)
5769       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5770         FunctionName(FuncName) {}
5771 
5772   bool ValidateCandidate(const TypoCorrection &candidate) override {
5773     if (!candidate.getCorrectionSpecifier() ||
5774         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5775       return false;
5776     }
5777 
5778     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5779   }
5780 
5781   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5782     return std::make_unique<FunctionCallCCC>(*this);
5783   }
5784 
5785 private:
5786   const IdentifierInfo *const FunctionName;
5787 };
5788 }
5789 
5790 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5791                                                FunctionDecl *FDecl,
5792                                                ArrayRef<Expr *> Args) {
5793   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5794   DeclarationName FuncName = FDecl->getDeclName();
5795   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5796 
5797   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5798   if (TypoCorrection Corrected = S.CorrectTypo(
5799           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5800           S.getScopeForContext(S.CurContext), nullptr, CCC,
5801           Sema::CTK_ErrorRecovery)) {
5802     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5803       if (Corrected.isOverloaded()) {
5804         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5805         OverloadCandidateSet::iterator Best;
5806         for (NamedDecl *CD : Corrected) {
5807           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5808             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5809                                    OCS);
5810         }
5811         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5812         case OR_Success:
5813           ND = Best->FoundDecl;
5814           Corrected.setCorrectionDecl(ND);
5815           break;
5816         default:
5817           break;
5818         }
5819       }
5820       ND = ND->getUnderlyingDecl();
5821       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5822         return Corrected;
5823     }
5824   }
5825   return TypoCorrection();
5826 }
5827 
5828 /// ConvertArgumentsForCall - Converts the arguments specified in
5829 /// Args/NumArgs to the parameter types of the function FDecl with
5830 /// function prototype Proto. Call is the call expression itself, and
5831 /// Fn is the function expression. For a C++ member function, this
5832 /// routine does not attempt to convert the object argument. Returns
5833 /// true if the call is ill-formed.
5834 bool
5835 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5836                               FunctionDecl *FDecl,
5837                               const FunctionProtoType *Proto,
5838                               ArrayRef<Expr *> Args,
5839                               SourceLocation RParenLoc,
5840                               bool IsExecConfig) {
5841   // Bail out early if calling a builtin with custom typechecking.
5842   if (FDecl)
5843     if (unsigned ID = FDecl->getBuiltinID())
5844       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5845         return false;
5846 
5847   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5848   // assignment, to the types of the corresponding parameter, ...
5849   unsigned NumParams = Proto->getNumParams();
5850   bool Invalid = false;
5851   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5852   unsigned FnKind = Fn->getType()->isBlockPointerType()
5853                        ? 1 /* block */
5854                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5855                                        : 0 /* function */);
5856 
5857   // If too few arguments are available (and we don't have default
5858   // arguments for the remaining parameters), don't make the call.
5859   if (Args.size() < NumParams) {
5860     if (Args.size() < MinArgs) {
5861       TypoCorrection TC;
5862       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5863         unsigned diag_id =
5864             MinArgs == NumParams && !Proto->isVariadic()
5865                 ? diag::err_typecheck_call_too_few_args_suggest
5866                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5867         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5868                                         << static_cast<unsigned>(Args.size())
5869                                         << TC.getCorrectionRange());
5870       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5871         Diag(RParenLoc,
5872              MinArgs == NumParams && !Proto->isVariadic()
5873                  ? diag::err_typecheck_call_too_few_args_one
5874                  : diag::err_typecheck_call_too_few_args_at_least_one)
5875             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5876       else
5877         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5878                             ? diag::err_typecheck_call_too_few_args
5879                             : diag::err_typecheck_call_too_few_args_at_least)
5880             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5881             << Fn->getSourceRange();
5882 
5883       // Emit the location of the prototype.
5884       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5885         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5886 
5887       return true;
5888     }
5889     // We reserve space for the default arguments when we create
5890     // the call expression, before calling ConvertArgumentsForCall.
5891     assert((Call->getNumArgs() == NumParams) &&
5892            "We should have reserved space for the default arguments before!");
5893   }
5894 
5895   // If too many are passed and not variadic, error on the extras and drop
5896   // them.
5897   if (Args.size() > NumParams) {
5898     if (!Proto->isVariadic()) {
5899       TypoCorrection TC;
5900       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5901         unsigned diag_id =
5902             MinArgs == NumParams && !Proto->isVariadic()
5903                 ? diag::err_typecheck_call_too_many_args_suggest
5904                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5905         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5906                                         << static_cast<unsigned>(Args.size())
5907                                         << TC.getCorrectionRange());
5908       } else if (NumParams == 1 && FDecl &&
5909                  FDecl->getParamDecl(0)->getDeclName())
5910         Diag(Args[NumParams]->getBeginLoc(),
5911              MinArgs == NumParams
5912                  ? diag::err_typecheck_call_too_many_args_one
5913                  : diag::err_typecheck_call_too_many_args_at_most_one)
5914             << FnKind << FDecl->getParamDecl(0)
5915             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5916             << SourceRange(Args[NumParams]->getBeginLoc(),
5917                            Args.back()->getEndLoc());
5918       else
5919         Diag(Args[NumParams]->getBeginLoc(),
5920              MinArgs == NumParams
5921                  ? diag::err_typecheck_call_too_many_args
5922                  : diag::err_typecheck_call_too_many_args_at_most)
5923             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5924             << Fn->getSourceRange()
5925             << SourceRange(Args[NumParams]->getBeginLoc(),
5926                            Args.back()->getEndLoc());
5927 
5928       // Emit the location of the prototype.
5929       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5930         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5931 
5932       // This deletes the extra arguments.
5933       Call->shrinkNumArgs(NumParams);
5934       return true;
5935     }
5936   }
5937   SmallVector<Expr *, 8> AllArgs;
5938   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5939 
5940   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5941                                    AllArgs, CallType);
5942   if (Invalid)
5943     return true;
5944   unsigned TotalNumArgs = AllArgs.size();
5945   for (unsigned i = 0; i < TotalNumArgs; ++i)
5946     Call->setArg(i, AllArgs[i]);
5947 
5948   Call->computeDependence();
5949   return false;
5950 }
5951 
5952 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5953                                   const FunctionProtoType *Proto,
5954                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5955                                   SmallVectorImpl<Expr *> &AllArgs,
5956                                   VariadicCallType CallType, bool AllowExplicit,
5957                                   bool IsListInitialization) {
5958   unsigned NumParams = Proto->getNumParams();
5959   bool Invalid = false;
5960   size_t ArgIx = 0;
5961   // Continue to check argument types (even if we have too few/many args).
5962   for (unsigned i = FirstParam; i < NumParams; i++) {
5963     QualType ProtoArgType = Proto->getParamType(i);
5964 
5965     Expr *Arg;
5966     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5967     if (ArgIx < Args.size()) {
5968       Arg = Args[ArgIx++];
5969 
5970       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5971                               diag::err_call_incomplete_argument, Arg))
5972         return true;
5973 
5974       // Strip the unbridged-cast placeholder expression off, if applicable.
5975       bool CFAudited = false;
5976       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5977           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5978           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5979         Arg = stripARCUnbridgedCast(Arg);
5980       else if (getLangOpts().ObjCAutoRefCount &&
5981                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5982                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5983         CFAudited = true;
5984 
5985       if (Proto->getExtParameterInfo(i).isNoEscape() &&
5986           ProtoArgType->isBlockPointerType())
5987         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5988           BE->getBlockDecl()->setDoesNotEscape();
5989 
5990       InitializedEntity Entity =
5991           Param ? InitializedEntity::InitializeParameter(Context, Param,
5992                                                          ProtoArgType)
5993                 : InitializedEntity::InitializeParameter(
5994                       Context, ProtoArgType, Proto->isParamConsumed(i));
5995 
5996       // Remember that parameter belongs to a CF audited API.
5997       if (CFAudited)
5998         Entity.setParameterCFAudited();
5999 
6000       ExprResult ArgE = PerformCopyInitialization(
6001           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6002       if (ArgE.isInvalid())
6003         return true;
6004 
6005       Arg = ArgE.getAs<Expr>();
6006     } else {
6007       assert(Param && "can't use default arguments without a known callee");
6008 
6009       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6010       if (ArgExpr.isInvalid())
6011         return true;
6012 
6013       Arg = ArgExpr.getAs<Expr>();
6014     }
6015 
6016     // Check for array bounds violations for each argument to the call. This
6017     // check only triggers warnings when the argument isn't a more complex Expr
6018     // with its own checking, such as a BinaryOperator.
6019     CheckArrayAccess(Arg);
6020 
6021     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6022     CheckStaticArrayArgument(CallLoc, Param, Arg);
6023 
6024     AllArgs.push_back(Arg);
6025   }
6026 
6027   // If this is a variadic call, handle args passed through "...".
6028   if (CallType != VariadicDoesNotApply) {
6029     // Assume that extern "C" functions with variadic arguments that
6030     // return __unknown_anytype aren't *really* variadic.
6031     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6032         FDecl->isExternC()) {
6033       for (Expr *A : Args.slice(ArgIx)) {
6034         QualType paramType; // ignored
6035         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6036         Invalid |= arg.isInvalid();
6037         AllArgs.push_back(arg.get());
6038       }
6039 
6040     // Otherwise do argument promotion, (C99 6.5.2.2p7).
6041     } else {
6042       for (Expr *A : Args.slice(ArgIx)) {
6043         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6044         Invalid |= Arg.isInvalid();
6045         AllArgs.push_back(Arg.get());
6046       }
6047     }
6048 
6049     // Check for array bounds violations.
6050     for (Expr *A : Args.slice(ArgIx))
6051       CheckArrayAccess(A);
6052   }
6053   return Invalid;
6054 }
6055 
6056 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6057   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6058   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6059     TL = DTL.getOriginalLoc();
6060   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6061     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6062       << ATL.getLocalSourceRange();
6063 }
6064 
6065 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6066 /// array parameter, check that it is non-null, and that if it is formed by
6067 /// array-to-pointer decay, the underlying array is sufficiently large.
6068 ///
6069 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6070 /// array type derivation, then for each call to the function, the value of the
6071 /// corresponding actual argument shall provide access to the first element of
6072 /// an array with at least as many elements as specified by the size expression.
6073 void
6074 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6075                                ParmVarDecl *Param,
6076                                const Expr *ArgExpr) {
6077   // Static array parameters are not supported in C++.
6078   if (!Param || getLangOpts().CPlusPlus)
6079     return;
6080 
6081   QualType OrigTy = Param->getOriginalType();
6082 
6083   const ArrayType *AT = Context.getAsArrayType(OrigTy);
6084   if (!AT || AT->getSizeModifier() != ArrayType::Static)
6085     return;
6086 
6087   if (ArgExpr->isNullPointerConstant(Context,
6088                                      Expr::NPC_NeverValueDependent)) {
6089     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6090     DiagnoseCalleeStaticArrayParam(*this, Param);
6091     return;
6092   }
6093 
6094   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6095   if (!CAT)
6096     return;
6097 
6098   const ConstantArrayType *ArgCAT =
6099     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6100   if (!ArgCAT)
6101     return;
6102 
6103   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6104                                              ArgCAT->getElementType())) {
6105     if (ArgCAT->getSize().ult(CAT->getSize())) {
6106       Diag(CallLoc, diag::warn_static_array_too_small)
6107           << ArgExpr->getSourceRange()
6108           << (unsigned)ArgCAT->getSize().getZExtValue()
6109           << (unsigned)CAT->getSize().getZExtValue() << 0;
6110       DiagnoseCalleeStaticArrayParam(*this, Param);
6111     }
6112     return;
6113   }
6114 
6115   Optional<CharUnits> ArgSize =
6116       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6117   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6118   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6119     Diag(CallLoc, diag::warn_static_array_too_small)
6120         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6121         << (unsigned)ParmSize->getQuantity() << 1;
6122     DiagnoseCalleeStaticArrayParam(*this, Param);
6123   }
6124 }
6125 
6126 /// Given a function expression of unknown-any type, try to rebuild it
6127 /// to have a function type.
6128 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6129 
6130 /// Is the given type a placeholder that we need to lower out
6131 /// immediately during argument processing?
6132 static bool isPlaceholderToRemoveAsArg(QualType type) {
6133   // Placeholders are never sugared.
6134   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6135   if (!placeholder) return false;
6136 
6137   switch (placeholder->getKind()) {
6138   // Ignore all the non-placeholder types.
6139 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6140   case BuiltinType::Id:
6141 #include "clang/Basic/OpenCLImageTypes.def"
6142 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6143   case BuiltinType::Id:
6144 #include "clang/Basic/OpenCLExtensionTypes.def"
6145   // In practice we'll never use this, since all SVE types are sugared
6146   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6147 #define SVE_TYPE(Name, Id, SingletonId) \
6148   case BuiltinType::Id:
6149 #include "clang/Basic/AArch64SVEACLETypes.def"
6150 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6151   case BuiltinType::Id:
6152 #include "clang/Basic/PPCTypes.def"
6153 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6154 #include "clang/Basic/RISCVVTypes.def"
6155 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6156 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6157 #include "clang/AST/BuiltinTypes.def"
6158     return false;
6159 
6160   // We cannot lower out overload sets; they might validly be resolved
6161   // by the call machinery.
6162   case BuiltinType::Overload:
6163     return false;
6164 
6165   // Unbridged casts in ARC can be handled in some call positions and
6166   // should be left in place.
6167   case BuiltinType::ARCUnbridgedCast:
6168     return false;
6169 
6170   // Pseudo-objects should be converted as soon as possible.
6171   case BuiltinType::PseudoObject:
6172     return true;
6173 
6174   // The debugger mode could theoretically but currently does not try
6175   // to resolve unknown-typed arguments based on known parameter types.
6176   case BuiltinType::UnknownAny:
6177     return true;
6178 
6179   // These are always invalid as call arguments and should be reported.
6180   case BuiltinType::BoundMember:
6181   case BuiltinType::BuiltinFn:
6182   case BuiltinType::IncompleteMatrixIdx:
6183   case BuiltinType::OMPArraySection:
6184   case BuiltinType::OMPArrayShaping:
6185   case BuiltinType::OMPIterator:
6186     return true;
6187 
6188   }
6189   llvm_unreachable("bad builtin type kind");
6190 }
6191 
6192 /// Check an argument list for placeholders that we won't try to
6193 /// handle later.
6194 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6195   // Apply this processing to all the arguments at once instead of
6196   // dying at the first failure.
6197   bool hasInvalid = false;
6198   for (size_t i = 0, e = args.size(); i != e; i++) {
6199     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6200       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6201       if (result.isInvalid()) hasInvalid = true;
6202       else args[i] = result.get();
6203     }
6204   }
6205   return hasInvalid;
6206 }
6207 
6208 /// If a builtin function has a pointer argument with no explicit address
6209 /// space, then it should be able to accept a pointer to any address
6210 /// space as input.  In order to do this, we need to replace the
6211 /// standard builtin declaration with one that uses the same address space
6212 /// as the call.
6213 ///
6214 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6215 ///                  it does not contain any pointer arguments without
6216 ///                  an address space qualifer.  Otherwise the rewritten
6217 ///                  FunctionDecl is returned.
6218 /// TODO: Handle pointer return types.
6219 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6220                                                 FunctionDecl *FDecl,
6221                                                 MultiExprArg ArgExprs) {
6222 
6223   QualType DeclType = FDecl->getType();
6224   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6225 
6226   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6227       ArgExprs.size() < FT->getNumParams())
6228     return nullptr;
6229 
6230   bool NeedsNewDecl = false;
6231   unsigned i = 0;
6232   SmallVector<QualType, 8> OverloadParams;
6233 
6234   for (QualType ParamType : FT->param_types()) {
6235 
6236     // Convert array arguments to pointer to simplify type lookup.
6237     ExprResult ArgRes =
6238         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6239     if (ArgRes.isInvalid())
6240       return nullptr;
6241     Expr *Arg = ArgRes.get();
6242     QualType ArgType = Arg->getType();
6243     if (!ParamType->isPointerType() ||
6244         ParamType.hasAddressSpace() ||
6245         !ArgType->isPointerType() ||
6246         !ArgType->getPointeeType().hasAddressSpace()) {
6247       OverloadParams.push_back(ParamType);
6248       continue;
6249     }
6250 
6251     QualType PointeeType = ParamType->getPointeeType();
6252     if (PointeeType.hasAddressSpace())
6253       continue;
6254 
6255     NeedsNewDecl = true;
6256     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6257 
6258     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6259     OverloadParams.push_back(Context.getPointerType(PointeeType));
6260   }
6261 
6262   if (!NeedsNewDecl)
6263     return nullptr;
6264 
6265   FunctionProtoType::ExtProtoInfo EPI;
6266   EPI.Variadic = FT->isVariadic();
6267   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6268                                                 OverloadParams, EPI);
6269   DeclContext *Parent = FDecl->getParent();
6270   FunctionDecl *OverloadDecl = FunctionDecl::Create(
6271       Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6272       FDecl->getIdentifier(), OverloadTy,
6273       /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6274       false,
6275       /*hasPrototype=*/true);
6276   SmallVector<ParmVarDecl*, 16> Params;
6277   FT = cast<FunctionProtoType>(OverloadTy);
6278   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6279     QualType ParamType = FT->getParamType(i);
6280     ParmVarDecl *Parm =
6281         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6282                                 SourceLocation(), nullptr, ParamType,
6283                                 /*TInfo=*/nullptr, SC_None, nullptr);
6284     Parm->setScopeInfo(0, i);
6285     Params.push_back(Parm);
6286   }
6287   OverloadDecl->setParams(Params);
6288   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6289   return OverloadDecl;
6290 }
6291 
6292 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6293                                     FunctionDecl *Callee,
6294                                     MultiExprArg ArgExprs) {
6295   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6296   // similar attributes) really don't like it when functions are called with an
6297   // invalid number of args.
6298   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6299                          /*PartialOverloading=*/false) &&
6300       !Callee->isVariadic())
6301     return;
6302   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6303     return;
6304 
6305   if (const EnableIfAttr *Attr =
6306           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6307     S.Diag(Fn->getBeginLoc(),
6308            isa<CXXMethodDecl>(Callee)
6309                ? diag::err_ovl_no_viable_member_function_in_call
6310                : diag::err_ovl_no_viable_function_in_call)
6311         << Callee << Callee->getSourceRange();
6312     S.Diag(Callee->getLocation(),
6313            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6314         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6315     return;
6316   }
6317 }
6318 
6319 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6320     const UnresolvedMemberExpr *const UME, Sema &S) {
6321 
6322   const auto GetFunctionLevelDCIfCXXClass =
6323       [](Sema &S) -> const CXXRecordDecl * {
6324     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6325     if (!DC || !DC->getParent())
6326       return nullptr;
6327 
6328     // If the call to some member function was made from within a member
6329     // function body 'M' return return 'M's parent.
6330     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6331       return MD->getParent()->getCanonicalDecl();
6332     // else the call was made from within a default member initializer of a
6333     // class, so return the class.
6334     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6335       return RD->getCanonicalDecl();
6336     return nullptr;
6337   };
6338   // If our DeclContext is neither a member function nor a class (in the
6339   // case of a lambda in a default member initializer), we can't have an
6340   // enclosing 'this'.
6341 
6342   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6343   if (!CurParentClass)
6344     return false;
6345 
6346   // The naming class for implicit member functions call is the class in which
6347   // name lookup starts.
6348   const CXXRecordDecl *const NamingClass =
6349       UME->getNamingClass()->getCanonicalDecl();
6350   assert(NamingClass && "Must have naming class even for implicit access");
6351 
6352   // If the unresolved member functions were found in a 'naming class' that is
6353   // related (either the same or derived from) to the class that contains the
6354   // member function that itself contained the implicit member access.
6355 
6356   return CurParentClass == NamingClass ||
6357          CurParentClass->isDerivedFrom(NamingClass);
6358 }
6359 
6360 static void
6361 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6362     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6363 
6364   if (!UME)
6365     return;
6366 
6367   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6368   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6369   // already been captured, or if this is an implicit member function call (if
6370   // it isn't, an attempt to capture 'this' should already have been made).
6371   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6372       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6373     return;
6374 
6375   // Check if the naming class in which the unresolved members were found is
6376   // related (same as or is a base of) to the enclosing class.
6377 
6378   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6379     return;
6380 
6381 
6382   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6383   // If the enclosing function is not dependent, then this lambda is
6384   // capture ready, so if we can capture this, do so.
6385   if (!EnclosingFunctionCtx->isDependentContext()) {
6386     // If the current lambda and all enclosing lambdas can capture 'this' -
6387     // then go ahead and capture 'this' (since our unresolved overload set
6388     // contains at least one non-static member function).
6389     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6390       S.CheckCXXThisCapture(CallLoc);
6391   } else if (S.CurContext->isDependentContext()) {
6392     // ... since this is an implicit member reference, that might potentially
6393     // involve a 'this' capture, mark 'this' for potential capture in
6394     // enclosing lambdas.
6395     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6396       CurLSI->addPotentialThisCapture(CallLoc);
6397   }
6398 }
6399 
6400 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6401                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6402                                Expr *ExecConfig) {
6403   ExprResult Call =
6404       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6405                     /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6406   if (Call.isInvalid())
6407     return Call;
6408 
6409   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6410   // language modes.
6411   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6412     if (ULE->hasExplicitTemplateArgs() &&
6413         ULE->decls_begin() == ULE->decls_end()) {
6414       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6415                                  ? diag::warn_cxx17_compat_adl_only_template_id
6416                                  : diag::ext_adl_only_template_id)
6417           << ULE->getName();
6418     }
6419   }
6420 
6421   if (LangOpts.OpenMP)
6422     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6423                            ExecConfig);
6424 
6425   return Call;
6426 }
6427 
6428 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6429 /// This provides the location of the left/right parens and a list of comma
6430 /// locations.
6431 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6432                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6433                                Expr *ExecConfig, bool IsExecConfig,
6434                                bool AllowRecovery) {
6435   // Since this might be a postfix expression, get rid of ParenListExprs.
6436   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6437   if (Result.isInvalid()) return ExprError();
6438   Fn = Result.get();
6439 
6440   if (checkArgsForPlaceholders(*this, ArgExprs))
6441     return ExprError();
6442 
6443   if (getLangOpts().CPlusPlus) {
6444     // If this is a pseudo-destructor expression, build the call immediately.
6445     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6446       if (!ArgExprs.empty()) {
6447         // Pseudo-destructor calls should not have any arguments.
6448         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6449             << FixItHint::CreateRemoval(
6450                    SourceRange(ArgExprs.front()->getBeginLoc(),
6451                                ArgExprs.back()->getEndLoc()));
6452       }
6453 
6454       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6455                               VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6456     }
6457     if (Fn->getType() == Context.PseudoObjectTy) {
6458       ExprResult result = CheckPlaceholderExpr(Fn);
6459       if (result.isInvalid()) return ExprError();
6460       Fn = result.get();
6461     }
6462 
6463     // Determine whether this is a dependent call inside a C++ template,
6464     // in which case we won't do any semantic analysis now.
6465     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6466       if (ExecConfig) {
6467         return CUDAKernelCallExpr::Create(Context, Fn,
6468                                           cast<CallExpr>(ExecConfig), ArgExprs,
6469                                           Context.DependentTy, VK_PRValue,
6470                                           RParenLoc, CurFPFeatureOverrides());
6471       } else {
6472 
6473         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6474             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6475             Fn->getBeginLoc());
6476 
6477         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6478                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6479       }
6480     }
6481 
6482     // Determine whether this is a call to an object (C++ [over.call.object]).
6483     if (Fn->getType()->isRecordType())
6484       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6485                                           RParenLoc);
6486 
6487     if (Fn->getType() == Context.UnknownAnyTy) {
6488       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6489       if (result.isInvalid()) return ExprError();
6490       Fn = result.get();
6491     }
6492 
6493     if (Fn->getType() == Context.BoundMemberTy) {
6494       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6495                                        RParenLoc, ExecConfig, IsExecConfig,
6496                                        AllowRecovery);
6497     }
6498   }
6499 
6500   // Check for overloaded calls.  This can happen even in C due to extensions.
6501   if (Fn->getType() == Context.OverloadTy) {
6502     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6503 
6504     // We aren't supposed to apply this logic if there's an '&' involved.
6505     if (!find.HasFormOfMemberPointer) {
6506       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6507         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6508                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6509       OverloadExpr *ovl = find.Expression;
6510       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6511         return BuildOverloadedCallExpr(
6512             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6513             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6514       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6515                                        RParenLoc, ExecConfig, IsExecConfig,
6516                                        AllowRecovery);
6517     }
6518   }
6519 
6520   // If we're directly calling a function, get the appropriate declaration.
6521   if (Fn->getType() == Context.UnknownAnyTy) {
6522     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6523     if (result.isInvalid()) return ExprError();
6524     Fn = result.get();
6525   }
6526 
6527   Expr *NakedFn = Fn->IgnoreParens();
6528 
6529   bool CallingNDeclIndirectly = false;
6530   NamedDecl *NDecl = nullptr;
6531   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6532     if (UnOp->getOpcode() == UO_AddrOf) {
6533       CallingNDeclIndirectly = true;
6534       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6535     }
6536   }
6537 
6538   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6539     NDecl = DRE->getDecl();
6540 
6541     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6542     if (FDecl && FDecl->getBuiltinID()) {
6543       // Rewrite the function decl for this builtin by replacing parameters
6544       // with no explicit address space with the address space of the arguments
6545       // in ArgExprs.
6546       if ((FDecl =
6547                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6548         NDecl = FDecl;
6549         Fn = DeclRefExpr::Create(
6550             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6551             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6552             nullptr, DRE->isNonOdrUse());
6553       }
6554     }
6555   } else if (isa<MemberExpr>(NakedFn))
6556     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6557 
6558   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6559     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6560                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6561       return ExprError();
6562 
6563     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6564 
6565     // If this expression is a call to a builtin function in HIP device
6566     // compilation, allow a pointer-type argument to default address space to be
6567     // passed as a pointer-type parameter to a non-default address space.
6568     // If Arg is declared in the default address space and Param is declared
6569     // in a non-default address space, perform an implicit address space cast to
6570     // the parameter type.
6571     if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6572         FD->getBuiltinID()) {
6573       for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6574         ParmVarDecl *Param = FD->getParamDecl(Idx);
6575         if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6576             !ArgExprs[Idx]->getType()->isPointerType())
6577           continue;
6578 
6579         auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6580         auto ArgTy = ArgExprs[Idx]->getType();
6581         auto ArgPtTy = ArgTy->getPointeeType();
6582         auto ArgAS = ArgPtTy.getAddressSpace();
6583 
6584         // Add address space cast if target address spaces are different
6585         bool NeedImplicitASC =
6586           ParamAS != LangAS::Default &&       // Pointer params in generic AS don't need special handling.
6587           ( ArgAS == LangAS::Default  ||      // We do allow implicit conversion from generic AS
6588                                               // or from specific AS which has target AS matching that of Param.
6589           getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
6590         if (!NeedImplicitASC)
6591           continue;
6592 
6593         // First, ensure that the Arg is an RValue.
6594         if (ArgExprs[Idx]->isGLValue()) {
6595           ArgExprs[Idx] = ImplicitCastExpr::Create(
6596               Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6597               nullptr, VK_PRValue, FPOptionsOverride());
6598         }
6599 
6600         // Construct a new arg type with address space of Param
6601         Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6602         ArgPtQuals.setAddressSpace(ParamAS);
6603         auto NewArgPtTy =
6604             Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6605         auto NewArgTy =
6606             Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6607                                      ArgTy.getQualifiers());
6608 
6609         // Finally perform an implicit address space cast
6610         ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6611                                           CK_AddressSpaceConversion)
6612                             .get();
6613       }
6614     }
6615   }
6616 
6617   if (Context.isDependenceAllowed() &&
6618       (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6619     assert(!getLangOpts().CPlusPlus);
6620     assert((Fn->containsErrors() ||
6621             llvm::any_of(ArgExprs,
6622                          [](clang::Expr *E) { return E->containsErrors(); })) &&
6623            "should only occur in error-recovery path.");
6624     QualType ReturnType =
6625         llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6626             ? cast<FunctionDecl>(NDecl)->getCallResultType()
6627             : Context.DependentTy;
6628     return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6629                             Expr::getValueKindForType(ReturnType), RParenLoc,
6630                             CurFPFeatureOverrides());
6631   }
6632   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6633                                ExecConfig, IsExecConfig);
6634 }
6635 
6636 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6637 //  with the specified CallArgs
6638 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6639                                  MultiExprArg CallArgs) {
6640   StringRef Name = Context.BuiltinInfo.getName(Id);
6641   LookupResult R(*this, &Context.Idents.get(Name), Loc,
6642                  Sema::LookupOrdinaryName);
6643   LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6644 
6645   auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6646   assert(BuiltInDecl && "failed to find builtin declaration");
6647 
6648   ExprResult DeclRef =
6649       BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6650   assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6651 
6652   ExprResult Call =
6653       BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6654 
6655   assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6656   return Call.get();
6657 }
6658 
6659 /// Parse a __builtin_astype expression.
6660 ///
6661 /// __builtin_astype( value, dst type )
6662 ///
6663 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6664                                  SourceLocation BuiltinLoc,
6665                                  SourceLocation RParenLoc) {
6666   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6667   return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6668 }
6669 
6670 /// Create a new AsTypeExpr node (bitcast) from the arguments.
6671 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6672                                  SourceLocation BuiltinLoc,
6673                                  SourceLocation RParenLoc) {
6674   ExprValueKind VK = VK_PRValue;
6675   ExprObjectKind OK = OK_Ordinary;
6676   QualType SrcTy = E->getType();
6677   if (!SrcTy->isDependentType() &&
6678       Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6679     return ExprError(
6680         Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6681         << DestTy << SrcTy << E->getSourceRange());
6682   return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6683 }
6684 
6685 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6686 /// provided arguments.
6687 ///
6688 /// __builtin_convertvector( value, dst type )
6689 ///
6690 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6691                                         SourceLocation BuiltinLoc,
6692                                         SourceLocation RParenLoc) {
6693   TypeSourceInfo *TInfo;
6694   GetTypeFromParser(ParsedDestTy, &TInfo);
6695   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6696 }
6697 
6698 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6699 /// i.e. an expression not of \p OverloadTy.  The expression should
6700 /// unary-convert to an expression of function-pointer or
6701 /// block-pointer type.
6702 ///
6703 /// \param NDecl the declaration being called, if available
6704 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6705                                        SourceLocation LParenLoc,
6706                                        ArrayRef<Expr *> Args,
6707                                        SourceLocation RParenLoc, Expr *Config,
6708                                        bool IsExecConfig, ADLCallKind UsesADL) {
6709   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6710   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6711 
6712   // Functions with 'interrupt' attribute cannot be called directly.
6713   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6714     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6715     return ExprError();
6716   }
6717 
6718   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6719   // so there's some risk when calling out to non-interrupt handler functions
6720   // that the callee might not preserve them. This is easy to diagnose here,
6721   // but can be very challenging to debug.
6722   // Likewise, X86 interrupt handlers may only call routines with attribute
6723   // no_caller_saved_registers since there is no efficient way to
6724   // save and restore the non-GPR state.
6725   if (auto *Caller = getCurFunctionDecl()) {
6726     if (Caller->hasAttr<ARMInterruptAttr>()) {
6727       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6728       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6729         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6730         if (FDecl)
6731           Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6732       }
6733     }
6734     if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6735         ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6736       Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6737       if (FDecl)
6738         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6739     }
6740   }
6741 
6742   // Promote the function operand.
6743   // We special-case function promotion here because we only allow promoting
6744   // builtin functions to function pointers in the callee of a call.
6745   ExprResult Result;
6746   QualType ResultTy;
6747   if (BuiltinID &&
6748       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6749     // Extract the return type from the (builtin) function pointer type.
6750     // FIXME Several builtins still have setType in
6751     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6752     // Builtins.def to ensure they are correct before removing setType calls.
6753     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6754     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6755     ResultTy = FDecl->getCallResultType();
6756   } else {
6757     Result = CallExprUnaryConversions(Fn);
6758     ResultTy = Context.BoolTy;
6759   }
6760   if (Result.isInvalid())
6761     return ExprError();
6762   Fn = Result.get();
6763 
6764   // Check for a valid function type, but only if it is not a builtin which
6765   // requires custom type checking. These will be handled by
6766   // CheckBuiltinFunctionCall below just after creation of the call expression.
6767   const FunctionType *FuncT = nullptr;
6768   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6769   retry:
6770     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6771       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6772       // have type pointer to function".
6773       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6774       if (!FuncT)
6775         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6776                          << Fn->getType() << Fn->getSourceRange());
6777     } else if (const BlockPointerType *BPT =
6778                    Fn->getType()->getAs<BlockPointerType>()) {
6779       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6780     } else {
6781       // Handle calls to expressions of unknown-any type.
6782       if (Fn->getType() == Context.UnknownAnyTy) {
6783         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6784         if (rewrite.isInvalid())
6785           return ExprError();
6786         Fn = rewrite.get();
6787         goto retry;
6788       }
6789 
6790       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6791                        << Fn->getType() << Fn->getSourceRange());
6792     }
6793   }
6794 
6795   // Get the number of parameters in the function prototype, if any.
6796   // We will allocate space for max(Args.size(), NumParams) arguments
6797   // in the call expression.
6798   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6799   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6800 
6801   CallExpr *TheCall;
6802   if (Config) {
6803     assert(UsesADL == ADLCallKind::NotADL &&
6804            "CUDAKernelCallExpr should not use ADL");
6805     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6806                                          Args, ResultTy, VK_PRValue, RParenLoc,
6807                                          CurFPFeatureOverrides(), NumParams);
6808   } else {
6809     TheCall =
6810         CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6811                          CurFPFeatureOverrides(), NumParams, UsesADL);
6812   }
6813 
6814   if (!Context.isDependenceAllowed()) {
6815     // Forget about the nulled arguments since typo correction
6816     // do not handle them well.
6817     TheCall->shrinkNumArgs(Args.size());
6818     // C cannot always handle TypoExpr nodes in builtin calls and direct
6819     // function calls as their argument checking don't necessarily handle
6820     // dependent types properly, so make sure any TypoExprs have been
6821     // dealt with.
6822     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6823     if (!Result.isUsable()) return ExprError();
6824     CallExpr *TheOldCall = TheCall;
6825     TheCall = dyn_cast<CallExpr>(Result.get());
6826     bool CorrectedTypos = TheCall != TheOldCall;
6827     if (!TheCall) return Result;
6828     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6829 
6830     // A new call expression node was created if some typos were corrected.
6831     // However it may not have been constructed with enough storage. In this
6832     // case, rebuild the node with enough storage. The waste of space is
6833     // immaterial since this only happens when some typos were corrected.
6834     if (CorrectedTypos && Args.size() < NumParams) {
6835       if (Config)
6836         TheCall = CUDAKernelCallExpr::Create(
6837             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6838             RParenLoc, CurFPFeatureOverrides(), NumParams);
6839       else
6840         TheCall =
6841             CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6842                              CurFPFeatureOverrides(), NumParams, UsesADL);
6843     }
6844     // We can now handle the nulled arguments for the default arguments.
6845     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6846   }
6847 
6848   // Bail out early if calling a builtin with custom type checking.
6849   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6850     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6851 
6852   if (getLangOpts().CUDA) {
6853     if (Config) {
6854       // CUDA: Kernel calls must be to global functions
6855       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6856         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6857             << FDecl << Fn->getSourceRange());
6858 
6859       // CUDA: Kernel function must have 'void' return type
6860       if (!FuncT->getReturnType()->isVoidType() &&
6861           !FuncT->getReturnType()->getAs<AutoType>() &&
6862           !FuncT->getReturnType()->isInstantiationDependentType())
6863         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6864             << Fn->getType() << Fn->getSourceRange());
6865     } else {
6866       // CUDA: Calls to global functions must be configured
6867       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6868         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6869             << FDecl << Fn->getSourceRange());
6870     }
6871   }
6872 
6873   // Check for a valid return type
6874   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6875                           FDecl))
6876     return ExprError();
6877 
6878   // We know the result type of the call, set it.
6879   TheCall->setType(FuncT->getCallResultType(Context));
6880   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6881 
6882   if (Proto) {
6883     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6884                                 IsExecConfig))
6885       return ExprError();
6886   } else {
6887     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6888 
6889     if (FDecl) {
6890       // Check if we have too few/too many template arguments, based
6891       // on our knowledge of the function definition.
6892       const FunctionDecl *Def = nullptr;
6893       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6894         Proto = Def->getType()->getAs<FunctionProtoType>();
6895        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6896           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6897           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6898       }
6899 
6900       // If the function we're calling isn't a function prototype, but we have
6901       // a function prototype from a prior declaratiom, use that prototype.
6902       if (!FDecl->hasPrototype())
6903         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6904     }
6905 
6906     // Promote the arguments (C99 6.5.2.2p6).
6907     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6908       Expr *Arg = Args[i];
6909 
6910       if (Proto && i < Proto->getNumParams()) {
6911         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6912             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6913         ExprResult ArgE =
6914             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6915         if (ArgE.isInvalid())
6916           return true;
6917 
6918         Arg = ArgE.getAs<Expr>();
6919 
6920       } else {
6921         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6922 
6923         if (ArgE.isInvalid())
6924           return true;
6925 
6926         Arg = ArgE.getAs<Expr>();
6927       }
6928 
6929       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6930                               diag::err_call_incomplete_argument, Arg))
6931         return ExprError();
6932 
6933       TheCall->setArg(i, Arg);
6934     }
6935     TheCall->computeDependence();
6936   }
6937 
6938   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6939     if (!Method->isStatic())
6940       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6941         << Fn->getSourceRange());
6942 
6943   // Check for sentinels
6944   if (NDecl)
6945     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6946 
6947   // Warn for unions passing across security boundary (CMSE).
6948   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6949     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6950       if (const auto *RT =
6951               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6952         if (RT->getDecl()->isOrContainsUnion())
6953           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6954               << 0 << i;
6955       }
6956     }
6957   }
6958 
6959   // Do special checking on direct calls to functions.
6960   if (FDecl) {
6961     if (CheckFunctionCall(FDecl, TheCall, Proto))
6962       return ExprError();
6963 
6964     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6965 
6966     if (BuiltinID)
6967       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6968   } else if (NDecl) {
6969     if (CheckPointerCall(NDecl, TheCall, Proto))
6970       return ExprError();
6971   } else {
6972     if (CheckOtherCall(TheCall, Proto))
6973       return ExprError();
6974   }
6975 
6976   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6977 }
6978 
6979 ExprResult
6980 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6981                            SourceLocation RParenLoc, Expr *InitExpr) {
6982   assert(Ty && "ActOnCompoundLiteral(): missing type");
6983   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6984 
6985   TypeSourceInfo *TInfo;
6986   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6987   if (!TInfo)
6988     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6989 
6990   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6991 }
6992 
6993 ExprResult
6994 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6995                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6996   QualType literalType = TInfo->getType();
6997 
6998   if (literalType->isArrayType()) {
6999     if (RequireCompleteSizedType(
7000             LParenLoc, Context.getBaseElementType(literalType),
7001             diag::err_array_incomplete_or_sizeless_type,
7002             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7003       return ExprError();
7004     if (literalType->isVariableArrayType()) {
7005       if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7006                                            diag::err_variable_object_no_init)) {
7007         return ExprError();
7008       }
7009     }
7010   } else if (!literalType->isDependentType() &&
7011              RequireCompleteType(LParenLoc, literalType,
7012                diag::err_typecheck_decl_incomplete_type,
7013                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7014     return ExprError();
7015 
7016   InitializedEntity Entity
7017     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7018   InitializationKind Kind
7019     = InitializationKind::CreateCStyleCast(LParenLoc,
7020                                            SourceRange(LParenLoc, RParenLoc),
7021                                            /*InitList=*/true);
7022   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7023   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7024                                       &literalType);
7025   if (Result.isInvalid())
7026     return ExprError();
7027   LiteralExpr = Result.get();
7028 
7029   bool isFileScope = !CurContext->isFunctionOrMethod();
7030 
7031   // In C, compound literals are l-values for some reason.
7032   // For GCC compatibility, in C++, file-scope array compound literals with
7033   // constant initializers are also l-values, and compound literals are
7034   // otherwise prvalues.
7035   //
7036   // (GCC also treats C++ list-initialized file-scope array prvalues with
7037   // constant initializers as l-values, but that's non-conforming, so we don't
7038   // follow it there.)
7039   //
7040   // FIXME: It would be better to handle the lvalue cases as materializing and
7041   // lifetime-extending a temporary object, but our materialized temporaries
7042   // representation only supports lifetime extension from a variable, not "out
7043   // of thin air".
7044   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7045   // is bound to the result of applying array-to-pointer decay to the compound
7046   // literal.
7047   // FIXME: GCC supports compound literals of reference type, which should
7048   // obviously have a value kind derived from the kind of reference involved.
7049   ExprValueKind VK =
7050       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7051           ? VK_PRValue
7052           : VK_LValue;
7053 
7054   if (isFileScope)
7055     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7056       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7057         Expr *Init = ILE->getInit(i);
7058         ILE->setInit(i, ConstantExpr::Create(Context, Init));
7059       }
7060 
7061   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7062                                               VK, LiteralExpr, isFileScope);
7063   if (isFileScope) {
7064     if (!LiteralExpr->isTypeDependent() &&
7065         !LiteralExpr->isValueDependent() &&
7066         !literalType->isDependentType()) // C99 6.5.2.5p3
7067       if (CheckForConstantInitializer(LiteralExpr, literalType))
7068         return ExprError();
7069   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7070              literalType.getAddressSpace() != LangAS::Default) {
7071     // Embedded-C extensions to C99 6.5.2.5:
7072     //   "If the compound literal occurs inside the body of a function, the
7073     //   type name shall not be qualified by an address-space qualifier."
7074     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7075       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7076     return ExprError();
7077   }
7078 
7079   if (!isFileScope && !getLangOpts().CPlusPlus) {
7080     // Compound literals that have automatic storage duration are destroyed at
7081     // the end of the scope in C; in C++, they're just temporaries.
7082 
7083     // Emit diagnostics if it is or contains a C union type that is non-trivial
7084     // to destruct.
7085     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7086       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7087                             NTCUC_CompoundLiteral, NTCUK_Destruct);
7088 
7089     // Diagnose jumps that enter or exit the lifetime of the compound literal.
7090     if (literalType.isDestructedType()) {
7091       Cleanup.setExprNeedsCleanups(true);
7092       ExprCleanupObjects.push_back(E);
7093       getCurFunction()->setHasBranchProtectedScope();
7094     }
7095   }
7096 
7097   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7098       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7099     checkNonTrivialCUnionInInitializer(E->getInitializer(),
7100                                        E->getInitializer()->getExprLoc());
7101 
7102   return MaybeBindToTemporary(E);
7103 }
7104 
7105 ExprResult
7106 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7107                     SourceLocation RBraceLoc) {
7108   // Only produce each kind of designated initialization diagnostic once.
7109   SourceLocation FirstDesignator;
7110   bool DiagnosedArrayDesignator = false;
7111   bool DiagnosedNestedDesignator = false;
7112   bool DiagnosedMixedDesignator = false;
7113 
7114   // Check that any designated initializers are syntactically valid in the
7115   // current language mode.
7116   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7117     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7118       if (FirstDesignator.isInvalid())
7119         FirstDesignator = DIE->getBeginLoc();
7120 
7121       if (!getLangOpts().CPlusPlus)
7122         break;
7123 
7124       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7125         DiagnosedNestedDesignator = true;
7126         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7127           << DIE->getDesignatorsSourceRange();
7128       }
7129 
7130       for (auto &Desig : DIE->designators()) {
7131         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7132           DiagnosedArrayDesignator = true;
7133           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7134             << Desig.getSourceRange();
7135         }
7136       }
7137 
7138       if (!DiagnosedMixedDesignator &&
7139           !isa<DesignatedInitExpr>(InitArgList[0])) {
7140         DiagnosedMixedDesignator = true;
7141         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7142           << DIE->getSourceRange();
7143         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7144           << InitArgList[0]->getSourceRange();
7145       }
7146     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7147                isa<DesignatedInitExpr>(InitArgList[0])) {
7148       DiagnosedMixedDesignator = true;
7149       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7150       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7151         << DIE->getSourceRange();
7152       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7153         << InitArgList[I]->getSourceRange();
7154     }
7155   }
7156 
7157   if (FirstDesignator.isValid()) {
7158     // Only diagnose designated initiaization as a C++20 extension if we didn't
7159     // already diagnose use of (non-C++20) C99 designator syntax.
7160     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7161         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7162       Diag(FirstDesignator, getLangOpts().CPlusPlus20
7163                                 ? diag::warn_cxx17_compat_designated_init
7164                                 : diag::ext_cxx_designated_init);
7165     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7166       Diag(FirstDesignator, diag::ext_designated_init);
7167     }
7168   }
7169 
7170   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7171 }
7172 
7173 ExprResult
7174 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7175                     SourceLocation RBraceLoc) {
7176   // Semantic analysis for initializers is done by ActOnDeclarator() and
7177   // CheckInitializer() - it requires knowledge of the object being initialized.
7178 
7179   // Immediately handle non-overload placeholders.  Overloads can be
7180   // resolved contextually, but everything else here can't.
7181   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7182     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7183       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7184 
7185       // Ignore failures; dropping the entire initializer list because
7186       // of one failure would be terrible for indexing/etc.
7187       if (result.isInvalid()) continue;
7188 
7189       InitArgList[I] = result.get();
7190     }
7191   }
7192 
7193   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7194                                                RBraceLoc);
7195   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7196   return E;
7197 }
7198 
7199 /// Do an explicit extend of the given block pointer if we're in ARC.
7200 void Sema::maybeExtendBlockObject(ExprResult &E) {
7201   assert(E.get()->getType()->isBlockPointerType());
7202   assert(E.get()->isPRValue());
7203 
7204   // Only do this in an r-value context.
7205   if (!getLangOpts().ObjCAutoRefCount) return;
7206 
7207   E = ImplicitCastExpr::Create(
7208       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7209       /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7210   Cleanup.setExprNeedsCleanups(true);
7211 }
7212 
7213 /// Prepare a conversion of the given expression to an ObjC object
7214 /// pointer type.
7215 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7216   QualType type = E.get()->getType();
7217   if (type->isObjCObjectPointerType()) {
7218     return CK_BitCast;
7219   } else if (type->isBlockPointerType()) {
7220     maybeExtendBlockObject(E);
7221     return CK_BlockPointerToObjCPointerCast;
7222   } else {
7223     assert(type->isPointerType());
7224     return CK_CPointerToObjCPointerCast;
7225   }
7226 }
7227 
7228 /// Prepares for a scalar cast, performing all the necessary stages
7229 /// except the final cast and returning the kind required.
7230 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7231   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7232   // Also, callers should have filtered out the invalid cases with
7233   // pointers.  Everything else should be possible.
7234 
7235   QualType SrcTy = Src.get()->getType();
7236   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7237     return CK_NoOp;
7238 
7239   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7240   case Type::STK_MemberPointer:
7241     llvm_unreachable("member pointer type in C");
7242 
7243   case Type::STK_CPointer:
7244   case Type::STK_BlockPointer:
7245   case Type::STK_ObjCObjectPointer:
7246     switch (DestTy->getScalarTypeKind()) {
7247     case Type::STK_CPointer: {
7248       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7249       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7250       if (SrcAS != DestAS)
7251         return CK_AddressSpaceConversion;
7252       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7253         return CK_NoOp;
7254       return CK_BitCast;
7255     }
7256     case Type::STK_BlockPointer:
7257       return (SrcKind == Type::STK_BlockPointer
7258                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7259     case Type::STK_ObjCObjectPointer:
7260       if (SrcKind == Type::STK_ObjCObjectPointer)
7261         return CK_BitCast;
7262       if (SrcKind == Type::STK_CPointer)
7263         return CK_CPointerToObjCPointerCast;
7264       maybeExtendBlockObject(Src);
7265       return CK_BlockPointerToObjCPointerCast;
7266     case Type::STK_Bool:
7267       return CK_PointerToBoolean;
7268     case Type::STK_Integral:
7269       return CK_PointerToIntegral;
7270     case Type::STK_Floating:
7271     case Type::STK_FloatingComplex:
7272     case Type::STK_IntegralComplex:
7273     case Type::STK_MemberPointer:
7274     case Type::STK_FixedPoint:
7275       llvm_unreachable("illegal cast from pointer");
7276     }
7277     llvm_unreachable("Should have returned before this");
7278 
7279   case Type::STK_FixedPoint:
7280     switch (DestTy->getScalarTypeKind()) {
7281     case Type::STK_FixedPoint:
7282       return CK_FixedPointCast;
7283     case Type::STK_Bool:
7284       return CK_FixedPointToBoolean;
7285     case Type::STK_Integral:
7286       return CK_FixedPointToIntegral;
7287     case Type::STK_Floating:
7288       return CK_FixedPointToFloating;
7289     case Type::STK_IntegralComplex:
7290     case Type::STK_FloatingComplex:
7291       Diag(Src.get()->getExprLoc(),
7292            diag::err_unimplemented_conversion_with_fixed_point_type)
7293           << DestTy;
7294       return CK_IntegralCast;
7295     case Type::STK_CPointer:
7296     case Type::STK_ObjCObjectPointer:
7297     case Type::STK_BlockPointer:
7298     case Type::STK_MemberPointer:
7299       llvm_unreachable("illegal cast to pointer type");
7300     }
7301     llvm_unreachable("Should have returned before this");
7302 
7303   case Type::STK_Bool: // casting from bool is like casting from an integer
7304   case Type::STK_Integral:
7305     switch (DestTy->getScalarTypeKind()) {
7306     case Type::STK_CPointer:
7307     case Type::STK_ObjCObjectPointer:
7308     case Type::STK_BlockPointer:
7309       if (Src.get()->isNullPointerConstant(Context,
7310                                            Expr::NPC_ValueDependentIsNull))
7311         return CK_NullToPointer;
7312       return CK_IntegralToPointer;
7313     case Type::STK_Bool:
7314       return CK_IntegralToBoolean;
7315     case Type::STK_Integral:
7316       return CK_IntegralCast;
7317     case Type::STK_Floating:
7318       return CK_IntegralToFloating;
7319     case Type::STK_IntegralComplex:
7320       Src = ImpCastExprToType(Src.get(),
7321                       DestTy->castAs<ComplexType>()->getElementType(),
7322                       CK_IntegralCast);
7323       return CK_IntegralRealToComplex;
7324     case Type::STK_FloatingComplex:
7325       Src = ImpCastExprToType(Src.get(),
7326                       DestTy->castAs<ComplexType>()->getElementType(),
7327                       CK_IntegralToFloating);
7328       return CK_FloatingRealToComplex;
7329     case Type::STK_MemberPointer:
7330       llvm_unreachable("member pointer type in C");
7331     case Type::STK_FixedPoint:
7332       return CK_IntegralToFixedPoint;
7333     }
7334     llvm_unreachable("Should have returned before this");
7335 
7336   case Type::STK_Floating:
7337     switch (DestTy->getScalarTypeKind()) {
7338     case Type::STK_Floating:
7339       return CK_FloatingCast;
7340     case Type::STK_Bool:
7341       return CK_FloatingToBoolean;
7342     case Type::STK_Integral:
7343       return CK_FloatingToIntegral;
7344     case Type::STK_FloatingComplex:
7345       Src = ImpCastExprToType(Src.get(),
7346                               DestTy->castAs<ComplexType>()->getElementType(),
7347                               CK_FloatingCast);
7348       return CK_FloatingRealToComplex;
7349     case Type::STK_IntegralComplex:
7350       Src = ImpCastExprToType(Src.get(),
7351                               DestTy->castAs<ComplexType>()->getElementType(),
7352                               CK_FloatingToIntegral);
7353       return CK_IntegralRealToComplex;
7354     case Type::STK_CPointer:
7355     case Type::STK_ObjCObjectPointer:
7356     case Type::STK_BlockPointer:
7357       llvm_unreachable("valid float->pointer cast?");
7358     case Type::STK_MemberPointer:
7359       llvm_unreachable("member pointer type in C");
7360     case Type::STK_FixedPoint:
7361       return CK_FloatingToFixedPoint;
7362     }
7363     llvm_unreachable("Should have returned before this");
7364 
7365   case Type::STK_FloatingComplex:
7366     switch (DestTy->getScalarTypeKind()) {
7367     case Type::STK_FloatingComplex:
7368       return CK_FloatingComplexCast;
7369     case Type::STK_IntegralComplex:
7370       return CK_FloatingComplexToIntegralComplex;
7371     case Type::STK_Floating: {
7372       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7373       if (Context.hasSameType(ET, DestTy))
7374         return CK_FloatingComplexToReal;
7375       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7376       return CK_FloatingCast;
7377     }
7378     case Type::STK_Bool:
7379       return CK_FloatingComplexToBoolean;
7380     case Type::STK_Integral:
7381       Src = ImpCastExprToType(Src.get(),
7382                               SrcTy->castAs<ComplexType>()->getElementType(),
7383                               CK_FloatingComplexToReal);
7384       return CK_FloatingToIntegral;
7385     case Type::STK_CPointer:
7386     case Type::STK_ObjCObjectPointer:
7387     case Type::STK_BlockPointer:
7388       llvm_unreachable("valid complex float->pointer cast?");
7389     case Type::STK_MemberPointer:
7390       llvm_unreachable("member pointer type in C");
7391     case Type::STK_FixedPoint:
7392       Diag(Src.get()->getExprLoc(),
7393            diag::err_unimplemented_conversion_with_fixed_point_type)
7394           << SrcTy;
7395       return CK_IntegralCast;
7396     }
7397     llvm_unreachable("Should have returned before this");
7398 
7399   case Type::STK_IntegralComplex:
7400     switch (DestTy->getScalarTypeKind()) {
7401     case Type::STK_FloatingComplex:
7402       return CK_IntegralComplexToFloatingComplex;
7403     case Type::STK_IntegralComplex:
7404       return CK_IntegralComplexCast;
7405     case Type::STK_Integral: {
7406       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7407       if (Context.hasSameType(ET, DestTy))
7408         return CK_IntegralComplexToReal;
7409       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7410       return CK_IntegralCast;
7411     }
7412     case Type::STK_Bool:
7413       return CK_IntegralComplexToBoolean;
7414     case Type::STK_Floating:
7415       Src = ImpCastExprToType(Src.get(),
7416                               SrcTy->castAs<ComplexType>()->getElementType(),
7417                               CK_IntegralComplexToReal);
7418       return CK_IntegralToFloating;
7419     case Type::STK_CPointer:
7420     case Type::STK_ObjCObjectPointer:
7421     case Type::STK_BlockPointer:
7422       llvm_unreachable("valid complex int->pointer cast?");
7423     case Type::STK_MemberPointer:
7424       llvm_unreachable("member pointer type in C");
7425     case Type::STK_FixedPoint:
7426       Diag(Src.get()->getExprLoc(),
7427            diag::err_unimplemented_conversion_with_fixed_point_type)
7428           << SrcTy;
7429       return CK_IntegralCast;
7430     }
7431     llvm_unreachable("Should have returned before this");
7432   }
7433 
7434   llvm_unreachable("Unhandled scalar cast");
7435 }
7436 
7437 static bool breakDownVectorType(QualType type, uint64_t &len,
7438                                 QualType &eltType) {
7439   // Vectors are simple.
7440   if (const VectorType *vecType = type->getAs<VectorType>()) {
7441     len = vecType->getNumElements();
7442     eltType = vecType->getElementType();
7443     assert(eltType->isScalarType());
7444     return true;
7445   }
7446 
7447   // We allow lax conversion to and from non-vector types, but only if
7448   // they're real types (i.e. non-complex, non-pointer scalar types).
7449   if (!type->isRealType()) return false;
7450 
7451   len = 1;
7452   eltType = type;
7453   return true;
7454 }
7455 
7456 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7457 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7458 /// allowed?
7459 ///
7460 /// This will also return false if the two given types do not make sense from
7461 /// the perspective of SVE bitcasts.
7462 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7463   assert(srcTy->isVectorType() || destTy->isVectorType());
7464 
7465   auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7466     if (!FirstType->isSizelessBuiltinType())
7467       return false;
7468 
7469     const auto *VecTy = SecondType->getAs<VectorType>();
7470     return VecTy &&
7471            VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7472   };
7473 
7474   return ValidScalableConversion(srcTy, destTy) ||
7475          ValidScalableConversion(destTy, srcTy);
7476 }
7477 
7478 /// Are the two types matrix types and do they have the same dimensions i.e.
7479 /// do they have the same number of rows and the same number of columns?
7480 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7481   if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7482     return false;
7483 
7484   const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7485   const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7486 
7487   return matSrcType->getNumRows() == matDestType->getNumRows() &&
7488          matSrcType->getNumColumns() == matDestType->getNumColumns();
7489 }
7490 
7491 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7492   assert(DestTy->isVectorType() || SrcTy->isVectorType());
7493 
7494   uint64_t SrcLen, DestLen;
7495   QualType SrcEltTy, DestEltTy;
7496   if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7497     return false;
7498   if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7499     return false;
7500 
7501   // ASTContext::getTypeSize will return the size rounded up to a
7502   // power of 2, so instead of using that, we need to use the raw
7503   // element size multiplied by the element count.
7504   uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7505   uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7506 
7507   return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7508 }
7509 
7510 /// Are the two types lax-compatible vector types?  That is, given
7511 /// that one of them is a vector, do they have equal storage sizes,
7512 /// where the storage size is the number of elements times the element
7513 /// size?
7514 ///
7515 /// This will also return false if either of the types is neither a
7516 /// vector nor a real type.
7517 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7518   assert(destTy->isVectorType() || srcTy->isVectorType());
7519 
7520   // Disallow lax conversions between scalars and ExtVectors (these
7521   // conversions are allowed for other vector types because common headers
7522   // depend on them).  Most scalar OP ExtVector cases are handled by the
7523   // splat path anyway, which does what we want (convert, not bitcast).
7524   // What this rules out for ExtVectors is crazy things like char4*float.
7525   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7526   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7527 
7528   return areVectorTypesSameSize(srcTy, destTy);
7529 }
7530 
7531 /// Is this a legal conversion between two types, one of which is
7532 /// known to be a vector type?
7533 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7534   assert(destTy->isVectorType() || srcTy->isVectorType());
7535 
7536   switch (Context.getLangOpts().getLaxVectorConversions()) {
7537   case LangOptions::LaxVectorConversionKind::None:
7538     return false;
7539 
7540   case LangOptions::LaxVectorConversionKind::Integer:
7541     if (!srcTy->isIntegralOrEnumerationType()) {
7542       auto *Vec = srcTy->getAs<VectorType>();
7543       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7544         return false;
7545     }
7546     if (!destTy->isIntegralOrEnumerationType()) {
7547       auto *Vec = destTy->getAs<VectorType>();
7548       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7549         return false;
7550     }
7551     // OK, integer (vector) -> integer (vector) bitcast.
7552     break;
7553 
7554     case LangOptions::LaxVectorConversionKind::All:
7555     break;
7556   }
7557 
7558   return areLaxCompatibleVectorTypes(srcTy, destTy);
7559 }
7560 
7561 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7562                            CastKind &Kind) {
7563   if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7564     if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7565       return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7566              << DestTy << SrcTy << R;
7567     }
7568   } else if (SrcTy->isMatrixType()) {
7569     return Diag(R.getBegin(),
7570                 diag::err_invalid_conversion_between_matrix_and_type)
7571            << SrcTy << DestTy << R;
7572   } else if (DestTy->isMatrixType()) {
7573     return Diag(R.getBegin(),
7574                 diag::err_invalid_conversion_between_matrix_and_type)
7575            << DestTy << SrcTy << R;
7576   }
7577 
7578   Kind = CK_MatrixCast;
7579   return false;
7580 }
7581 
7582 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7583                            CastKind &Kind) {
7584   assert(VectorTy->isVectorType() && "Not a vector type!");
7585 
7586   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7587     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7588       return Diag(R.getBegin(),
7589                   Ty->isVectorType() ?
7590                   diag::err_invalid_conversion_between_vectors :
7591                   diag::err_invalid_conversion_between_vector_and_integer)
7592         << VectorTy << Ty << R;
7593   } else
7594     return Diag(R.getBegin(),
7595                 diag::err_invalid_conversion_between_vector_and_scalar)
7596       << VectorTy << Ty << R;
7597 
7598   Kind = CK_BitCast;
7599   return false;
7600 }
7601 
7602 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7603   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7604 
7605   if (DestElemTy == SplattedExpr->getType())
7606     return SplattedExpr;
7607 
7608   assert(DestElemTy->isFloatingType() ||
7609          DestElemTy->isIntegralOrEnumerationType());
7610 
7611   CastKind CK;
7612   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7613     // OpenCL requires that we convert `true` boolean expressions to -1, but
7614     // only when splatting vectors.
7615     if (DestElemTy->isFloatingType()) {
7616       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7617       // in two steps: boolean to signed integral, then to floating.
7618       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7619                                                  CK_BooleanToSignedIntegral);
7620       SplattedExpr = CastExprRes.get();
7621       CK = CK_IntegralToFloating;
7622     } else {
7623       CK = CK_BooleanToSignedIntegral;
7624     }
7625   } else {
7626     ExprResult CastExprRes = SplattedExpr;
7627     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7628     if (CastExprRes.isInvalid())
7629       return ExprError();
7630     SplattedExpr = CastExprRes.get();
7631   }
7632   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7633 }
7634 
7635 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7636                                     Expr *CastExpr, CastKind &Kind) {
7637   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7638 
7639   QualType SrcTy = CastExpr->getType();
7640 
7641   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7642   // an ExtVectorType.
7643   // In OpenCL, casts between vectors of different types are not allowed.
7644   // (See OpenCL 6.2).
7645   if (SrcTy->isVectorType()) {
7646     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7647         (getLangOpts().OpenCL &&
7648          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7649       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7650         << DestTy << SrcTy << R;
7651       return ExprError();
7652     }
7653     Kind = CK_BitCast;
7654     return CastExpr;
7655   }
7656 
7657   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7658   // conversion will take place first from scalar to elt type, and then
7659   // splat from elt type to vector.
7660   if (SrcTy->isPointerType())
7661     return Diag(R.getBegin(),
7662                 diag::err_invalid_conversion_between_vector_and_scalar)
7663       << DestTy << SrcTy << R;
7664 
7665   Kind = CK_VectorSplat;
7666   return prepareVectorSplat(DestTy, CastExpr);
7667 }
7668 
7669 ExprResult
7670 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7671                     Declarator &D, ParsedType &Ty,
7672                     SourceLocation RParenLoc, Expr *CastExpr) {
7673   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7674          "ActOnCastExpr(): missing type or expr");
7675 
7676   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7677   if (D.isInvalidType())
7678     return ExprError();
7679 
7680   if (getLangOpts().CPlusPlus) {
7681     // Check that there are no default arguments (C++ only).
7682     CheckExtraCXXDefaultArguments(D);
7683   } else {
7684     // Make sure any TypoExprs have been dealt with.
7685     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7686     if (!Res.isUsable())
7687       return ExprError();
7688     CastExpr = Res.get();
7689   }
7690 
7691   checkUnusedDeclAttributes(D);
7692 
7693   QualType castType = castTInfo->getType();
7694   Ty = CreateParsedType(castType, castTInfo);
7695 
7696   bool isVectorLiteral = false;
7697 
7698   // Check for an altivec or OpenCL literal,
7699   // i.e. all the elements are integer constants.
7700   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7701   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7702   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7703        && castType->isVectorType() && (PE || PLE)) {
7704     if (PLE && PLE->getNumExprs() == 0) {
7705       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7706       return ExprError();
7707     }
7708     if (PE || PLE->getNumExprs() == 1) {
7709       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7710       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7711         isVectorLiteral = true;
7712     }
7713     else
7714       isVectorLiteral = true;
7715   }
7716 
7717   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7718   // then handle it as such.
7719   if (isVectorLiteral)
7720     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7721 
7722   // If the Expr being casted is a ParenListExpr, handle it specially.
7723   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7724   // sequence of BinOp comma operators.
7725   if (isa<ParenListExpr>(CastExpr)) {
7726     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7727     if (Result.isInvalid()) return ExprError();
7728     CastExpr = Result.get();
7729   }
7730 
7731   if (getLangOpts().CPlusPlus && !castType->isVoidType())
7732     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7733 
7734   CheckTollFreeBridgeCast(castType, CastExpr);
7735 
7736   CheckObjCBridgeRelatedCast(castType, CastExpr);
7737 
7738   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7739 
7740   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7741 }
7742 
7743 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7744                                     SourceLocation RParenLoc, Expr *E,
7745                                     TypeSourceInfo *TInfo) {
7746   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7747          "Expected paren or paren list expression");
7748 
7749   Expr **exprs;
7750   unsigned numExprs;
7751   Expr *subExpr;
7752   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7753   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7754     LiteralLParenLoc = PE->getLParenLoc();
7755     LiteralRParenLoc = PE->getRParenLoc();
7756     exprs = PE->getExprs();
7757     numExprs = PE->getNumExprs();
7758   } else { // isa<ParenExpr> by assertion at function entrance
7759     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7760     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7761     subExpr = cast<ParenExpr>(E)->getSubExpr();
7762     exprs = &subExpr;
7763     numExprs = 1;
7764   }
7765 
7766   QualType Ty = TInfo->getType();
7767   assert(Ty->isVectorType() && "Expected vector type");
7768 
7769   SmallVector<Expr *, 8> initExprs;
7770   const VectorType *VTy = Ty->castAs<VectorType>();
7771   unsigned numElems = VTy->getNumElements();
7772 
7773   // '(...)' form of vector initialization in AltiVec: the number of
7774   // initializers must be one or must match the size of the vector.
7775   // If a single value is specified in the initializer then it will be
7776   // replicated to all the components of the vector
7777   if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
7778                                  VTy->getElementType()))
7779     return ExprError();
7780   if (ShouldSplatAltivecScalarInCast(VTy)) {
7781     // The number of initializers must be one or must match the size of the
7782     // vector. If a single value is specified in the initializer then it will
7783     // be replicated to all the components of the vector
7784     if (numExprs == 1) {
7785       QualType ElemTy = VTy->getElementType();
7786       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7787       if (Literal.isInvalid())
7788         return ExprError();
7789       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7790                                   PrepareScalarCast(Literal, ElemTy));
7791       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7792     }
7793     else if (numExprs < numElems) {
7794       Diag(E->getExprLoc(),
7795            diag::err_incorrect_number_of_vector_initializers);
7796       return ExprError();
7797     }
7798     else
7799       initExprs.append(exprs, exprs + numExprs);
7800   }
7801   else {
7802     // For OpenCL, when the number of initializers is a single value,
7803     // it will be replicated to all components of the vector.
7804     if (getLangOpts().OpenCL &&
7805         VTy->getVectorKind() == VectorType::GenericVector &&
7806         numExprs == 1) {
7807         QualType ElemTy = VTy->getElementType();
7808         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7809         if (Literal.isInvalid())
7810           return ExprError();
7811         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7812                                     PrepareScalarCast(Literal, ElemTy));
7813         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7814     }
7815 
7816     initExprs.append(exprs, exprs + numExprs);
7817   }
7818   // FIXME: This means that pretty-printing the final AST will produce curly
7819   // braces instead of the original commas.
7820   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7821                                                    initExprs, LiteralRParenLoc);
7822   initE->setType(Ty);
7823   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7824 }
7825 
7826 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7827 /// the ParenListExpr into a sequence of comma binary operators.
7828 ExprResult
7829 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7830   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7831   if (!E)
7832     return OrigExpr;
7833 
7834   ExprResult Result(E->getExpr(0));
7835 
7836   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7837     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7838                         E->getExpr(i));
7839 
7840   if (Result.isInvalid()) return ExprError();
7841 
7842   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7843 }
7844 
7845 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7846                                     SourceLocation R,
7847                                     MultiExprArg Val) {
7848   return ParenListExpr::Create(Context, L, Val, R);
7849 }
7850 
7851 /// Emit a specialized diagnostic when one expression is a null pointer
7852 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7853 /// emitted.
7854 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7855                                       SourceLocation QuestionLoc) {
7856   Expr *NullExpr = LHSExpr;
7857   Expr *NonPointerExpr = RHSExpr;
7858   Expr::NullPointerConstantKind NullKind =
7859       NullExpr->isNullPointerConstant(Context,
7860                                       Expr::NPC_ValueDependentIsNotNull);
7861 
7862   if (NullKind == Expr::NPCK_NotNull) {
7863     NullExpr = RHSExpr;
7864     NonPointerExpr = LHSExpr;
7865     NullKind =
7866         NullExpr->isNullPointerConstant(Context,
7867                                         Expr::NPC_ValueDependentIsNotNull);
7868   }
7869 
7870   if (NullKind == Expr::NPCK_NotNull)
7871     return false;
7872 
7873   if (NullKind == Expr::NPCK_ZeroExpression)
7874     return false;
7875 
7876   if (NullKind == Expr::NPCK_ZeroLiteral) {
7877     // In this case, check to make sure that we got here from a "NULL"
7878     // string in the source code.
7879     NullExpr = NullExpr->IgnoreParenImpCasts();
7880     SourceLocation loc = NullExpr->getExprLoc();
7881     if (!findMacroSpelling(loc, "NULL"))
7882       return false;
7883   }
7884 
7885   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7886   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7887       << NonPointerExpr->getType() << DiagType
7888       << NonPointerExpr->getSourceRange();
7889   return true;
7890 }
7891 
7892 /// Return false if the condition expression is valid, true otherwise.
7893 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7894   QualType CondTy = Cond->getType();
7895 
7896   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7897   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7898     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7899       << CondTy << Cond->getSourceRange();
7900     return true;
7901   }
7902 
7903   // C99 6.5.15p2
7904   if (CondTy->isScalarType()) return false;
7905 
7906   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7907     << CondTy << Cond->getSourceRange();
7908   return true;
7909 }
7910 
7911 /// Handle when one or both operands are void type.
7912 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7913                                          ExprResult &RHS) {
7914     Expr *LHSExpr = LHS.get();
7915     Expr *RHSExpr = RHS.get();
7916 
7917     if (!LHSExpr->getType()->isVoidType())
7918       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7919           << RHSExpr->getSourceRange();
7920     if (!RHSExpr->getType()->isVoidType())
7921       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7922           << LHSExpr->getSourceRange();
7923     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7924     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7925     return S.Context.VoidTy;
7926 }
7927 
7928 /// Return false if the NullExpr can be promoted to PointerTy,
7929 /// true otherwise.
7930 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7931                                         QualType PointerTy) {
7932   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7933       !NullExpr.get()->isNullPointerConstant(S.Context,
7934                                             Expr::NPC_ValueDependentIsNull))
7935     return true;
7936 
7937   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7938   return false;
7939 }
7940 
7941 /// Checks compatibility between two pointers and return the resulting
7942 /// type.
7943 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7944                                                      ExprResult &RHS,
7945                                                      SourceLocation Loc) {
7946   QualType LHSTy = LHS.get()->getType();
7947   QualType RHSTy = RHS.get()->getType();
7948 
7949   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7950     // Two identical pointers types are always compatible.
7951     return LHSTy;
7952   }
7953 
7954   QualType lhptee, rhptee;
7955 
7956   // Get the pointee types.
7957   bool IsBlockPointer = false;
7958   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7959     lhptee = LHSBTy->getPointeeType();
7960     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7961     IsBlockPointer = true;
7962   } else {
7963     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7964     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7965   }
7966 
7967   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7968   // differently qualified versions of compatible types, the result type is
7969   // a pointer to an appropriately qualified version of the composite
7970   // type.
7971 
7972   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7973   // clause doesn't make sense for our extensions. E.g. address space 2 should
7974   // be incompatible with address space 3: they may live on different devices or
7975   // anything.
7976   Qualifiers lhQual = lhptee.getQualifiers();
7977   Qualifiers rhQual = rhptee.getQualifiers();
7978 
7979   LangAS ResultAddrSpace = LangAS::Default;
7980   LangAS LAddrSpace = lhQual.getAddressSpace();
7981   LangAS RAddrSpace = rhQual.getAddressSpace();
7982 
7983   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7984   // spaces is disallowed.
7985   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7986     ResultAddrSpace = LAddrSpace;
7987   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7988     ResultAddrSpace = RAddrSpace;
7989   else {
7990     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7991         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7992         << RHS.get()->getSourceRange();
7993     return QualType();
7994   }
7995 
7996   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7997   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7998   lhQual.removeCVRQualifiers();
7999   rhQual.removeCVRQualifiers();
8000 
8001   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8002   // (C99 6.7.3) for address spaces. We assume that the check should behave in
8003   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8004   // qual types are compatible iff
8005   //  * corresponded types are compatible
8006   //  * CVR qualifiers are equal
8007   //  * address spaces are equal
8008   // Thus for conditional operator we merge CVR and address space unqualified
8009   // pointees and if there is a composite type we return a pointer to it with
8010   // merged qualifiers.
8011   LHSCastKind =
8012       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8013   RHSCastKind =
8014       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8015   lhQual.removeAddressSpace();
8016   rhQual.removeAddressSpace();
8017 
8018   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8019   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8020 
8021   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
8022 
8023   if (CompositeTy.isNull()) {
8024     // In this situation, we assume void* type. No especially good
8025     // reason, but this is what gcc does, and we do have to pick
8026     // to get a consistent AST.
8027     QualType incompatTy;
8028     incompatTy = S.Context.getPointerType(
8029         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8030     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8031     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8032 
8033     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8034     // for casts between types with incompatible address space qualifiers.
8035     // For the following code the compiler produces casts between global and
8036     // local address spaces of the corresponded innermost pointees:
8037     // local int *global *a;
8038     // global int *global *b;
8039     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8040     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8041         << LHSTy << RHSTy << LHS.get()->getSourceRange()
8042         << RHS.get()->getSourceRange();
8043 
8044     return incompatTy;
8045   }
8046 
8047   // The pointer types are compatible.
8048   // In case of OpenCL ResultTy should have the address space qualifier
8049   // which is a superset of address spaces of both the 2nd and the 3rd
8050   // operands of the conditional operator.
8051   QualType ResultTy = [&, ResultAddrSpace]() {
8052     if (S.getLangOpts().OpenCL) {
8053       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8054       CompositeQuals.setAddressSpace(ResultAddrSpace);
8055       return S.Context
8056           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8057           .withCVRQualifiers(MergedCVRQual);
8058     }
8059     return CompositeTy.withCVRQualifiers(MergedCVRQual);
8060   }();
8061   if (IsBlockPointer)
8062     ResultTy = S.Context.getBlockPointerType(ResultTy);
8063   else
8064     ResultTy = S.Context.getPointerType(ResultTy);
8065 
8066   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8067   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8068   return ResultTy;
8069 }
8070 
8071 /// Return the resulting type when the operands are both block pointers.
8072 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8073                                                           ExprResult &LHS,
8074                                                           ExprResult &RHS,
8075                                                           SourceLocation Loc) {
8076   QualType LHSTy = LHS.get()->getType();
8077   QualType RHSTy = RHS.get()->getType();
8078 
8079   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8080     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8081       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8082       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8083       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8084       return destType;
8085     }
8086     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8087       << LHSTy << RHSTy << LHS.get()->getSourceRange()
8088       << RHS.get()->getSourceRange();
8089     return QualType();
8090   }
8091 
8092   // We have 2 block pointer types.
8093   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8094 }
8095 
8096 /// Return the resulting type when the operands are both pointers.
8097 static QualType
8098 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8099                                             ExprResult &RHS,
8100                                             SourceLocation Loc) {
8101   // get the pointer types
8102   QualType LHSTy = LHS.get()->getType();
8103   QualType RHSTy = RHS.get()->getType();
8104 
8105   // get the "pointed to" types
8106   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8107   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8108 
8109   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8110   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8111     // Figure out necessary qualifiers (C99 6.5.15p6)
8112     QualType destPointee
8113       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8114     QualType destType = S.Context.getPointerType(destPointee);
8115     // Add qualifiers if necessary.
8116     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8117     // Promote to void*.
8118     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8119     return destType;
8120   }
8121   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8122     QualType destPointee
8123       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8124     QualType destType = S.Context.getPointerType(destPointee);
8125     // Add qualifiers if necessary.
8126     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8127     // Promote to void*.
8128     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8129     return destType;
8130   }
8131 
8132   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8133 }
8134 
8135 /// Return false if the first expression is not an integer and the second
8136 /// expression is not a pointer, true otherwise.
8137 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8138                                         Expr* PointerExpr, SourceLocation Loc,
8139                                         bool IsIntFirstExpr) {
8140   if (!PointerExpr->getType()->isPointerType() ||
8141       !Int.get()->getType()->isIntegerType())
8142     return false;
8143 
8144   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8145   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8146 
8147   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8148     << Expr1->getType() << Expr2->getType()
8149     << Expr1->getSourceRange() << Expr2->getSourceRange();
8150   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8151                             CK_IntegralToPointer);
8152   return true;
8153 }
8154 
8155 /// Simple conversion between integer and floating point types.
8156 ///
8157 /// Used when handling the OpenCL conditional operator where the
8158 /// condition is a vector while the other operands are scalar.
8159 ///
8160 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8161 /// types are either integer or floating type. Between the two
8162 /// operands, the type with the higher rank is defined as the "result
8163 /// type". The other operand needs to be promoted to the same type. No
8164 /// other type promotion is allowed. We cannot use
8165 /// UsualArithmeticConversions() for this purpose, since it always
8166 /// promotes promotable types.
8167 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8168                                             ExprResult &RHS,
8169                                             SourceLocation QuestionLoc) {
8170   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8171   if (LHS.isInvalid())
8172     return QualType();
8173   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8174   if (RHS.isInvalid())
8175     return QualType();
8176 
8177   // For conversion purposes, we ignore any qualifiers.
8178   // For example, "const float" and "float" are equivalent.
8179   QualType LHSType =
8180     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8181   QualType RHSType =
8182     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8183 
8184   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8185     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8186       << LHSType << LHS.get()->getSourceRange();
8187     return QualType();
8188   }
8189 
8190   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8191     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8192       << RHSType << RHS.get()->getSourceRange();
8193     return QualType();
8194   }
8195 
8196   // If both types are identical, no conversion is needed.
8197   if (LHSType == RHSType)
8198     return LHSType;
8199 
8200   // Now handle "real" floating types (i.e. float, double, long double).
8201   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8202     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8203                                  /*IsCompAssign = */ false);
8204 
8205   // Finally, we have two differing integer types.
8206   return handleIntegerConversion<doIntegralCast, doIntegralCast>
8207   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8208 }
8209 
8210 /// Convert scalar operands to a vector that matches the
8211 ///        condition in length.
8212 ///
8213 /// Used when handling the OpenCL conditional operator where the
8214 /// condition is a vector while the other operands are scalar.
8215 ///
8216 /// We first compute the "result type" for the scalar operands
8217 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8218 /// into a vector of that type where the length matches the condition
8219 /// vector type. s6.11.6 requires that the element types of the result
8220 /// and the condition must have the same number of bits.
8221 static QualType
8222 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8223                               QualType CondTy, SourceLocation QuestionLoc) {
8224   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8225   if (ResTy.isNull()) return QualType();
8226 
8227   const VectorType *CV = CondTy->getAs<VectorType>();
8228   assert(CV);
8229 
8230   // Determine the vector result type
8231   unsigned NumElements = CV->getNumElements();
8232   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8233 
8234   // Ensure that all types have the same number of bits
8235   if (S.Context.getTypeSize(CV->getElementType())
8236       != S.Context.getTypeSize(ResTy)) {
8237     // Since VectorTy is created internally, it does not pretty print
8238     // with an OpenCL name. Instead, we just print a description.
8239     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8240     SmallString<64> Str;
8241     llvm::raw_svector_ostream OS(Str);
8242     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8243     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8244       << CondTy << OS.str();
8245     return QualType();
8246   }
8247 
8248   // Convert operands to the vector result type
8249   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8250   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8251 
8252   return VectorTy;
8253 }
8254 
8255 /// Return false if this is a valid OpenCL condition vector
8256 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8257                                        SourceLocation QuestionLoc) {
8258   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8259   // integral type.
8260   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8261   assert(CondTy);
8262   QualType EleTy = CondTy->getElementType();
8263   if (EleTy->isIntegerType()) return false;
8264 
8265   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8266     << Cond->getType() << Cond->getSourceRange();
8267   return true;
8268 }
8269 
8270 /// Return false if the vector condition type and the vector
8271 ///        result type are compatible.
8272 ///
8273 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8274 /// number of elements, and their element types have the same number
8275 /// of bits.
8276 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8277                               SourceLocation QuestionLoc) {
8278   const VectorType *CV = CondTy->getAs<VectorType>();
8279   const VectorType *RV = VecResTy->getAs<VectorType>();
8280   assert(CV && RV);
8281 
8282   if (CV->getNumElements() != RV->getNumElements()) {
8283     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8284       << CondTy << VecResTy;
8285     return true;
8286   }
8287 
8288   QualType CVE = CV->getElementType();
8289   QualType RVE = RV->getElementType();
8290 
8291   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8292     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8293       << CondTy << VecResTy;
8294     return true;
8295   }
8296 
8297   return false;
8298 }
8299 
8300 /// Return the resulting type for the conditional operator in
8301 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8302 ///        s6.3.i) when the condition is a vector type.
8303 static QualType
8304 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8305                              ExprResult &LHS, ExprResult &RHS,
8306                              SourceLocation QuestionLoc) {
8307   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8308   if (Cond.isInvalid())
8309     return QualType();
8310   QualType CondTy = Cond.get()->getType();
8311 
8312   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8313     return QualType();
8314 
8315   // If either operand is a vector then find the vector type of the
8316   // result as specified in OpenCL v1.1 s6.3.i.
8317   if (LHS.get()->getType()->isVectorType() ||
8318       RHS.get()->getType()->isVectorType()) {
8319     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8320                                               /*isCompAssign*/false,
8321                                               /*AllowBothBool*/true,
8322                                               /*AllowBoolConversions*/false);
8323     if (VecResTy.isNull()) return QualType();
8324     // The result type must match the condition type as specified in
8325     // OpenCL v1.1 s6.11.6.
8326     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8327       return QualType();
8328     return VecResTy;
8329   }
8330 
8331   // Both operands are scalar.
8332   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8333 }
8334 
8335 /// Return true if the Expr is block type
8336 static bool checkBlockType(Sema &S, const Expr *E) {
8337   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8338     QualType Ty = CE->getCallee()->getType();
8339     if (Ty->isBlockPointerType()) {
8340       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8341       return true;
8342     }
8343   }
8344   return false;
8345 }
8346 
8347 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8348 /// In that case, LHS = cond.
8349 /// C99 6.5.15
8350 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8351                                         ExprResult &RHS, ExprValueKind &VK,
8352                                         ExprObjectKind &OK,
8353                                         SourceLocation QuestionLoc) {
8354 
8355   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8356   if (!LHSResult.isUsable()) return QualType();
8357   LHS = LHSResult;
8358 
8359   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8360   if (!RHSResult.isUsable()) return QualType();
8361   RHS = RHSResult;
8362 
8363   // C++ is sufficiently different to merit its own checker.
8364   if (getLangOpts().CPlusPlus)
8365     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8366 
8367   VK = VK_PRValue;
8368   OK = OK_Ordinary;
8369 
8370   if (Context.isDependenceAllowed() &&
8371       (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8372        RHS.get()->isTypeDependent())) {
8373     assert(!getLangOpts().CPlusPlus);
8374     assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8375             RHS.get()->containsErrors()) &&
8376            "should only occur in error-recovery path.");
8377     return Context.DependentTy;
8378   }
8379 
8380   // The OpenCL operator with a vector condition is sufficiently
8381   // different to merit its own checker.
8382   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8383       Cond.get()->getType()->isExtVectorType())
8384     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8385 
8386   // First, check the condition.
8387   Cond = UsualUnaryConversions(Cond.get());
8388   if (Cond.isInvalid())
8389     return QualType();
8390   if (checkCondition(*this, Cond.get(), QuestionLoc))
8391     return QualType();
8392 
8393   // Now check the two expressions.
8394   if (LHS.get()->getType()->isVectorType() ||
8395       RHS.get()->getType()->isVectorType())
8396     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8397                                /*AllowBothBool*/true,
8398                                /*AllowBoolConversions*/false);
8399 
8400   QualType ResTy =
8401       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8402   if (LHS.isInvalid() || RHS.isInvalid())
8403     return QualType();
8404 
8405   QualType LHSTy = LHS.get()->getType();
8406   QualType RHSTy = RHS.get()->getType();
8407 
8408   // Diagnose attempts to convert between __ibm128, __float128 and long double
8409   // where such conversions currently can't be handled.
8410   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8411     Diag(QuestionLoc,
8412          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8413       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8414     return QualType();
8415   }
8416 
8417   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8418   // selection operator (?:).
8419   if (getLangOpts().OpenCL &&
8420       ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8421     return QualType();
8422   }
8423 
8424   // If both operands have arithmetic type, do the usual arithmetic conversions
8425   // to find a common type: C99 6.5.15p3,5.
8426   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8427     // Disallow invalid arithmetic conversions, such as those between bit-
8428     // precise integers types of different sizes, or between a bit-precise
8429     // integer and another type.
8430     if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8431       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8432           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8433           << RHS.get()->getSourceRange();
8434       return QualType();
8435     }
8436 
8437     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8438     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8439 
8440     return ResTy;
8441   }
8442 
8443   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8444   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8445     return LHSTy;
8446   }
8447 
8448   // If both operands are the same structure or union type, the result is that
8449   // type.
8450   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8451     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8452       if (LHSRT->getDecl() == RHSRT->getDecl())
8453         // "If both the operands have structure or union type, the result has
8454         // that type."  This implies that CV qualifiers are dropped.
8455         return LHSTy.getUnqualifiedType();
8456     // FIXME: Type of conditional expression must be complete in C mode.
8457   }
8458 
8459   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8460   // The following || allows only one side to be void (a GCC-ism).
8461   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8462     return checkConditionalVoidType(*this, LHS, RHS);
8463   }
8464 
8465   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8466   // the type of the other operand."
8467   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8468   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8469 
8470   // All objective-c pointer type analysis is done here.
8471   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8472                                                         QuestionLoc);
8473   if (LHS.isInvalid() || RHS.isInvalid())
8474     return QualType();
8475   if (!compositeType.isNull())
8476     return compositeType;
8477 
8478 
8479   // Handle block pointer types.
8480   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8481     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8482                                                      QuestionLoc);
8483 
8484   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8485   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8486     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8487                                                        QuestionLoc);
8488 
8489   // GCC compatibility: soften pointer/integer mismatch.  Note that
8490   // null pointers have been filtered out by this point.
8491   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8492       /*IsIntFirstExpr=*/true))
8493     return RHSTy;
8494   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8495       /*IsIntFirstExpr=*/false))
8496     return LHSTy;
8497 
8498   // Allow ?: operations in which both operands have the same
8499   // built-in sizeless type.
8500   if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8501     return LHSTy;
8502 
8503   // Emit a better diagnostic if one of the expressions is a null pointer
8504   // constant and the other is not a pointer type. In this case, the user most
8505   // likely forgot to take the address of the other expression.
8506   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8507     return QualType();
8508 
8509   // Otherwise, the operands are not compatible.
8510   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8511     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8512     << RHS.get()->getSourceRange();
8513   return QualType();
8514 }
8515 
8516 /// FindCompositeObjCPointerType - Helper method to find composite type of
8517 /// two objective-c pointer types of the two input expressions.
8518 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8519                                             SourceLocation QuestionLoc) {
8520   QualType LHSTy = LHS.get()->getType();
8521   QualType RHSTy = RHS.get()->getType();
8522 
8523   // Handle things like Class and struct objc_class*.  Here we case the result
8524   // to the pseudo-builtin, because that will be implicitly cast back to the
8525   // redefinition type if an attempt is made to access its fields.
8526   if (LHSTy->isObjCClassType() &&
8527       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8528     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8529     return LHSTy;
8530   }
8531   if (RHSTy->isObjCClassType() &&
8532       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8533     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8534     return RHSTy;
8535   }
8536   // And the same for struct objc_object* / id
8537   if (LHSTy->isObjCIdType() &&
8538       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8539     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8540     return LHSTy;
8541   }
8542   if (RHSTy->isObjCIdType() &&
8543       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8544     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8545     return RHSTy;
8546   }
8547   // And the same for struct objc_selector* / SEL
8548   if (Context.isObjCSelType(LHSTy) &&
8549       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8550     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8551     return LHSTy;
8552   }
8553   if (Context.isObjCSelType(RHSTy) &&
8554       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8555     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8556     return RHSTy;
8557   }
8558   // Check constraints for Objective-C object pointers types.
8559   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8560 
8561     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8562       // Two identical object pointer types are always compatible.
8563       return LHSTy;
8564     }
8565     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8566     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8567     QualType compositeType = LHSTy;
8568 
8569     // If both operands are interfaces and either operand can be
8570     // assigned to the other, use that type as the composite
8571     // type. This allows
8572     //   xxx ? (A*) a : (B*) b
8573     // where B is a subclass of A.
8574     //
8575     // Additionally, as for assignment, if either type is 'id'
8576     // allow silent coercion. Finally, if the types are
8577     // incompatible then make sure to use 'id' as the composite
8578     // type so the result is acceptable for sending messages to.
8579 
8580     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8581     // It could return the composite type.
8582     if (!(compositeType =
8583           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8584       // Nothing more to do.
8585     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8586       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8587     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8588       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8589     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8590                 RHSOPT->isObjCQualifiedIdType()) &&
8591                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8592                                                          true)) {
8593       // Need to handle "id<xx>" explicitly.
8594       // GCC allows qualified id and any Objective-C type to devolve to
8595       // id. Currently localizing to here until clear this should be
8596       // part of ObjCQualifiedIdTypesAreCompatible.
8597       compositeType = Context.getObjCIdType();
8598     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8599       compositeType = Context.getObjCIdType();
8600     } else {
8601       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8602       << LHSTy << RHSTy
8603       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8604       QualType incompatTy = Context.getObjCIdType();
8605       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8606       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8607       return incompatTy;
8608     }
8609     // The object pointer types are compatible.
8610     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8611     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8612     return compositeType;
8613   }
8614   // Check Objective-C object pointer types and 'void *'
8615   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8616     if (getLangOpts().ObjCAutoRefCount) {
8617       // ARC forbids the implicit conversion of object pointers to 'void *',
8618       // so these types are not compatible.
8619       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8620           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8621       LHS = RHS = true;
8622       return QualType();
8623     }
8624     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8625     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8626     QualType destPointee
8627     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8628     QualType destType = Context.getPointerType(destPointee);
8629     // Add qualifiers if necessary.
8630     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8631     // Promote to void*.
8632     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8633     return destType;
8634   }
8635   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8636     if (getLangOpts().ObjCAutoRefCount) {
8637       // ARC forbids the implicit conversion of object pointers to 'void *',
8638       // so these types are not compatible.
8639       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8640           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8641       LHS = RHS = true;
8642       return QualType();
8643     }
8644     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8645     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8646     QualType destPointee
8647     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8648     QualType destType = Context.getPointerType(destPointee);
8649     // Add qualifiers if necessary.
8650     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8651     // Promote to void*.
8652     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8653     return destType;
8654   }
8655   return QualType();
8656 }
8657 
8658 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8659 /// ParenRange in parentheses.
8660 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8661                                const PartialDiagnostic &Note,
8662                                SourceRange ParenRange) {
8663   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8664   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8665       EndLoc.isValid()) {
8666     Self.Diag(Loc, Note)
8667       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8668       << FixItHint::CreateInsertion(EndLoc, ")");
8669   } else {
8670     // We can't display the parentheses, so just show the bare note.
8671     Self.Diag(Loc, Note) << ParenRange;
8672   }
8673 }
8674 
8675 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8676   return BinaryOperator::isAdditiveOp(Opc) ||
8677          BinaryOperator::isMultiplicativeOp(Opc) ||
8678          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8679   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8680   // not any of the logical operators.  Bitwise-xor is commonly used as a
8681   // logical-xor because there is no logical-xor operator.  The logical
8682   // operators, including uses of xor, have a high false positive rate for
8683   // precedence warnings.
8684 }
8685 
8686 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8687 /// expression, either using a built-in or overloaded operator,
8688 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8689 /// expression.
8690 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8691                                    Expr **RHSExprs) {
8692   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8693   E = E->IgnoreImpCasts();
8694   E = E->IgnoreConversionOperatorSingleStep();
8695   E = E->IgnoreImpCasts();
8696   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8697     E = MTE->getSubExpr();
8698     E = E->IgnoreImpCasts();
8699   }
8700 
8701   // Built-in binary operator.
8702   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8703     if (IsArithmeticOp(OP->getOpcode())) {
8704       *Opcode = OP->getOpcode();
8705       *RHSExprs = OP->getRHS();
8706       return true;
8707     }
8708   }
8709 
8710   // Overloaded operator.
8711   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8712     if (Call->getNumArgs() != 2)
8713       return false;
8714 
8715     // Make sure this is really a binary operator that is safe to pass into
8716     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8717     OverloadedOperatorKind OO = Call->getOperator();
8718     if (OO < OO_Plus || OO > OO_Arrow ||
8719         OO == OO_PlusPlus || OO == OO_MinusMinus)
8720       return false;
8721 
8722     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8723     if (IsArithmeticOp(OpKind)) {
8724       *Opcode = OpKind;
8725       *RHSExprs = Call->getArg(1);
8726       return true;
8727     }
8728   }
8729 
8730   return false;
8731 }
8732 
8733 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8734 /// or is a logical expression such as (x==y) which has int type, but is
8735 /// commonly interpreted as boolean.
8736 static bool ExprLooksBoolean(Expr *E) {
8737   E = E->IgnoreParenImpCasts();
8738 
8739   if (E->getType()->isBooleanType())
8740     return true;
8741   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8742     return OP->isComparisonOp() || OP->isLogicalOp();
8743   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8744     return OP->getOpcode() == UO_LNot;
8745   if (E->getType()->isPointerType())
8746     return true;
8747   // FIXME: What about overloaded operator calls returning "unspecified boolean
8748   // type"s (commonly pointer-to-members)?
8749 
8750   return false;
8751 }
8752 
8753 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8754 /// and binary operator are mixed in a way that suggests the programmer assumed
8755 /// the conditional operator has higher precedence, for example:
8756 /// "int x = a + someBinaryCondition ? 1 : 2".
8757 static void DiagnoseConditionalPrecedence(Sema &Self,
8758                                           SourceLocation OpLoc,
8759                                           Expr *Condition,
8760                                           Expr *LHSExpr,
8761                                           Expr *RHSExpr) {
8762   BinaryOperatorKind CondOpcode;
8763   Expr *CondRHS;
8764 
8765   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8766     return;
8767   if (!ExprLooksBoolean(CondRHS))
8768     return;
8769 
8770   // The condition is an arithmetic binary expression, with a right-
8771   // hand side that looks boolean, so warn.
8772 
8773   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8774                         ? diag::warn_precedence_bitwise_conditional
8775                         : diag::warn_precedence_conditional;
8776 
8777   Self.Diag(OpLoc, DiagID)
8778       << Condition->getSourceRange()
8779       << BinaryOperator::getOpcodeStr(CondOpcode);
8780 
8781   SuggestParentheses(
8782       Self, OpLoc,
8783       Self.PDiag(diag::note_precedence_silence)
8784           << BinaryOperator::getOpcodeStr(CondOpcode),
8785       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8786 
8787   SuggestParentheses(Self, OpLoc,
8788                      Self.PDiag(diag::note_precedence_conditional_first),
8789                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8790 }
8791 
8792 /// Compute the nullability of a conditional expression.
8793 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8794                                               QualType LHSTy, QualType RHSTy,
8795                                               ASTContext &Ctx) {
8796   if (!ResTy->isAnyPointerType())
8797     return ResTy;
8798 
8799   auto GetNullability = [&Ctx](QualType Ty) {
8800     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8801     if (Kind) {
8802       // For our purposes, treat _Nullable_result as _Nullable.
8803       if (*Kind == NullabilityKind::NullableResult)
8804         return NullabilityKind::Nullable;
8805       return *Kind;
8806     }
8807     return NullabilityKind::Unspecified;
8808   };
8809 
8810   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8811   NullabilityKind MergedKind;
8812 
8813   // Compute nullability of a binary conditional expression.
8814   if (IsBin) {
8815     if (LHSKind == NullabilityKind::NonNull)
8816       MergedKind = NullabilityKind::NonNull;
8817     else
8818       MergedKind = RHSKind;
8819   // Compute nullability of a normal conditional expression.
8820   } else {
8821     if (LHSKind == NullabilityKind::Nullable ||
8822         RHSKind == NullabilityKind::Nullable)
8823       MergedKind = NullabilityKind::Nullable;
8824     else if (LHSKind == NullabilityKind::NonNull)
8825       MergedKind = RHSKind;
8826     else if (RHSKind == NullabilityKind::NonNull)
8827       MergedKind = LHSKind;
8828     else
8829       MergedKind = NullabilityKind::Unspecified;
8830   }
8831 
8832   // Return if ResTy already has the correct nullability.
8833   if (GetNullability(ResTy) == MergedKind)
8834     return ResTy;
8835 
8836   // Strip all nullability from ResTy.
8837   while (ResTy->getNullability(Ctx))
8838     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8839 
8840   // Create a new AttributedType with the new nullability kind.
8841   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8842   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8843 }
8844 
8845 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8846 /// in the case of a the GNU conditional expr extension.
8847 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8848                                     SourceLocation ColonLoc,
8849                                     Expr *CondExpr, Expr *LHSExpr,
8850                                     Expr *RHSExpr) {
8851   if (!Context.isDependenceAllowed()) {
8852     // C cannot handle TypoExpr nodes in the condition because it
8853     // doesn't handle dependent types properly, so make sure any TypoExprs have
8854     // been dealt with before checking the operands.
8855     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8856     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8857     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8858 
8859     if (!CondResult.isUsable())
8860       return ExprError();
8861 
8862     if (LHSExpr) {
8863       if (!LHSResult.isUsable())
8864         return ExprError();
8865     }
8866 
8867     if (!RHSResult.isUsable())
8868       return ExprError();
8869 
8870     CondExpr = CondResult.get();
8871     LHSExpr = LHSResult.get();
8872     RHSExpr = RHSResult.get();
8873   }
8874 
8875   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8876   // was the condition.
8877   OpaqueValueExpr *opaqueValue = nullptr;
8878   Expr *commonExpr = nullptr;
8879   if (!LHSExpr) {
8880     commonExpr = CondExpr;
8881     // Lower out placeholder types first.  This is important so that we don't
8882     // try to capture a placeholder. This happens in few cases in C++; such
8883     // as Objective-C++'s dictionary subscripting syntax.
8884     if (commonExpr->hasPlaceholderType()) {
8885       ExprResult result = CheckPlaceholderExpr(commonExpr);
8886       if (!result.isUsable()) return ExprError();
8887       commonExpr = result.get();
8888     }
8889     // We usually want to apply unary conversions *before* saving, except
8890     // in the special case of a C++ l-value conditional.
8891     if (!(getLangOpts().CPlusPlus
8892           && !commonExpr->isTypeDependent()
8893           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8894           && commonExpr->isGLValue()
8895           && commonExpr->isOrdinaryOrBitFieldObject()
8896           && RHSExpr->isOrdinaryOrBitFieldObject()
8897           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8898       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8899       if (commonRes.isInvalid())
8900         return ExprError();
8901       commonExpr = commonRes.get();
8902     }
8903 
8904     // If the common expression is a class or array prvalue, materialize it
8905     // so that we can safely refer to it multiple times.
8906     if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8907                                     commonExpr->getType()->isArrayType())) {
8908       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8909       if (MatExpr.isInvalid())
8910         return ExprError();
8911       commonExpr = MatExpr.get();
8912     }
8913 
8914     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8915                                                 commonExpr->getType(),
8916                                                 commonExpr->getValueKind(),
8917                                                 commonExpr->getObjectKind(),
8918                                                 commonExpr);
8919     LHSExpr = CondExpr = opaqueValue;
8920   }
8921 
8922   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8923   ExprValueKind VK = VK_PRValue;
8924   ExprObjectKind OK = OK_Ordinary;
8925   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8926   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8927                                              VK, OK, QuestionLoc);
8928   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8929       RHS.isInvalid())
8930     return ExprError();
8931 
8932   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8933                                 RHS.get());
8934 
8935   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8936 
8937   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8938                                          Context);
8939 
8940   if (!commonExpr)
8941     return new (Context)
8942         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8943                             RHS.get(), result, VK, OK);
8944 
8945   return new (Context) BinaryConditionalOperator(
8946       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8947       ColonLoc, result, VK, OK);
8948 }
8949 
8950 // Check if we have a conversion between incompatible cmse function pointer
8951 // types, that is, a conversion between a function pointer with the
8952 // cmse_nonsecure_call attribute and one without.
8953 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8954                                           QualType ToType) {
8955   if (const auto *ToFn =
8956           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8957     if (const auto *FromFn =
8958             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8959       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8960       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8961 
8962       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8963     }
8964   }
8965   return false;
8966 }
8967 
8968 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8969 // being closely modeled after the C99 spec:-). The odd characteristic of this
8970 // routine is it effectively iqnores the qualifiers on the top level pointee.
8971 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8972 // FIXME: add a couple examples in this comment.
8973 static Sema::AssignConvertType
8974 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8975   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8976   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8977 
8978   // get the "pointed to" type (ignoring qualifiers at the top level)
8979   const Type *lhptee, *rhptee;
8980   Qualifiers lhq, rhq;
8981   std::tie(lhptee, lhq) =
8982       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8983   std::tie(rhptee, rhq) =
8984       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8985 
8986   Sema::AssignConvertType ConvTy = Sema::Compatible;
8987 
8988   // C99 6.5.16.1p1: This following citation is common to constraints
8989   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8990   // qualifiers of the type *pointed to* by the right;
8991 
8992   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8993   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8994       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8995     // Ignore lifetime for further calculation.
8996     lhq.removeObjCLifetime();
8997     rhq.removeObjCLifetime();
8998   }
8999 
9000   if (!lhq.compatiblyIncludes(rhq)) {
9001     // Treat address-space mismatches as fatal.
9002     if (!lhq.isAddressSpaceSupersetOf(rhq))
9003       return Sema::IncompatiblePointerDiscardsQualifiers;
9004 
9005     // It's okay to add or remove GC or lifetime qualifiers when converting to
9006     // and from void*.
9007     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9008                         .compatiblyIncludes(
9009                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9010              && (lhptee->isVoidType() || rhptee->isVoidType()))
9011       ; // keep old
9012 
9013     // Treat lifetime mismatches as fatal.
9014     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9015       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9016 
9017     // For GCC/MS compatibility, other qualifier mismatches are treated
9018     // as still compatible in C.
9019     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9020   }
9021 
9022   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9023   // incomplete type and the other is a pointer to a qualified or unqualified
9024   // version of void...
9025   if (lhptee->isVoidType()) {
9026     if (rhptee->isIncompleteOrObjectType())
9027       return ConvTy;
9028 
9029     // As an extension, we allow cast to/from void* to function pointer.
9030     assert(rhptee->isFunctionType());
9031     return Sema::FunctionVoidPointer;
9032   }
9033 
9034   if (rhptee->isVoidType()) {
9035     if (lhptee->isIncompleteOrObjectType())
9036       return ConvTy;
9037 
9038     // As an extension, we allow cast to/from void* to function pointer.
9039     assert(lhptee->isFunctionType());
9040     return Sema::FunctionVoidPointer;
9041   }
9042 
9043   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9044   // unqualified versions of compatible types, ...
9045   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9046   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9047     // Check if the pointee types are compatible ignoring the sign.
9048     // We explicitly check for char so that we catch "char" vs
9049     // "unsigned char" on systems where "char" is unsigned.
9050     if (lhptee->isCharType())
9051       ltrans = S.Context.UnsignedCharTy;
9052     else if (lhptee->hasSignedIntegerRepresentation())
9053       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9054 
9055     if (rhptee->isCharType())
9056       rtrans = S.Context.UnsignedCharTy;
9057     else if (rhptee->hasSignedIntegerRepresentation())
9058       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9059 
9060     if (ltrans == rtrans) {
9061       // Types are compatible ignoring the sign. Qualifier incompatibility
9062       // takes priority over sign incompatibility because the sign
9063       // warning can be disabled.
9064       if (ConvTy != Sema::Compatible)
9065         return ConvTy;
9066 
9067       return Sema::IncompatiblePointerSign;
9068     }
9069 
9070     // If we are a multi-level pointer, it's possible that our issue is simply
9071     // one of qualification - e.g. char ** -> const char ** is not allowed. If
9072     // the eventual target type is the same and the pointers have the same
9073     // level of indirection, this must be the issue.
9074     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9075       do {
9076         std::tie(lhptee, lhq) =
9077           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9078         std::tie(rhptee, rhq) =
9079           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9080 
9081         // Inconsistent address spaces at this point is invalid, even if the
9082         // address spaces would be compatible.
9083         // FIXME: This doesn't catch address space mismatches for pointers of
9084         // different nesting levels, like:
9085         //   __local int *** a;
9086         //   int ** b = a;
9087         // It's not clear how to actually determine when such pointers are
9088         // invalidly incompatible.
9089         if (lhq.getAddressSpace() != rhq.getAddressSpace())
9090           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9091 
9092       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9093 
9094       if (lhptee == rhptee)
9095         return Sema::IncompatibleNestedPointerQualifiers;
9096     }
9097 
9098     // General pointer incompatibility takes priority over qualifiers.
9099     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9100       return Sema::IncompatibleFunctionPointer;
9101     return Sema::IncompatiblePointer;
9102   }
9103   if (!S.getLangOpts().CPlusPlus &&
9104       S.IsFunctionConversion(ltrans, rtrans, ltrans))
9105     return Sema::IncompatibleFunctionPointer;
9106   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9107     return Sema::IncompatibleFunctionPointer;
9108   return ConvTy;
9109 }
9110 
9111 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9112 /// block pointer types are compatible or whether a block and normal pointer
9113 /// are compatible. It is more restrict than comparing two function pointer
9114 // types.
9115 static Sema::AssignConvertType
9116 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9117                                     QualType RHSType) {
9118   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9119   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9120 
9121   QualType lhptee, rhptee;
9122 
9123   // get the "pointed to" type (ignoring qualifiers at the top level)
9124   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9125   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9126 
9127   // In C++, the types have to match exactly.
9128   if (S.getLangOpts().CPlusPlus)
9129     return Sema::IncompatibleBlockPointer;
9130 
9131   Sema::AssignConvertType ConvTy = Sema::Compatible;
9132 
9133   // For blocks we enforce that qualifiers are identical.
9134   Qualifiers LQuals = lhptee.getLocalQualifiers();
9135   Qualifiers RQuals = rhptee.getLocalQualifiers();
9136   if (S.getLangOpts().OpenCL) {
9137     LQuals.removeAddressSpace();
9138     RQuals.removeAddressSpace();
9139   }
9140   if (LQuals != RQuals)
9141     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9142 
9143   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9144   // assignment.
9145   // The current behavior is similar to C++ lambdas. A block might be
9146   // assigned to a variable iff its return type and parameters are compatible
9147   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9148   // an assignment. Presumably it should behave in way that a function pointer
9149   // assignment does in C, so for each parameter and return type:
9150   //  * CVR and address space of LHS should be a superset of CVR and address
9151   //  space of RHS.
9152   //  * unqualified types should be compatible.
9153   if (S.getLangOpts().OpenCL) {
9154     if (!S.Context.typesAreBlockPointerCompatible(
9155             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9156             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9157       return Sema::IncompatibleBlockPointer;
9158   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9159     return Sema::IncompatibleBlockPointer;
9160 
9161   return ConvTy;
9162 }
9163 
9164 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9165 /// for assignment compatibility.
9166 static Sema::AssignConvertType
9167 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9168                                    QualType RHSType) {
9169   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9170   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9171 
9172   if (LHSType->isObjCBuiltinType()) {
9173     // Class is not compatible with ObjC object pointers.
9174     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9175         !RHSType->isObjCQualifiedClassType())
9176       return Sema::IncompatiblePointer;
9177     return Sema::Compatible;
9178   }
9179   if (RHSType->isObjCBuiltinType()) {
9180     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9181         !LHSType->isObjCQualifiedClassType())
9182       return Sema::IncompatiblePointer;
9183     return Sema::Compatible;
9184   }
9185   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9186   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9187 
9188   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9189       // make an exception for id<P>
9190       !LHSType->isObjCQualifiedIdType())
9191     return Sema::CompatiblePointerDiscardsQualifiers;
9192 
9193   if (S.Context.typesAreCompatible(LHSType, RHSType))
9194     return Sema::Compatible;
9195   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9196     return Sema::IncompatibleObjCQualifiedId;
9197   return Sema::IncompatiblePointer;
9198 }
9199 
9200 Sema::AssignConvertType
9201 Sema::CheckAssignmentConstraints(SourceLocation Loc,
9202                                  QualType LHSType, QualType RHSType) {
9203   // Fake up an opaque expression.  We don't actually care about what
9204   // cast operations are required, so if CheckAssignmentConstraints
9205   // adds casts to this they'll be wasted, but fortunately that doesn't
9206   // usually happen on valid code.
9207   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9208   ExprResult RHSPtr = &RHSExpr;
9209   CastKind K;
9210 
9211   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9212 }
9213 
9214 /// This helper function returns true if QT is a vector type that has element
9215 /// type ElementType.
9216 static bool isVector(QualType QT, QualType ElementType) {
9217   if (const VectorType *VT = QT->getAs<VectorType>())
9218     return VT->getElementType().getCanonicalType() == ElementType;
9219   return false;
9220 }
9221 
9222 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9223 /// has code to accommodate several GCC extensions when type checking
9224 /// pointers. Here are some objectionable examples that GCC considers warnings:
9225 ///
9226 ///  int a, *pint;
9227 ///  short *pshort;
9228 ///  struct foo *pfoo;
9229 ///
9230 ///  pint = pshort; // warning: assignment from incompatible pointer type
9231 ///  a = pint; // warning: assignment makes integer from pointer without a cast
9232 ///  pint = a; // warning: assignment makes pointer from integer without a cast
9233 ///  pint = pfoo; // warning: assignment from incompatible pointer type
9234 ///
9235 /// As a result, the code for dealing with pointers is more complex than the
9236 /// C99 spec dictates.
9237 ///
9238 /// Sets 'Kind' for any result kind except Incompatible.
9239 Sema::AssignConvertType
9240 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9241                                  CastKind &Kind, bool ConvertRHS) {
9242   QualType RHSType = RHS.get()->getType();
9243   QualType OrigLHSType = LHSType;
9244 
9245   // Get canonical types.  We're not formatting these types, just comparing
9246   // them.
9247   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9248   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9249 
9250   // Common case: no conversion required.
9251   if (LHSType == RHSType) {
9252     Kind = CK_NoOp;
9253     return Compatible;
9254   }
9255 
9256   // If we have an atomic type, try a non-atomic assignment, then just add an
9257   // atomic qualification step.
9258   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9259     Sema::AssignConvertType result =
9260       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9261     if (result != Compatible)
9262       return result;
9263     if (Kind != CK_NoOp && ConvertRHS)
9264       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9265     Kind = CK_NonAtomicToAtomic;
9266     return Compatible;
9267   }
9268 
9269   // If the left-hand side is a reference type, then we are in a
9270   // (rare!) case where we've allowed the use of references in C,
9271   // e.g., as a parameter type in a built-in function. In this case,
9272   // just make sure that the type referenced is compatible with the
9273   // right-hand side type. The caller is responsible for adjusting
9274   // LHSType so that the resulting expression does not have reference
9275   // type.
9276   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9277     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9278       Kind = CK_LValueBitCast;
9279       return Compatible;
9280     }
9281     return Incompatible;
9282   }
9283 
9284   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9285   // to the same ExtVector type.
9286   if (LHSType->isExtVectorType()) {
9287     if (RHSType->isExtVectorType())
9288       return Incompatible;
9289     if (RHSType->isArithmeticType()) {
9290       // CK_VectorSplat does T -> vector T, so first cast to the element type.
9291       if (ConvertRHS)
9292         RHS = prepareVectorSplat(LHSType, RHS.get());
9293       Kind = CK_VectorSplat;
9294       return Compatible;
9295     }
9296   }
9297 
9298   // Conversions to or from vector type.
9299   if (LHSType->isVectorType() || RHSType->isVectorType()) {
9300     if (LHSType->isVectorType() && RHSType->isVectorType()) {
9301       // Allow assignments of an AltiVec vector type to an equivalent GCC
9302       // vector type and vice versa
9303       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9304         Kind = CK_BitCast;
9305         return Compatible;
9306       }
9307 
9308       // If we are allowing lax vector conversions, and LHS and RHS are both
9309       // vectors, the total size only needs to be the same. This is a bitcast;
9310       // no bits are changed but the result type is different.
9311       if (isLaxVectorConversion(RHSType, LHSType)) {
9312         Kind = CK_BitCast;
9313         return IncompatibleVectors;
9314       }
9315     }
9316 
9317     // When the RHS comes from another lax conversion (e.g. binops between
9318     // scalars and vectors) the result is canonicalized as a vector. When the
9319     // LHS is also a vector, the lax is allowed by the condition above. Handle
9320     // the case where LHS is a scalar.
9321     if (LHSType->isScalarType()) {
9322       const VectorType *VecType = RHSType->getAs<VectorType>();
9323       if (VecType && VecType->getNumElements() == 1 &&
9324           isLaxVectorConversion(RHSType, LHSType)) {
9325         ExprResult *VecExpr = &RHS;
9326         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9327         Kind = CK_BitCast;
9328         return Compatible;
9329       }
9330     }
9331 
9332     // Allow assignments between fixed-length and sizeless SVE vectors.
9333     if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9334         (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9335       if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9336           Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9337         Kind = CK_BitCast;
9338         return Compatible;
9339       }
9340 
9341     return Incompatible;
9342   }
9343 
9344   // Diagnose attempts to convert between __ibm128, __float128 and long double
9345   // where such conversions currently can't be handled.
9346   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9347     return Incompatible;
9348 
9349   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9350   // discards the imaginary part.
9351   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9352       !LHSType->getAs<ComplexType>())
9353     return Incompatible;
9354 
9355   // Arithmetic conversions.
9356   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9357       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9358     if (ConvertRHS)
9359       Kind = PrepareScalarCast(RHS, LHSType);
9360     return Compatible;
9361   }
9362 
9363   // Conversions to normal pointers.
9364   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9365     // U* -> T*
9366     if (isa<PointerType>(RHSType)) {
9367       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9368       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9369       if (AddrSpaceL != AddrSpaceR)
9370         Kind = CK_AddressSpaceConversion;
9371       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9372         Kind = CK_NoOp;
9373       else
9374         Kind = CK_BitCast;
9375       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9376     }
9377 
9378     // int -> T*
9379     if (RHSType->isIntegerType()) {
9380       Kind = CK_IntegralToPointer; // FIXME: null?
9381       return IntToPointer;
9382     }
9383 
9384     // C pointers are not compatible with ObjC object pointers,
9385     // with two exceptions:
9386     if (isa<ObjCObjectPointerType>(RHSType)) {
9387       //  - conversions to void*
9388       if (LHSPointer->getPointeeType()->isVoidType()) {
9389         Kind = CK_BitCast;
9390         return Compatible;
9391       }
9392 
9393       //  - conversions from 'Class' to the redefinition type
9394       if (RHSType->isObjCClassType() &&
9395           Context.hasSameType(LHSType,
9396                               Context.getObjCClassRedefinitionType())) {
9397         Kind = CK_BitCast;
9398         return Compatible;
9399       }
9400 
9401       Kind = CK_BitCast;
9402       return IncompatiblePointer;
9403     }
9404 
9405     // U^ -> void*
9406     if (RHSType->getAs<BlockPointerType>()) {
9407       if (LHSPointer->getPointeeType()->isVoidType()) {
9408         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9409         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9410                                 ->getPointeeType()
9411                                 .getAddressSpace();
9412         Kind =
9413             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9414         return Compatible;
9415       }
9416     }
9417 
9418     return Incompatible;
9419   }
9420 
9421   // Conversions to block pointers.
9422   if (isa<BlockPointerType>(LHSType)) {
9423     // U^ -> T^
9424     if (RHSType->isBlockPointerType()) {
9425       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9426                               ->getPointeeType()
9427                               .getAddressSpace();
9428       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9429                               ->getPointeeType()
9430                               .getAddressSpace();
9431       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9432       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9433     }
9434 
9435     // int or null -> T^
9436     if (RHSType->isIntegerType()) {
9437       Kind = CK_IntegralToPointer; // FIXME: null
9438       return IntToBlockPointer;
9439     }
9440 
9441     // id -> T^
9442     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9443       Kind = CK_AnyPointerToBlockPointerCast;
9444       return Compatible;
9445     }
9446 
9447     // void* -> T^
9448     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9449       if (RHSPT->getPointeeType()->isVoidType()) {
9450         Kind = CK_AnyPointerToBlockPointerCast;
9451         return Compatible;
9452       }
9453 
9454     return Incompatible;
9455   }
9456 
9457   // Conversions to Objective-C pointers.
9458   if (isa<ObjCObjectPointerType>(LHSType)) {
9459     // A* -> B*
9460     if (RHSType->isObjCObjectPointerType()) {
9461       Kind = CK_BitCast;
9462       Sema::AssignConvertType result =
9463         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9464       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9465           result == Compatible &&
9466           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9467         result = IncompatibleObjCWeakRef;
9468       return result;
9469     }
9470 
9471     // int or null -> A*
9472     if (RHSType->isIntegerType()) {
9473       Kind = CK_IntegralToPointer; // FIXME: null
9474       return IntToPointer;
9475     }
9476 
9477     // In general, C pointers are not compatible with ObjC object pointers,
9478     // with two exceptions:
9479     if (isa<PointerType>(RHSType)) {
9480       Kind = CK_CPointerToObjCPointerCast;
9481 
9482       //  - conversions from 'void*'
9483       if (RHSType->isVoidPointerType()) {
9484         return Compatible;
9485       }
9486 
9487       //  - conversions to 'Class' from its redefinition type
9488       if (LHSType->isObjCClassType() &&
9489           Context.hasSameType(RHSType,
9490                               Context.getObjCClassRedefinitionType())) {
9491         return Compatible;
9492       }
9493 
9494       return IncompatiblePointer;
9495     }
9496 
9497     // Only under strict condition T^ is compatible with an Objective-C pointer.
9498     if (RHSType->isBlockPointerType() &&
9499         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9500       if (ConvertRHS)
9501         maybeExtendBlockObject(RHS);
9502       Kind = CK_BlockPointerToObjCPointerCast;
9503       return Compatible;
9504     }
9505 
9506     return Incompatible;
9507   }
9508 
9509   // Conversions from pointers that are not covered by the above.
9510   if (isa<PointerType>(RHSType)) {
9511     // T* -> _Bool
9512     if (LHSType == Context.BoolTy) {
9513       Kind = CK_PointerToBoolean;
9514       return Compatible;
9515     }
9516 
9517     // T* -> int
9518     if (LHSType->isIntegerType()) {
9519       Kind = CK_PointerToIntegral;
9520       return PointerToInt;
9521     }
9522 
9523     return Incompatible;
9524   }
9525 
9526   // Conversions from Objective-C pointers that are not covered by the above.
9527   if (isa<ObjCObjectPointerType>(RHSType)) {
9528     // T* -> _Bool
9529     if (LHSType == Context.BoolTy) {
9530       Kind = CK_PointerToBoolean;
9531       return Compatible;
9532     }
9533 
9534     // T* -> int
9535     if (LHSType->isIntegerType()) {
9536       Kind = CK_PointerToIntegral;
9537       return PointerToInt;
9538     }
9539 
9540     return Incompatible;
9541   }
9542 
9543   // struct A -> struct B
9544   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9545     if (Context.typesAreCompatible(LHSType, RHSType)) {
9546       Kind = CK_NoOp;
9547       return Compatible;
9548     }
9549   }
9550 
9551   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9552     Kind = CK_IntToOCLSampler;
9553     return Compatible;
9554   }
9555 
9556   return Incompatible;
9557 }
9558 
9559 /// Constructs a transparent union from an expression that is
9560 /// used to initialize the transparent union.
9561 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9562                                       ExprResult &EResult, QualType UnionType,
9563                                       FieldDecl *Field) {
9564   // Build an initializer list that designates the appropriate member
9565   // of the transparent union.
9566   Expr *E = EResult.get();
9567   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9568                                                    E, SourceLocation());
9569   Initializer->setType(UnionType);
9570   Initializer->setInitializedFieldInUnion(Field);
9571 
9572   // Build a compound literal constructing a value of the transparent
9573   // union type from this initializer list.
9574   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9575   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9576                                         VK_PRValue, Initializer, false);
9577 }
9578 
9579 Sema::AssignConvertType
9580 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9581                                                ExprResult &RHS) {
9582   QualType RHSType = RHS.get()->getType();
9583 
9584   // If the ArgType is a Union type, we want to handle a potential
9585   // transparent_union GCC extension.
9586   const RecordType *UT = ArgType->getAsUnionType();
9587   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9588     return Incompatible;
9589 
9590   // The field to initialize within the transparent union.
9591   RecordDecl *UD = UT->getDecl();
9592   FieldDecl *InitField = nullptr;
9593   // It's compatible if the expression matches any of the fields.
9594   for (auto *it : UD->fields()) {
9595     if (it->getType()->isPointerType()) {
9596       // If the transparent union contains a pointer type, we allow:
9597       // 1) void pointer
9598       // 2) null pointer constant
9599       if (RHSType->isPointerType())
9600         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9601           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9602           InitField = it;
9603           break;
9604         }
9605 
9606       if (RHS.get()->isNullPointerConstant(Context,
9607                                            Expr::NPC_ValueDependentIsNull)) {
9608         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9609                                 CK_NullToPointer);
9610         InitField = it;
9611         break;
9612       }
9613     }
9614 
9615     CastKind Kind;
9616     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9617           == Compatible) {
9618       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9619       InitField = it;
9620       break;
9621     }
9622   }
9623 
9624   if (!InitField)
9625     return Incompatible;
9626 
9627   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9628   return Compatible;
9629 }
9630 
9631 Sema::AssignConvertType
9632 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9633                                        bool Diagnose,
9634                                        bool DiagnoseCFAudited,
9635                                        bool ConvertRHS) {
9636   // We need to be able to tell the caller whether we diagnosed a problem, if
9637   // they ask us to issue diagnostics.
9638   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9639 
9640   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9641   // we can't avoid *all* modifications at the moment, so we need some somewhere
9642   // to put the updated value.
9643   ExprResult LocalRHS = CallerRHS;
9644   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9645 
9646   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9647     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9648       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9649           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9650         Diag(RHS.get()->getExprLoc(),
9651              diag::warn_noderef_to_dereferenceable_pointer)
9652             << RHS.get()->getSourceRange();
9653       }
9654     }
9655   }
9656 
9657   if (getLangOpts().CPlusPlus) {
9658     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9659       // C++ 5.17p3: If the left operand is not of class type, the
9660       // expression is implicitly converted (C++ 4) to the
9661       // cv-unqualified type of the left operand.
9662       QualType RHSType = RHS.get()->getType();
9663       if (Diagnose) {
9664         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9665                                         AA_Assigning);
9666       } else {
9667         ImplicitConversionSequence ICS =
9668             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9669                                   /*SuppressUserConversions=*/false,
9670                                   AllowedExplicit::None,
9671                                   /*InOverloadResolution=*/false,
9672                                   /*CStyle=*/false,
9673                                   /*AllowObjCWritebackConversion=*/false);
9674         if (ICS.isFailure())
9675           return Incompatible;
9676         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9677                                         ICS, AA_Assigning);
9678       }
9679       if (RHS.isInvalid())
9680         return Incompatible;
9681       Sema::AssignConvertType result = Compatible;
9682       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9683           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9684         result = IncompatibleObjCWeakRef;
9685       return result;
9686     }
9687 
9688     // FIXME: Currently, we fall through and treat C++ classes like C
9689     // structures.
9690     // FIXME: We also fall through for atomics; not sure what should
9691     // happen there, though.
9692   } else if (RHS.get()->getType() == Context.OverloadTy) {
9693     // As a set of extensions to C, we support overloading on functions. These
9694     // functions need to be resolved here.
9695     DeclAccessPair DAP;
9696     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9697             RHS.get(), LHSType, /*Complain=*/false, DAP))
9698       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9699     else
9700       return Incompatible;
9701   }
9702 
9703   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9704   // a null pointer constant.
9705   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9706        LHSType->isBlockPointerType()) &&
9707       RHS.get()->isNullPointerConstant(Context,
9708                                        Expr::NPC_ValueDependentIsNull)) {
9709     if (Diagnose || ConvertRHS) {
9710       CastKind Kind;
9711       CXXCastPath Path;
9712       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9713                              /*IgnoreBaseAccess=*/false, Diagnose);
9714       if (ConvertRHS)
9715         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9716     }
9717     return Compatible;
9718   }
9719 
9720   // OpenCL queue_t type assignment.
9721   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9722                                  Context, Expr::NPC_ValueDependentIsNull)) {
9723     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9724     return Compatible;
9725   }
9726 
9727   // This check seems unnatural, however it is necessary to ensure the proper
9728   // conversion of functions/arrays. If the conversion were done for all
9729   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9730   // expressions that suppress this implicit conversion (&, sizeof).
9731   //
9732   // Suppress this for references: C++ 8.5.3p5.
9733   if (!LHSType->isReferenceType()) {
9734     // FIXME: We potentially allocate here even if ConvertRHS is false.
9735     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9736     if (RHS.isInvalid())
9737       return Incompatible;
9738   }
9739   CastKind Kind;
9740   Sema::AssignConvertType result =
9741     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9742 
9743   // C99 6.5.16.1p2: The value of the right operand is converted to the
9744   // type of the assignment expression.
9745   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9746   // so that we can use references in built-in functions even in C.
9747   // The getNonReferenceType() call makes sure that the resulting expression
9748   // does not have reference type.
9749   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9750     QualType Ty = LHSType.getNonLValueExprType(Context);
9751     Expr *E = RHS.get();
9752 
9753     // Check for various Objective-C errors. If we are not reporting
9754     // diagnostics and just checking for errors, e.g., during overload
9755     // resolution, return Incompatible to indicate the failure.
9756     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9757         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9758                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9759       if (!Diagnose)
9760         return Incompatible;
9761     }
9762     if (getLangOpts().ObjC &&
9763         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9764                                            E->getType(), E, Diagnose) ||
9765          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9766       if (!Diagnose)
9767         return Incompatible;
9768       // Replace the expression with a corrected version and continue so we
9769       // can find further errors.
9770       RHS = E;
9771       return Compatible;
9772     }
9773 
9774     if (ConvertRHS)
9775       RHS = ImpCastExprToType(E, Ty, Kind);
9776   }
9777 
9778   return result;
9779 }
9780 
9781 namespace {
9782 /// The original operand to an operator, prior to the application of the usual
9783 /// arithmetic conversions and converting the arguments of a builtin operator
9784 /// candidate.
9785 struct OriginalOperand {
9786   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9787     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9788       Op = MTE->getSubExpr();
9789     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9790       Op = BTE->getSubExpr();
9791     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9792       Orig = ICE->getSubExprAsWritten();
9793       Conversion = ICE->getConversionFunction();
9794     }
9795   }
9796 
9797   QualType getType() const { return Orig->getType(); }
9798 
9799   Expr *Orig;
9800   NamedDecl *Conversion;
9801 };
9802 }
9803 
9804 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9805                                ExprResult &RHS) {
9806   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9807 
9808   Diag(Loc, diag::err_typecheck_invalid_operands)
9809     << OrigLHS.getType() << OrigRHS.getType()
9810     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9811 
9812   // If a user-defined conversion was applied to either of the operands prior
9813   // to applying the built-in operator rules, tell the user about it.
9814   if (OrigLHS.Conversion) {
9815     Diag(OrigLHS.Conversion->getLocation(),
9816          diag::note_typecheck_invalid_operands_converted)
9817       << 0 << LHS.get()->getType();
9818   }
9819   if (OrigRHS.Conversion) {
9820     Diag(OrigRHS.Conversion->getLocation(),
9821          diag::note_typecheck_invalid_operands_converted)
9822       << 1 << RHS.get()->getType();
9823   }
9824 
9825   return QualType();
9826 }
9827 
9828 // Diagnose cases where a scalar was implicitly converted to a vector and
9829 // diagnose the underlying types. Otherwise, diagnose the error
9830 // as invalid vector logical operands for non-C++ cases.
9831 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9832                                             ExprResult &RHS) {
9833   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9834   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9835 
9836   bool LHSNatVec = LHSType->isVectorType();
9837   bool RHSNatVec = RHSType->isVectorType();
9838 
9839   if (!(LHSNatVec && RHSNatVec)) {
9840     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9841     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9842     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9843         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9844         << Vector->getSourceRange();
9845     return QualType();
9846   }
9847 
9848   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9849       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9850       << RHS.get()->getSourceRange();
9851 
9852   return QualType();
9853 }
9854 
9855 /// Try to convert a value of non-vector type to a vector type by converting
9856 /// the type to the element type of the vector and then performing a splat.
9857 /// If the language is OpenCL, we only use conversions that promote scalar
9858 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9859 /// for float->int.
9860 ///
9861 /// OpenCL V2.0 6.2.6.p2:
9862 /// An error shall occur if any scalar operand type has greater rank
9863 /// than the type of the vector element.
9864 ///
9865 /// \param scalar - if non-null, actually perform the conversions
9866 /// \return true if the operation fails (but without diagnosing the failure)
9867 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9868                                      QualType scalarTy,
9869                                      QualType vectorEltTy,
9870                                      QualType vectorTy,
9871                                      unsigned &DiagID) {
9872   // The conversion to apply to the scalar before splatting it,
9873   // if necessary.
9874   CastKind scalarCast = CK_NoOp;
9875 
9876   if (vectorEltTy->isIntegralType(S.Context)) {
9877     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9878         (scalarTy->isIntegerType() &&
9879          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9880       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9881       return true;
9882     }
9883     if (!scalarTy->isIntegralType(S.Context))
9884       return true;
9885     scalarCast = CK_IntegralCast;
9886   } else if (vectorEltTy->isRealFloatingType()) {
9887     if (scalarTy->isRealFloatingType()) {
9888       if (S.getLangOpts().OpenCL &&
9889           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9890         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9891         return true;
9892       }
9893       scalarCast = CK_FloatingCast;
9894     }
9895     else if (scalarTy->isIntegralType(S.Context))
9896       scalarCast = CK_IntegralToFloating;
9897     else
9898       return true;
9899   } else {
9900     return true;
9901   }
9902 
9903   // Adjust scalar if desired.
9904   if (scalar) {
9905     if (scalarCast != CK_NoOp)
9906       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9907     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9908   }
9909   return false;
9910 }
9911 
9912 /// Convert vector E to a vector with the same number of elements but different
9913 /// element type.
9914 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9915   const auto *VecTy = E->getType()->getAs<VectorType>();
9916   assert(VecTy && "Expression E must be a vector");
9917   QualType NewVecTy = S.Context.getVectorType(ElementType,
9918                                               VecTy->getNumElements(),
9919                                               VecTy->getVectorKind());
9920 
9921   // Look through the implicit cast. Return the subexpression if its type is
9922   // NewVecTy.
9923   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9924     if (ICE->getSubExpr()->getType() == NewVecTy)
9925       return ICE->getSubExpr();
9926 
9927   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9928   return S.ImpCastExprToType(E, NewVecTy, Cast);
9929 }
9930 
9931 /// Test if a (constant) integer Int can be casted to another integer type
9932 /// IntTy without losing precision.
9933 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9934                                       QualType OtherIntTy) {
9935   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9936 
9937   // Reject cases where the value of the Int is unknown as that would
9938   // possibly cause truncation, but accept cases where the scalar can be
9939   // demoted without loss of precision.
9940   Expr::EvalResult EVResult;
9941   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9942   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9943   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9944   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9945 
9946   if (CstInt) {
9947     // If the scalar is constant and is of a higher order and has more active
9948     // bits that the vector element type, reject it.
9949     llvm::APSInt Result = EVResult.Val.getInt();
9950     unsigned NumBits = IntSigned
9951                            ? (Result.isNegative() ? Result.getMinSignedBits()
9952                                                   : Result.getActiveBits())
9953                            : Result.getActiveBits();
9954     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9955       return true;
9956 
9957     // If the signedness of the scalar type and the vector element type
9958     // differs and the number of bits is greater than that of the vector
9959     // element reject it.
9960     return (IntSigned != OtherIntSigned &&
9961             NumBits > S.Context.getIntWidth(OtherIntTy));
9962   }
9963 
9964   // Reject cases where the value of the scalar is not constant and it's
9965   // order is greater than that of the vector element type.
9966   return (Order < 0);
9967 }
9968 
9969 /// Test if a (constant) integer Int can be casted to floating point type
9970 /// FloatTy without losing precision.
9971 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9972                                      QualType FloatTy) {
9973   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9974 
9975   // Determine if the integer constant can be expressed as a floating point
9976   // number of the appropriate type.
9977   Expr::EvalResult EVResult;
9978   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9979 
9980   uint64_t Bits = 0;
9981   if (CstInt) {
9982     // Reject constants that would be truncated if they were converted to
9983     // the floating point type. Test by simple to/from conversion.
9984     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9985     //        could be avoided if there was a convertFromAPInt method
9986     //        which could signal back if implicit truncation occurred.
9987     llvm::APSInt Result = EVResult.Val.getInt();
9988     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9989     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9990                            llvm::APFloat::rmTowardZero);
9991     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9992                              !IntTy->hasSignedIntegerRepresentation());
9993     bool Ignored = false;
9994     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9995                            &Ignored);
9996     if (Result != ConvertBack)
9997       return true;
9998   } else {
9999     // Reject types that cannot be fully encoded into the mantissa of
10000     // the float.
10001     Bits = S.Context.getTypeSize(IntTy);
10002     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10003         S.Context.getFloatTypeSemantics(FloatTy));
10004     if (Bits > FloatPrec)
10005       return true;
10006   }
10007 
10008   return false;
10009 }
10010 
10011 /// Attempt to convert and splat Scalar into a vector whose types matches
10012 /// Vector following GCC conversion rules. The rule is that implicit
10013 /// conversion can occur when Scalar can be casted to match Vector's element
10014 /// type without causing truncation of Scalar.
10015 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10016                                         ExprResult *Vector) {
10017   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10018   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10019   const VectorType *VT = VectorTy->getAs<VectorType>();
10020 
10021   assert(!isa<ExtVectorType>(VT) &&
10022          "ExtVectorTypes should not be handled here!");
10023 
10024   QualType VectorEltTy = VT->getElementType();
10025 
10026   // Reject cases where the vector element type or the scalar element type are
10027   // not integral or floating point types.
10028   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10029     return true;
10030 
10031   // The conversion to apply to the scalar before splatting it,
10032   // if necessary.
10033   CastKind ScalarCast = CK_NoOp;
10034 
10035   // Accept cases where the vector elements are integers and the scalar is
10036   // an integer.
10037   // FIXME: Notionally if the scalar was a floating point value with a precise
10038   //        integral representation, we could cast it to an appropriate integer
10039   //        type and then perform the rest of the checks here. GCC will perform
10040   //        this conversion in some cases as determined by the input language.
10041   //        We should accept it on a language independent basis.
10042   if (VectorEltTy->isIntegralType(S.Context) &&
10043       ScalarTy->isIntegralType(S.Context) &&
10044       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10045 
10046     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10047       return true;
10048 
10049     ScalarCast = CK_IntegralCast;
10050   } else if (VectorEltTy->isIntegralType(S.Context) &&
10051              ScalarTy->isRealFloatingType()) {
10052     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10053       ScalarCast = CK_FloatingToIntegral;
10054     else
10055       return true;
10056   } else if (VectorEltTy->isRealFloatingType()) {
10057     if (ScalarTy->isRealFloatingType()) {
10058 
10059       // Reject cases where the scalar type is not a constant and has a higher
10060       // Order than the vector element type.
10061       llvm::APFloat Result(0.0);
10062 
10063       // Determine whether this is a constant scalar. In the event that the
10064       // value is dependent (and thus cannot be evaluated by the constant
10065       // evaluator), skip the evaluation. This will then diagnose once the
10066       // expression is instantiated.
10067       bool CstScalar = Scalar->get()->isValueDependent() ||
10068                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
10069       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10070       if (!CstScalar && Order < 0)
10071         return true;
10072 
10073       // If the scalar cannot be safely casted to the vector element type,
10074       // reject it.
10075       if (CstScalar) {
10076         bool Truncated = false;
10077         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10078                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
10079         if (Truncated)
10080           return true;
10081       }
10082 
10083       ScalarCast = CK_FloatingCast;
10084     } else if (ScalarTy->isIntegralType(S.Context)) {
10085       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10086         return true;
10087 
10088       ScalarCast = CK_IntegralToFloating;
10089     } else
10090       return true;
10091   } else if (ScalarTy->isEnumeralType())
10092     return true;
10093 
10094   // Adjust scalar if desired.
10095   if (Scalar) {
10096     if (ScalarCast != CK_NoOp)
10097       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10098     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10099   }
10100   return false;
10101 }
10102 
10103 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10104                                    SourceLocation Loc, bool IsCompAssign,
10105                                    bool AllowBothBool,
10106                                    bool AllowBoolConversions) {
10107   if (!IsCompAssign) {
10108     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10109     if (LHS.isInvalid())
10110       return QualType();
10111   }
10112   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10113   if (RHS.isInvalid())
10114     return QualType();
10115 
10116   // For conversion purposes, we ignore any qualifiers.
10117   // For example, "const float" and "float" are equivalent.
10118   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10119   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10120 
10121   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10122   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10123   assert(LHSVecType || RHSVecType);
10124 
10125   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10126       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10127     return InvalidOperands(Loc, LHS, RHS);
10128 
10129   // AltiVec-style "vector bool op vector bool" combinations are allowed
10130   // for some operators but not others.
10131   if (!AllowBothBool &&
10132       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10133       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10134     return InvalidOperands(Loc, LHS, RHS);
10135 
10136   // If the vector types are identical, return.
10137   if (Context.hasSameType(LHSType, RHSType))
10138     return LHSType;
10139 
10140   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10141   if (LHSVecType && RHSVecType &&
10142       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10143     if (isa<ExtVectorType>(LHSVecType)) {
10144       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10145       return LHSType;
10146     }
10147 
10148     if (!IsCompAssign)
10149       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10150     return RHSType;
10151   }
10152 
10153   // AllowBoolConversions says that bool and non-bool AltiVec vectors
10154   // can be mixed, with the result being the non-bool type.  The non-bool
10155   // operand must have integer element type.
10156   if (AllowBoolConversions && LHSVecType && RHSVecType &&
10157       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10158       (Context.getTypeSize(LHSVecType->getElementType()) ==
10159        Context.getTypeSize(RHSVecType->getElementType()))) {
10160     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10161         LHSVecType->getElementType()->isIntegerType() &&
10162         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10163       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10164       return LHSType;
10165     }
10166     if (!IsCompAssign &&
10167         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10168         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10169         RHSVecType->getElementType()->isIntegerType()) {
10170       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10171       return RHSType;
10172     }
10173   }
10174 
10175   // Expressions containing fixed-length and sizeless SVE vectors are invalid
10176   // since the ambiguity can affect the ABI.
10177   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10178     const VectorType *VecType = SecondType->getAs<VectorType>();
10179     return FirstType->isSizelessBuiltinType() && VecType &&
10180            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10181             VecType->getVectorKind() ==
10182                 VectorType::SveFixedLengthPredicateVector);
10183   };
10184 
10185   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10186     Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10187     return QualType();
10188   }
10189 
10190   // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10191   // since the ambiguity can affect the ABI.
10192   auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10193     const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10194     const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10195 
10196     if (FirstVecType && SecondVecType)
10197       return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10198              (SecondVecType->getVectorKind() ==
10199                   VectorType::SveFixedLengthDataVector ||
10200               SecondVecType->getVectorKind() ==
10201                   VectorType::SveFixedLengthPredicateVector);
10202 
10203     return FirstType->isSizelessBuiltinType() && SecondVecType &&
10204            SecondVecType->getVectorKind() == VectorType::GenericVector;
10205   };
10206 
10207   if (IsSveGnuConversion(LHSType, RHSType) ||
10208       IsSveGnuConversion(RHSType, LHSType)) {
10209     Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10210     return QualType();
10211   }
10212 
10213   // If there's a vector type and a scalar, try to convert the scalar to
10214   // the vector element type and splat.
10215   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10216   if (!RHSVecType) {
10217     if (isa<ExtVectorType>(LHSVecType)) {
10218       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10219                                     LHSVecType->getElementType(), LHSType,
10220                                     DiagID))
10221         return LHSType;
10222     } else {
10223       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10224         return LHSType;
10225     }
10226   }
10227   if (!LHSVecType) {
10228     if (isa<ExtVectorType>(RHSVecType)) {
10229       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10230                                     LHSType, RHSVecType->getElementType(),
10231                                     RHSType, DiagID))
10232         return RHSType;
10233     } else {
10234       if (LHS.get()->isLValue() ||
10235           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10236         return RHSType;
10237     }
10238   }
10239 
10240   // FIXME: The code below also handles conversion between vectors and
10241   // non-scalars, we should break this down into fine grained specific checks
10242   // and emit proper diagnostics.
10243   QualType VecType = LHSVecType ? LHSType : RHSType;
10244   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10245   QualType OtherType = LHSVecType ? RHSType : LHSType;
10246   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10247   if (isLaxVectorConversion(OtherType, VecType)) {
10248     // If we're allowing lax vector conversions, only the total (data) size
10249     // needs to be the same. For non compound assignment, if one of the types is
10250     // scalar, the result is always the vector type.
10251     if (!IsCompAssign) {
10252       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10253       return VecType;
10254     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10255     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10256     // type. Note that this is already done by non-compound assignments in
10257     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10258     // <1 x T> -> T. The result is also a vector type.
10259     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10260                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10261       ExprResult *RHSExpr = &RHS;
10262       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10263       return VecType;
10264     }
10265   }
10266 
10267   // Okay, the expression is invalid.
10268 
10269   // If there's a non-vector, non-real operand, diagnose that.
10270   if ((!RHSVecType && !RHSType->isRealType()) ||
10271       (!LHSVecType && !LHSType->isRealType())) {
10272     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10273       << LHSType << RHSType
10274       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10275     return QualType();
10276   }
10277 
10278   // OpenCL V1.1 6.2.6.p1:
10279   // If the operands are of more than one vector type, then an error shall
10280   // occur. Implicit conversions between vector types are not permitted, per
10281   // section 6.2.1.
10282   if (getLangOpts().OpenCL &&
10283       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10284       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10285     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10286                                                            << RHSType;
10287     return QualType();
10288   }
10289 
10290 
10291   // If there is a vector type that is not a ExtVector and a scalar, we reach
10292   // this point if scalar could not be converted to the vector's element type
10293   // without truncation.
10294   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10295       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10296     QualType Scalar = LHSVecType ? RHSType : LHSType;
10297     QualType Vector = LHSVecType ? LHSType : RHSType;
10298     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10299     Diag(Loc,
10300          diag::err_typecheck_vector_not_convertable_implict_truncation)
10301         << ScalarOrVector << Scalar << Vector;
10302 
10303     return QualType();
10304   }
10305 
10306   // Otherwise, use the generic diagnostic.
10307   Diag(Loc, DiagID)
10308     << LHSType << RHSType
10309     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10310   return QualType();
10311 }
10312 
10313 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10314 // expression.  These are mainly cases where the null pointer is used as an
10315 // integer instead of a pointer.
10316 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10317                                 SourceLocation Loc, bool IsCompare) {
10318   // The canonical way to check for a GNU null is with isNullPointerConstant,
10319   // but we use a bit of a hack here for speed; this is a relatively
10320   // hot path, and isNullPointerConstant is slow.
10321   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10322   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10323 
10324   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10325 
10326   // Avoid analyzing cases where the result will either be invalid (and
10327   // diagnosed as such) or entirely valid and not something to warn about.
10328   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10329       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10330     return;
10331 
10332   // Comparison operations would not make sense with a null pointer no matter
10333   // what the other expression is.
10334   if (!IsCompare) {
10335     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10336         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10337         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10338     return;
10339   }
10340 
10341   // The rest of the operations only make sense with a null pointer
10342   // if the other expression is a pointer.
10343   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10344       NonNullType->canDecayToPointerType())
10345     return;
10346 
10347   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10348       << LHSNull /* LHS is NULL */ << NonNullType
10349       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10350 }
10351 
10352 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10353                                           SourceLocation Loc) {
10354   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10355   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10356   if (!LUE || !RUE)
10357     return;
10358   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10359       RUE->getKind() != UETT_SizeOf)
10360     return;
10361 
10362   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10363   QualType LHSTy = LHSArg->getType();
10364   QualType RHSTy;
10365 
10366   if (RUE->isArgumentType())
10367     RHSTy = RUE->getArgumentType().getNonReferenceType();
10368   else
10369     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10370 
10371   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10372     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10373       return;
10374 
10375     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10376     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10377       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10378         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10379             << LHSArgDecl;
10380     }
10381   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10382     QualType ArrayElemTy = ArrayTy->getElementType();
10383     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10384         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10385         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10386         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10387       return;
10388     S.Diag(Loc, diag::warn_division_sizeof_array)
10389         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10390     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10391       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10392         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10393             << LHSArgDecl;
10394     }
10395 
10396     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10397   }
10398 }
10399 
10400 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10401                                                ExprResult &RHS,
10402                                                SourceLocation Loc, bool IsDiv) {
10403   // Check for division/remainder by zero.
10404   Expr::EvalResult RHSValue;
10405   if (!RHS.get()->isValueDependent() &&
10406       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10407       RHSValue.Val.getInt() == 0)
10408     S.DiagRuntimeBehavior(Loc, RHS.get(),
10409                           S.PDiag(diag::warn_remainder_division_by_zero)
10410                             << IsDiv << RHS.get()->getSourceRange());
10411 }
10412 
10413 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10414                                            SourceLocation Loc,
10415                                            bool IsCompAssign, bool IsDiv) {
10416   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10417 
10418   QualType LHSTy = LHS.get()->getType();
10419   QualType RHSTy = RHS.get()->getType();
10420   if (LHSTy->isVectorType() || RHSTy->isVectorType())
10421     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10422                                /*AllowBothBool*/getLangOpts().AltiVec,
10423                                /*AllowBoolConversions*/false);
10424   if (!IsDiv &&
10425       (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10426     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10427   // For division, only matrix-by-scalar is supported. Other combinations with
10428   // matrix types are invalid.
10429   if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10430     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10431 
10432   QualType compType = UsualArithmeticConversions(
10433       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10434   if (LHS.isInvalid() || RHS.isInvalid())
10435     return QualType();
10436 
10437 
10438   if (compType.isNull() || !compType->isArithmeticType())
10439     return InvalidOperands(Loc, LHS, RHS);
10440   if (IsDiv) {
10441     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10442     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10443   }
10444   return compType;
10445 }
10446 
10447 QualType Sema::CheckRemainderOperands(
10448   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10449   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10450 
10451   if (LHS.get()->getType()->isVectorType() ||
10452       RHS.get()->getType()->isVectorType()) {
10453     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10454         RHS.get()->getType()->hasIntegerRepresentation())
10455       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10456                                  /*AllowBothBool*/getLangOpts().AltiVec,
10457                                  /*AllowBoolConversions*/false);
10458     return InvalidOperands(Loc, LHS, RHS);
10459   }
10460 
10461   QualType compType = UsualArithmeticConversions(
10462       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10463   if (LHS.isInvalid() || RHS.isInvalid())
10464     return QualType();
10465 
10466   if (compType.isNull() || !compType->isIntegerType())
10467     return InvalidOperands(Loc, LHS, RHS);
10468   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10469   return compType;
10470 }
10471 
10472 /// Diagnose invalid arithmetic on two void pointers.
10473 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10474                                                 Expr *LHSExpr, Expr *RHSExpr) {
10475   S.Diag(Loc, S.getLangOpts().CPlusPlus
10476                 ? diag::err_typecheck_pointer_arith_void_type
10477                 : diag::ext_gnu_void_ptr)
10478     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10479                             << RHSExpr->getSourceRange();
10480 }
10481 
10482 /// Diagnose invalid arithmetic on a void pointer.
10483 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10484                                             Expr *Pointer) {
10485   S.Diag(Loc, S.getLangOpts().CPlusPlus
10486                 ? diag::err_typecheck_pointer_arith_void_type
10487                 : diag::ext_gnu_void_ptr)
10488     << 0 /* one pointer */ << Pointer->getSourceRange();
10489 }
10490 
10491 /// Diagnose invalid arithmetic on a null pointer.
10492 ///
10493 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10494 /// idiom, which we recognize as a GNU extension.
10495 ///
10496 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10497                                             Expr *Pointer, bool IsGNUIdiom) {
10498   if (IsGNUIdiom)
10499     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10500       << Pointer->getSourceRange();
10501   else
10502     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10503       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10504 }
10505 
10506 /// Diagnose invalid subraction on a null pointer.
10507 ///
10508 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10509                                              Expr *Pointer, bool BothNull) {
10510   // Null - null is valid in C++ [expr.add]p7
10511   if (BothNull && S.getLangOpts().CPlusPlus)
10512     return;
10513 
10514   // Is this s a macro from a system header?
10515   if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10516     return;
10517 
10518   S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
10519       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10520 }
10521 
10522 /// Diagnose invalid arithmetic on two function pointers.
10523 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10524                                                     Expr *LHS, Expr *RHS) {
10525   assert(LHS->getType()->isAnyPointerType());
10526   assert(RHS->getType()->isAnyPointerType());
10527   S.Diag(Loc, S.getLangOpts().CPlusPlus
10528                 ? diag::err_typecheck_pointer_arith_function_type
10529                 : diag::ext_gnu_ptr_func_arith)
10530     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10531     // We only show the second type if it differs from the first.
10532     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10533                                                    RHS->getType())
10534     << RHS->getType()->getPointeeType()
10535     << LHS->getSourceRange() << RHS->getSourceRange();
10536 }
10537 
10538 /// Diagnose invalid arithmetic on a function pointer.
10539 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10540                                                 Expr *Pointer) {
10541   assert(Pointer->getType()->isAnyPointerType());
10542   S.Diag(Loc, S.getLangOpts().CPlusPlus
10543                 ? diag::err_typecheck_pointer_arith_function_type
10544                 : diag::ext_gnu_ptr_func_arith)
10545     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10546     << 0 /* one pointer, so only one type */
10547     << Pointer->getSourceRange();
10548 }
10549 
10550 /// Emit error if Operand is incomplete pointer type
10551 ///
10552 /// \returns True if pointer has incomplete type
10553 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10554                                                  Expr *Operand) {
10555   QualType ResType = Operand->getType();
10556   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10557     ResType = ResAtomicType->getValueType();
10558 
10559   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10560   QualType PointeeTy = ResType->getPointeeType();
10561   return S.RequireCompleteSizedType(
10562       Loc, PointeeTy,
10563       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10564       Operand->getSourceRange());
10565 }
10566 
10567 /// Check the validity of an arithmetic pointer operand.
10568 ///
10569 /// If the operand has pointer type, this code will check for pointer types
10570 /// which are invalid in arithmetic operations. These will be diagnosed
10571 /// appropriately, including whether or not the use is supported as an
10572 /// extension.
10573 ///
10574 /// \returns True when the operand is valid to use (even if as an extension).
10575 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10576                                             Expr *Operand) {
10577   QualType ResType = Operand->getType();
10578   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10579     ResType = ResAtomicType->getValueType();
10580 
10581   if (!ResType->isAnyPointerType()) return true;
10582 
10583   QualType PointeeTy = ResType->getPointeeType();
10584   if (PointeeTy->isVoidType()) {
10585     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10586     return !S.getLangOpts().CPlusPlus;
10587   }
10588   if (PointeeTy->isFunctionType()) {
10589     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10590     return !S.getLangOpts().CPlusPlus;
10591   }
10592 
10593   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10594 
10595   return true;
10596 }
10597 
10598 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10599 /// operands.
10600 ///
10601 /// This routine will diagnose any invalid arithmetic on pointer operands much
10602 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10603 /// for emitting a single diagnostic even for operations where both LHS and RHS
10604 /// are (potentially problematic) pointers.
10605 ///
10606 /// \returns True when the operand is valid to use (even if as an extension).
10607 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10608                                                 Expr *LHSExpr, Expr *RHSExpr) {
10609   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10610   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10611   if (!isLHSPointer && !isRHSPointer) return true;
10612 
10613   QualType LHSPointeeTy, RHSPointeeTy;
10614   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10615   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10616 
10617   // if both are pointers check if operation is valid wrt address spaces
10618   if (isLHSPointer && isRHSPointer) {
10619     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10620       S.Diag(Loc,
10621              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10622           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10623           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10624       return false;
10625     }
10626   }
10627 
10628   // Check for arithmetic on pointers to incomplete types.
10629   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10630   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10631   if (isLHSVoidPtr || isRHSVoidPtr) {
10632     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10633     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10634     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10635 
10636     return !S.getLangOpts().CPlusPlus;
10637   }
10638 
10639   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10640   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10641   if (isLHSFuncPtr || isRHSFuncPtr) {
10642     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10643     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10644                                                                 RHSExpr);
10645     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10646 
10647     return !S.getLangOpts().CPlusPlus;
10648   }
10649 
10650   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10651     return false;
10652   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10653     return false;
10654 
10655   return true;
10656 }
10657 
10658 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10659 /// literal.
10660 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10661                                   Expr *LHSExpr, Expr *RHSExpr) {
10662   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10663   Expr* IndexExpr = RHSExpr;
10664   if (!StrExpr) {
10665     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10666     IndexExpr = LHSExpr;
10667   }
10668 
10669   bool IsStringPlusInt = StrExpr &&
10670       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10671   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10672     return;
10673 
10674   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10675   Self.Diag(OpLoc, diag::warn_string_plus_int)
10676       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10677 
10678   // Only print a fixit for "str" + int, not for int + "str".
10679   if (IndexExpr == RHSExpr) {
10680     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10681     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10682         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10683         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10684         << FixItHint::CreateInsertion(EndLoc, "]");
10685   } else
10686     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10687 }
10688 
10689 /// Emit a warning when adding a char literal to a string.
10690 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10691                                    Expr *LHSExpr, Expr *RHSExpr) {
10692   const Expr *StringRefExpr = LHSExpr;
10693   const CharacterLiteral *CharExpr =
10694       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10695 
10696   if (!CharExpr) {
10697     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10698     StringRefExpr = RHSExpr;
10699   }
10700 
10701   if (!CharExpr || !StringRefExpr)
10702     return;
10703 
10704   const QualType StringType = StringRefExpr->getType();
10705 
10706   // Return if not a PointerType.
10707   if (!StringType->isAnyPointerType())
10708     return;
10709 
10710   // Return if not a CharacterType.
10711   if (!StringType->getPointeeType()->isAnyCharacterType())
10712     return;
10713 
10714   ASTContext &Ctx = Self.getASTContext();
10715   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10716 
10717   const QualType CharType = CharExpr->getType();
10718   if (!CharType->isAnyCharacterType() &&
10719       CharType->isIntegerType() &&
10720       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10721     Self.Diag(OpLoc, diag::warn_string_plus_char)
10722         << DiagRange << Ctx.CharTy;
10723   } else {
10724     Self.Diag(OpLoc, diag::warn_string_plus_char)
10725         << DiagRange << CharExpr->getType();
10726   }
10727 
10728   // Only print a fixit for str + char, not for char + str.
10729   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10730     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10731     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10732         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10733         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10734         << FixItHint::CreateInsertion(EndLoc, "]");
10735   } else {
10736     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10737   }
10738 }
10739 
10740 /// Emit error when two pointers are incompatible.
10741 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10742                                            Expr *LHSExpr, Expr *RHSExpr) {
10743   assert(LHSExpr->getType()->isAnyPointerType());
10744   assert(RHSExpr->getType()->isAnyPointerType());
10745   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10746     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10747     << RHSExpr->getSourceRange();
10748 }
10749 
10750 // C99 6.5.6
10751 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10752                                      SourceLocation Loc, BinaryOperatorKind Opc,
10753                                      QualType* CompLHSTy) {
10754   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10755 
10756   if (LHS.get()->getType()->isVectorType() ||
10757       RHS.get()->getType()->isVectorType()) {
10758     QualType compType = CheckVectorOperands(
10759         LHS, RHS, Loc, CompLHSTy,
10760         /*AllowBothBool*/getLangOpts().AltiVec,
10761         /*AllowBoolConversions*/getLangOpts().ZVector);
10762     if (CompLHSTy) *CompLHSTy = compType;
10763     return compType;
10764   }
10765 
10766   if (LHS.get()->getType()->isConstantMatrixType() ||
10767       RHS.get()->getType()->isConstantMatrixType()) {
10768     QualType compType =
10769         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10770     if (CompLHSTy)
10771       *CompLHSTy = compType;
10772     return compType;
10773   }
10774 
10775   QualType compType = UsualArithmeticConversions(
10776       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10777   if (LHS.isInvalid() || RHS.isInvalid())
10778     return QualType();
10779 
10780   // Diagnose "string literal" '+' int and string '+' "char literal".
10781   if (Opc == BO_Add) {
10782     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10783     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10784   }
10785 
10786   // handle the common case first (both operands are arithmetic).
10787   if (!compType.isNull() && compType->isArithmeticType()) {
10788     if (CompLHSTy) *CompLHSTy = compType;
10789     return compType;
10790   }
10791 
10792   // Type-checking.  Ultimately the pointer's going to be in PExp;
10793   // note that we bias towards the LHS being the pointer.
10794   Expr *PExp = LHS.get(), *IExp = RHS.get();
10795 
10796   bool isObjCPointer;
10797   if (PExp->getType()->isPointerType()) {
10798     isObjCPointer = false;
10799   } else if (PExp->getType()->isObjCObjectPointerType()) {
10800     isObjCPointer = true;
10801   } else {
10802     std::swap(PExp, IExp);
10803     if (PExp->getType()->isPointerType()) {
10804       isObjCPointer = false;
10805     } else if (PExp->getType()->isObjCObjectPointerType()) {
10806       isObjCPointer = true;
10807     } else {
10808       return InvalidOperands(Loc, LHS, RHS);
10809     }
10810   }
10811   assert(PExp->getType()->isAnyPointerType());
10812 
10813   if (!IExp->getType()->isIntegerType())
10814     return InvalidOperands(Loc, LHS, RHS);
10815 
10816   // Adding to a null pointer results in undefined behavior.
10817   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10818           Context, Expr::NPC_ValueDependentIsNotNull)) {
10819     // In C++ adding zero to a null pointer is defined.
10820     Expr::EvalResult KnownVal;
10821     if (!getLangOpts().CPlusPlus ||
10822         (!IExp->isValueDependent() &&
10823          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10824           KnownVal.Val.getInt() != 0))) {
10825       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10826       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10827           Context, BO_Add, PExp, IExp);
10828       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10829     }
10830   }
10831 
10832   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10833     return QualType();
10834 
10835   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10836     return QualType();
10837 
10838   // Check array bounds for pointer arithemtic
10839   CheckArrayAccess(PExp, IExp);
10840 
10841   if (CompLHSTy) {
10842     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10843     if (LHSTy.isNull()) {
10844       LHSTy = LHS.get()->getType();
10845       if (LHSTy->isPromotableIntegerType())
10846         LHSTy = Context.getPromotedIntegerType(LHSTy);
10847     }
10848     *CompLHSTy = LHSTy;
10849   }
10850 
10851   return PExp->getType();
10852 }
10853 
10854 // C99 6.5.6
10855 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10856                                         SourceLocation Loc,
10857                                         QualType* CompLHSTy) {
10858   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10859 
10860   if (LHS.get()->getType()->isVectorType() ||
10861       RHS.get()->getType()->isVectorType()) {
10862     QualType compType = CheckVectorOperands(
10863         LHS, RHS, Loc, CompLHSTy,
10864         /*AllowBothBool*/getLangOpts().AltiVec,
10865         /*AllowBoolConversions*/getLangOpts().ZVector);
10866     if (CompLHSTy) *CompLHSTy = compType;
10867     return compType;
10868   }
10869 
10870   if (LHS.get()->getType()->isConstantMatrixType() ||
10871       RHS.get()->getType()->isConstantMatrixType()) {
10872     QualType compType =
10873         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10874     if (CompLHSTy)
10875       *CompLHSTy = compType;
10876     return compType;
10877   }
10878 
10879   QualType compType = UsualArithmeticConversions(
10880       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10881   if (LHS.isInvalid() || RHS.isInvalid())
10882     return QualType();
10883 
10884   // Enforce type constraints: C99 6.5.6p3.
10885 
10886   // Handle the common case first (both operands are arithmetic).
10887   if (!compType.isNull() && compType->isArithmeticType()) {
10888     if (CompLHSTy) *CompLHSTy = compType;
10889     return compType;
10890   }
10891 
10892   // Either ptr - int   or   ptr - ptr.
10893   if (LHS.get()->getType()->isAnyPointerType()) {
10894     QualType lpointee = LHS.get()->getType()->getPointeeType();
10895 
10896     // Diagnose bad cases where we step over interface counts.
10897     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10898         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10899       return QualType();
10900 
10901     // The result type of a pointer-int computation is the pointer type.
10902     if (RHS.get()->getType()->isIntegerType()) {
10903       // Subtracting from a null pointer should produce a warning.
10904       // The last argument to the diagnose call says this doesn't match the
10905       // GNU int-to-pointer idiom.
10906       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10907                                            Expr::NPC_ValueDependentIsNotNull)) {
10908         // In C++ adding zero to a null pointer is defined.
10909         Expr::EvalResult KnownVal;
10910         if (!getLangOpts().CPlusPlus ||
10911             (!RHS.get()->isValueDependent() &&
10912              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10913               KnownVal.Val.getInt() != 0))) {
10914           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10915         }
10916       }
10917 
10918       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10919         return QualType();
10920 
10921       // Check array bounds for pointer arithemtic
10922       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10923                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10924 
10925       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10926       return LHS.get()->getType();
10927     }
10928 
10929     // Handle pointer-pointer subtractions.
10930     if (const PointerType *RHSPTy
10931           = RHS.get()->getType()->getAs<PointerType>()) {
10932       QualType rpointee = RHSPTy->getPointeeType();
10933 
10934       if (getLangOpts().CPlusPlus) {
10935         // Pointee types must be the same: C++ [expr.add]
10936         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10937           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10938         }
10939       } else {
10940         // Pointee types must be compatible C99 6.5.6p3
10941         if (!Context.typesAreCompatible(
10942                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10943                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10944           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10945           return QualType();
10946         }
10947       }
10948 
10949       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10950                                                LHS.get(), RHS.get()))
10951         return QualType();
10952 
10953       bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
10954           Context, Expr::NPC_ValueDependentIsNotNull);
10955       bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
10956           Context, Expr::NPC_ValueDependentIsNotNull);
10957 
10958       // Subtracting nullptr or from nullptr is suspect
10959       if (LHSIsNullPtr)
10960         diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
10961       if (RHSIsNullPtr)
10962         diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
10963 
10964       // The pointee type may have zero size.  As an extension, a structure or
10965       // union may have zero size or an array may have zero length.  In this
10966       // case subtraction does not make sense.
10967       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10968         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10969         if (ElementSize.isZero()) {
10970           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10971             << rpointee.getUnqualifiedType()
10972             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10973         }
10974       }
10975 
10976       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10977       return Context.getPointerDiffType();
10978     }
10979   }
10980 
10981   return InvalidOperands(Loc, LHS, RHS);
10982 }
10983 
10984 static bool isScopedEnumerationType(QualType T) {
10985   if (const EnumType *ET = T->getAs<EnumType>())
10986     return ET->getDecl()->isScoped();
10987   return false;
10988 }
10989 
10990 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10991                                    SourceLocation Loc, BinaryOperatorKind Opc,
10992                                    QualType LHSType) {
10993   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10994   // so skip remaining warnings as we don't want to modify values within Sema.
10995   if (S.getLangOpts().OpenCL)
10996     return;
10997 
10998   // Check right/shifter operand
10999   Expr::EvalResult RHSResult;
11000   if (RHS.get()->isValueDependent() ||
11001       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11002     return;
11003   llvm::APSInt Right = RHSResult.Val.getInt();
11004 
11005   if (Right.isNegative()) {
11006     S.DiagRuntimeBehavior(Loc, RHS.get(),
11007                           S.PDiag(diag::warn_shift_negative)
11008                             << RHS.get()->getSourceRange());
11009     return;
11010   }
11011 
11012   QualType LHSExprType = LHS.get()->getType();
11013   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11014   if (LHSExprType->isBitIntType())
11015     LeftSize = S.Context.getIntWidth(LHSExprType);
11016   else if (LHSExprType->isFixedPointType()) {
11017     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11018     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11019   }
11020   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11021   if (Right.uge(LeftBits)) {
11022     S.DiagRuntimeBehavior(Loc, RHS.get(),
11023                           S.PDiag(diag::warn_shift_gt_typewidth)
11024                             << RHS.get()->getSourceRange());
11025     return;
11026   }
11027 
11028   // FIXME: We probably need to handle fixed point types specially here.
11029   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11030     return;
11031 
11032   // When left shifting an ICE which is signed, we can check for overflow which
11033   // according to C++ standards prior to C++2a has undefined behavior
11034   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11035   // more than the maximum value representable in the result type, so never
11036   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11037   // expression is still probably a bug.)
11038   Expr::EvalResult LHSResult;
11039   if (LHS.get()->isValueDependent() ||
11040       LHSType->hasUnsignedIntegerRepresentation() ||
11041       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11042     return;
11043   llvm::APSInt Left = LHSResult.Val.getInt();
11044 
11045   // If LHS does not have a signed type and non-negative value
11046   // then, the behavior is undefined before C++2a. Warn about it.
11047   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
11048       !S.getLangOpts().CPlusPlus20) {
11049     S.DiagRuntimeBehavior(Loc, LHS.get(),
11050                           S.PDiag(diag::warn_shift_lhs_negative)
11051                             << LHS.get()->getSourceRange());
11052     return;
11053   }
11054 
11055   llvm::APInt ResultBits =
11056       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
11057   if (LeftBits.uge(ResultBits))
11058     return;
11059   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11060   Result = Result.shl(Right);
11061 
11062   // Print the bit representation of the signed integer as an unsigned
11063   // hexadecimal number.
11064   SmallString<40> HexResult;
11065   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11066 
11067   // If we are only missing a sign bit, this is less likely to result in actual
11068   // bugs -- if the result is cast back to an unsigned type, it will have the
11069   // expected value. Thus we place this behind a different warning that can be
11070   // turned off separately if needed.
11071   if (LeftBits == ResultBits - 1) {
11072     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11073         << HexResult << LHSType
11074         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11075     return;
11076   }
11077 
11078   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11079     << HexResult.str() << Result.getMinSignedBits() << LHSType
11080     << Left.getBitWidth() << LHS.get()->getSourceRange()
11081     << RHS.get()->getSourceRange();
11082 }
11083 
11084 /// Return the resulting type when a vector is shifted
11085 ///        by a scalar or vector shift amount.
11086 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11087                                  SourceLocation Loc, bool IsCompAssign) {
11088   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11089   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11090       !LHS.get()->getType()->isVectorType()) {
11091     S.Diag(Loc, diag::err_shift_rhs_only_vector)
11092       << RHS.get()->getType() << LHS.get()->getType()
11093       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11094     return QualType();
11095   }
11096 
11097   if (!IsCompAssign) {
11098     LHS = S.UsualUnaryConversions(LHS.get());
11099     if (LHS.isInvalid()) return QualType();
11100   }
11101 
11102   RHS = S.UsualUnaryConversions(RHS.get());
11103   if (RHS.isInvalid()) return QualType();
11104 
11105   QualType LHSType = LHS.get()->getType();
11106   // Note that LHS might be a scalar because the routine calls not only in
11107   // OpenCL case.
11108   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11109   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11110 
11111   // Note that RHS might not be a vector.
11112   QualType RHSType = RHS.get()->getType();
11113   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11114   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11115 
11116   // The operands need to be integers.
11117   if (!LHSEleType->isIntegerType()) {
11118     S.Diag(Loc, diag::err_typecheck_expect_int)
11119       << LHS.get()->getType() << LHS.get()->getSourceRange();
11120     return QualType();
11121   }
11122 
11123   if (!RHSEleType->isIntegerType()) {
11124     S.Diag(Loc, diag::err_typecheck_expect_int)
11125       << RHS.get()->getType() << RHS.get()->getSourceRange();
11126     return QualType();
11127   }
11128 
11129   if (!LHSVecTy) {
11130     assert(RHSVecTy);
11131     if (IsCompAssign)
11132       return RHSType;
11133     if (LHSEleType != RHSEleType) {
11134       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11135       LHSEleType = RHSEleType;
11136     }
11137     QualType VecTy =
11138         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11139     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11140     LHSType = VecTy;
11141   } else if (RHSVecTy) {
11142     // OpenCL v1.1 s6.3.j says that for vector types, the operators
11143     // are applied component-wise. So if RHS is a vector, then ensure
11144     // that the number of elements is the same as LHS...
11145     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11146       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11147         << LHS.get()->getType() << RHS.get()->getType()
11148         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11149       return QualType();
11150     }
11151     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11152       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11153       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11154       if (LHSBT != RHSBT &&
11155           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11156         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11157             << LHS.get()->getType() << RHS.get()->getType()
11158             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11159       }
11160     }
11161   } else {
11162     // ...else expand RHS to match the number of elements in LHS.
11163     QualType VecTy =
11164       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11165     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11166   }
11167 
11168   return LHSType;
11169 }
11170 
11171 // C99 6.5.7
11172 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11173                                   SourceLocation Loc, BinaryOperatorKind Opc,
11174                                   bool IsCompAssign) {
11175   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11176 
11177   // Vector shifts promote their scalar inputs to vector type.
11178   if (LHS.get()->getType()->isVectorType() ||
11179       RHS.get()->getType()->isVectorType()) {
11180     if (LangOpts.ZVector) {
11181       // The shift operators for the z vector extensions work basically
11182       // like general shifts, except that neither the LHS nor the RHS is
11183       // allowed to be a "vector bool".
11184       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11185         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11186           return InvalidOperands(Loc, LHS, RHS);
11187       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11188         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11189           return InvalidOperands(Loc, LHS, RHS);
11190     }
11191     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11192   }
11193 
11194   // Shifts don't perform usual arithmetic conversions, they just do integer
11195   // promotions on each operand. C99 6.5.7p3
11196 
11197   // For the LHS, do usual unary conversions, but then reset them away
11198   // if this is a compound assignment.
11199   ExprResult OldLHS = LHS;
11200   LHS = UsualUnaryConversions(LHS.get());
11201   if (LHS.isInvalid())
11202     return QualType();
11203   QualType LHSType = LHS.get()->getType();
11204   if (IsCompAssign) LHS = OldLHS;
11205 
11206   // The RHS is simpler.
11207   RHS = UsualUnaryConversions(RHS.get());
11208   if (RHS.isInvalid())
11209     return QualType();
11210   QualType RHSType = RHS.get()->getType();
11211 
11212   // C99 6.5.7p2: Each of the operands shall have integer type.
11213   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11214   if ((!LHSType->isFixedPointOrIntegerType() &&
11215        !LHSType->hasIntegerRepresentation()) ||
11216       !RHSType->hasIntegerRepresentation())
11217     return InvalidOperands(Loc, LHS, RHS);
11218 
11219   // C++0x: Don't allow scoped enums. FIXME: Use something better than
11220   // hasIntegerRepresentation() above instead of this.
11221   if (isScopedEnumerationType(LHSType) ||
11222       isScopedEnumerationType(RHSType)) {
11223     return InvalidOperands(Loc, LHS, RHS);
11224   }
11225   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11226 
11227   // "The type of the result is that of the promoted left operand."
11228   return LHSType;
11229 }
11230 
11231 /// Diagnose bad pointer comparisons.
11232 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11233                                               ExprResult &LHS, ExprResult &RHS,
11234                                               bool IsError) {
11235   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11236                       : diag::ext_typecheck_comparison_of_distinct_pointers)
11237     << LHS.get()->getType() << RHS.get()->getType()
11238     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11239 }
11240 
11241 /// Returns false if the pointers are converted to a composite type,
11242 /// true otherwise.
11243 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11244                                            ExprResult &LHS, ExprResult &RHS) {
11245   // C++ [expr.rel]p2:
11246   //   [...] Pointer conversions (4.10) and qualification
11247   //   conversions (4.4) are performed on pointer operands (or on
11248   //   a pointer operand and a null pointer constant) to bring
11249   //   them to their composite pointer type. [...]
11250   //
11251   // C++ [expr.eq]p1 uses the same notion for (in)equality
11252   // comparisons of pointers.
11253 
11254   QualType LHSType = LHS.get()->getType();
11255   QualType RHSType = RHS.get()->getType();
11256   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11257          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11258 
11259   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11260   if (T.isNull()) {
11261     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11262         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11263       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11264     else
11265       S.InvalidOperands(Loc, LHS, RHS);
11266     return true;
11267   }
11268 
11269   return false;
11270 }
11271 
11272 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11273                                                     ExprResult &LHS,
11274                                                     ExprResult &RHS,
11275                                                     bool IsError) {
11276   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11277                       : diag::ext_typecheck_comparison_of_fptr_to_void)
11278     << LHS.get()->getType() << RHS.get()->getType()
11279     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11280 }
11281 
11282 static bool isObjCObjectLiteral(ExprResult &E) {
11283   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11284   case Stmt::ObjCArrayLiteralClass:
11285   case Stmt::ObjCDictionaryLiteralClass:
11286   case Stmt::ObjCStringLiteralClass:
11287   case Stmt::ObjCBoxedExprClass:
11288     return true;
11289   default:
11290     // Note that ObjCBoolLiteral is NOT an object literal!
11291     return false;
11292   }
11293 }
11294 
11295 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11296   const ObjCObjectPointerType *Type =
11297     LHS->getType()->getAs<ObjCObjectPointerType>();
11298 
11299   // If this is not actually an Objective-C object, bail out.
11300   if (!Type)
11301     return false;
11302 
11303   // Get the LHS object's interface type.
11304   QualType InterfaceType = Type->getPointeeType();
11305 
11306   // If the RHS isn't an Objective-C object, bail out.
11307   if (!RHS->getType()->isObjCObjectPointerType())
11308     return false;
11309 
11310   // Try to find the -isEqual: method.
11311   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11312   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11313                                                       InterfaceType,
11314                                                       /*IsInstance=*/true);
11315   if (!Method) {
11316     if (Type->isObjCIdType()) {
11317       // For 'id', just check the global pool.
11318       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11319                                                   /*receiverId=*/true);
11320     } else {
11321       // Check protocols.
11322       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11323                                              /*IsInstance=*/true);
11324     }
11325   }
11326 
11327   if (!Method)
11328     return false;
11329 
11330   QualType T = Method->parameters()[0]->getType();
11331   if (!T->isObjCObjectPointerType())
11332     return false;
11333 
11334   QualType R = Method->getReturnType();
11335   if (!R->isScalarType())
11336     return false;
11337 
11338   return true;
11339 }
11340 
11341 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11342   FromE = FromE->IgnoreParenImpCasts();
11343   switch (FromE->getStmtClass()) {
11344     default:
11345       break;
11346     case Stmt::ObjCStringLiteralClass:
11347       // "string literal"
11348       return LK_String;
11349     case Stmt::ObjCArrayLiteralClass:
11350       // "array literal"
11351       return LK_Array;
11352     case Stmt::ObjCDictionaryLiteralClass:
11353       // "dictionary literal"
11354       return LK_Dictionary;
11355     case Stmt::BlockExprClass:
11356       return LK_Block;
11357     case Stmt::ObjCBoxedExprClass: {
11358       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11359       switch (Inner->getStmtClass()) {
11360         case Stmt::IntegerLiteralClass:
11361         case Stmt::FloatingLiteralClass:
11362         case Stmt::CharacterLiteralClass:
11363         case Stmt::ObjCBoolLiteralExprClass:
11364         case Stmt::CXXBoolLiteralExprClass:
11365           // "numeric literal"
11366           return LK_Numeric;
11367         case Stmt::ImplicitCastExprClass: {
11368           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11369           // Boolean literals can be represented by implicit casts.
11370           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11371             return LK_Numeric;
11372           break;
11373         }
11374         default:
11375           break;
11376       }
11377       return LK_Boxed;
11378     }
11379   }
11380   return LK_None;
11381 }
11382 
11383 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11384                                           ExprResult &LHS, ExprResult &RHS,
11385                                           BinaryOperator::Opcode Opc){
11386   Expr *Literal;
11387   Expr *Other;
11388   if (isObjCObjectLiteral(LHS)) {
11389     Literal = LHS.get();
11390     Other = RHS.get();
11391   } else {
11392     Literal = RHS.get();
11393     Other = LHS.get();
11394   }
11395 
11396   // Don't warn on comparisons against nil.
11397   Other = Other->IgnoreParenCasts();
11398   if (Other->isNullPointerConstant(S.getASTContext(),
11399                                    Expr::NPC_ValueDependentIsNotNull))
11400     return;
11401 
11402   // This should be kept in sync with warn_objc_literal_comparison.
11403   // LK_String should always be after the other literals, since it has its own
11404   // warning flag.
11405   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11406   assert(LiteralKind != Sema::LK_Block);
11407   if (LiteralKind == Sema::LK_None) {
11408     llvm_unreachable("Unknown Objective-C object literal kind");
11409   }
11410 
11411   if (LiteralKind == Sema::LK_String)
11412     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11413       << Literal->getSourceRange();
11414   else
11415     S.Diag(Loc, diag::warn_objc_literal_comparison)
11416       << LiteralKind << Literal->getSourceRange();
11417 
11418   if (BinaryOperator::isEqualityOp(Opc) &&
11419       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11420     SourceLocation Start = LHS.get()->getBeginLoc();
11421     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11422     CharSourceRange OpRange =
11423       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11424 
11425     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11426       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11427       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11428       << FixItHint::CreateInsertion(End, "]");
11429   }
11430 }
11431 
11432 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11433 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11434                                            ExprResult &RHS, SourceLocation Loc,
11435                                            BinaryOperatorKind Opc) {
11436   // Check that left hand side is !something.
11437   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11438   if (!UO || UO->getOpcode() != UO_LNot) return;
11439 
11440   // Only check if the right hand side is non-bool arithmetic type.
11441   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11442 
11443   // Make sure that the something in !something is not bool.
11444   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11445   if (SubExpr->isKnownToHaveBooleanValue()) return;
11446 
11447   // Emit warning.
11448   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11449   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11450       << Loc << IsBitwiseOp;
11451 
11452   // First note suggest !(x < y)
11453   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11454   SourceLocation FirstClose = RHS.get()->getEndLoc();
11455   FirstClose = S.getLocForEndOfToken(FirstClose);
11456   if (FirstClose.isInvalid())
11457     FirstOpen = SourceLocation();
11458   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11459       << IsBitwiseOp
11460       << FixItHint::CreateInsertion(FirstOpen, "(")
11461       << FixItHint::CreateInsertion(FirstClose, ")");
11462 
11463   // Second note suggests (!x) < y
11464   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11465   SourceLocation SecondClose = LHS.get()->getEndLoc();
11466   SecondClose = S.getLocForEndOfToken(SecondClose);
11467   if (SecondClose.isInvalid())
11468     SecondOpen = SourceLocation();
11469   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11470       << FixItHint::CreateInsertion(SecondOpen, "(")
11471       << FixItHint::CreateInsertion(SecondClose, ")");
11472 }
11473 
11474 // Returns true if E refers to a non-weak array.
11475 static bool checkForArray(const Expr *E) {
11476   const ValueDecl *D = nullptr;
11477   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11478     D = DR->getDecl();
11479   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11480     if (Mem->isImplicitAccess())
11481       D = Mem->getMemberDecl();
11482   }
11483   if (!D)
11484     return false;
11485   return D->getType()->isArrayType() && !D->isWeak();
11486 }
11487 
11488 /// Diagnose some forms of syntactically-obvious tautological comparison.
11489 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11490                                            Expr *LHS, Expr *RHS,
11491                                            BinaryOperatorKind Opc) {
11492   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11493   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11494 
11495   QualType LHSType = LHS->getType();
11496   QualType RHSType = RHS->getType();
11497   if (LHSType->hasFloatingRepresentation() ||
11498       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11499       S.inTemplateInstantiation())
11500     return;
11501 
11502   // Comparisons between two array types are ill-formed for operator<=>, so
11503   // we shouldn't emit any additional warnings about it.
11504   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11505     return;
11506 
11507   // For non-floating point types, check for self-comparisons of the form
11508   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11509   // often indicate logic errors in the program.
11510   //
11511   // NOTE: Don't warn about comparison expressions resulting from macro
11512   // expansion. Also don't warn about comparisons which are only self
11513   // comparisons within a template instantiation. The warnings should catch
11514   // obvious cases in the definition of the template anyways. The idea is to
11515   // warn when the typed comparison operator will always evaluate to the same
11516   // result.
11517 
11518   // Used for indexing into %select in warn_comparison_always
11519   enum {
11520     AlwaysConstant,
11521     AlwaysTrue,
11522     AlwaysFalse,
11523     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11524   };
11525 
11526   // C++2a [depr.array.comp]:
11527   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11528   //   operands of array type are deprecated.
11529   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11530       RHSStripped->getType()->isArrayType()) {
11531     S.Diag(Loc, diag::warn_depr_array_comparison)
11532         << LHS->getSourceRange() << RHS->getSourceRange()
11533         << LHSStripped->getType() << RHSStripped->getType();
11534     // Carry on to produce the tautological comparison warning, if this
11535     // expression is potentially-evaluated, we can resolve the array to a
11536     // non-weak declaration, and so on.
11537   }
11538 
11539   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11540     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11541       unsigned Result;
11542       switch (Opc) {
11543       case BO_EQ:
11544       case BO_LE:
11545       case BO_GE:
11546         Result = AlwaysTrue;
11547         break;
11548       case BO_NE:
11549       case BO_LT:
11550       case BO_GT:
11551         Result = AlwaysFalse;
11552         break;
11553       case BO_Cmp:
11554         Result = AlwaysEqual;
11555         break;
11556       default:
11557         Result = AlwaysConstant;
11558         break;
11559       }
11560       S.DiagRuntimeBehavior(Loc, nullptr,
11561                             S.PDiag(diag::warn_comparison_always)
11562                                 << 0 /*self-comparison*/
11563                                 << Result);
11564     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11565       // What is it always going to evaluate to?
11566       unsigned Result;
11567       switch (Opc) {
11568       case BO_EQ: // e.g. array1 == array2
11569         Result = AlwaysFalse;
11570         break;
11571       case BO_NE: // e.g. array1 != array2
11572         Result = AlwaysTrue;
11573         break;
11574       default: // e.g. array1 <= array2
11575         // The best we can say is 'a constant'
11576         Result = AlwaysConstant;
11577         break;
11578       }
11579       S.DiagRuntimeBehavior(Loc, nullptr,
11580                             S.PDiag(diag::warn_comparison_always)
11581                                 << 1 /*array comparison*/
11582                                 << Result);
11583     }
11584   }
11585 
11586   if (isa<CastExpr>(LHSStripped))
11587     LHSStripped = LHSStripped->IgnoreParenCasts();
11588   if (isa<CastExpr>(RHSStripped))
11589     RHSStripped = RHSStripped->IgnoreParenCasts();
11590 
11591   // Warn about comparisons against a string constant (unless the other
11592   // operand is null); the user probably wants string comparison function.
11593   Expr *LiteralString = nullptr;
11594   Expr *LiteralStringStripped = nullptr;
11595   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11596       !RHSStripped->isNullPointerConstant(S.Context,
11597                                           Expr::NPC_ValueDependentIsNull)) {
11598     LiteralString = LHS;
11599     LiteralStringStripped = LHSStripped;
11600   } else if ((isa<StringLiteral>(RHSStripped) ||
11601               isa<ObjCEncodeExpr>(RHSStripped)) &&
11602              !LHSStripped->isNullPointerConstant(S.Context,
11603                                           Expr::NPC_ValueDependentIsNull)) {
11604     LiteralString = RHS;
11605     LiteralStringStripped = RHSStripped;
11606   }
11607 
11608   if (LiteralString) {
11609     S.DiagRuntimeBehavior(Loc, nullptr,
11610                           S.PDiag(diag::warn_stringcompare)
11611                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11612                               << LiteralString->getSourceRange());
11613   }
11614 }
11615 
11616 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11617   switch (CK) {
11618   default: {
11619 #ifndef NDEBUG
11620     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11621                  << "\n";
11622 #endif
11623     llvm_unreachable("unhandled cast kind");
11624   }
11625   case CK_UserDefinedConversion:
11626     return ICK_Identity;
11627   case CK_LValueToRValue:
11628     return ICK_Lvalue_To_Rvalue;
11629   case CK_ArrayToPointerDecay:
11630     return ICK_Array_To_Pointer;
11631   case CK_FunctionToPointerDecay:
11632     return ICK_Function_To_Pointer;
11633   case CK_IntegralCast:
11634     return ICK_Integral_Conversion;
11635   case CK_FloatingCast:
11636     return ICK_Floating_Conversion;
11637   case CK_IntegralToFloating:
11638   case CK_FloatingToIntegral:
11639     return ICK_Floating_Integral;
11640   case CK_IntegralComplexCast:
11641   case CK_FloatingComplexCast:
11642   case CK_FloatingComplexToIntegralComplex:
11643   case CK_IntegralComplexToFloatingComplex:
11644     return ICK_Complex_Conversion;
11645   case CK_FloatingComplexToReal:
11646   case CK_FloatingRealToComplex:
11647   case CK_IntegralComplexToReal:
11648   case CK_IntegralRealToComplex:
11649     return ICK_Complex_Real;
11650   }
11651 }
11652 
11653 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11654                                              QualType FromType,
11655                                              SourceLocation Loc) {
11656   // Check for a narrowing implicit conversion.
11657   StandardConversionSequence SCS;
11658   SCS.setAsIdentityConversion();
11659   SCS.setToType(0, FromType);
11660   SCS.setToType(1, ToType);
11661   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11662     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11663 
11664   APValue PreNarrowingValue;
11665   QualType PreNarrowingType;
11666   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11667                                PreNarrowingType,
11668                                /*IgnoreFloatToIntegralConversion*/ true)) {
11669   case NK_Dependent_Narrowing:
11670     // Implicit conversion to a narrower type, but the expression is
11671     // value-dependent so we can't tell whether it's actually narrowing.
11672   case NK_Not_Narrowing:
11673     return false;
11674 
11675   case NK_Constant_Narrowing:
11676     // Implicit conversion to a narrower type, and the value is not a constant
11677     // expression.
11678     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11679         << /*Constant*/ 1
11680         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11681     return true;
11682 
11683   case NK_Variable_Narrowing:
11684     // Implicit conversion to a narrower type, and the value is not a constant
11685     // expression.
11686   case NK_Type_Narrowing:
11687     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11688         << /*Constant*/ 0 << FromType << ToType;
11689     // TODO: It's not a constant expression, but what if the user intended it
11690     // to be? Can we produce notes to help them figure out why it isn't?
11691     return true;
11692   }
11693   llvm_unreachable("unhandled case in switch");
11694 }
11695 
11696 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11697                                                          ExprResult &LHS,
11698                                                          ExprResult &RHS,
11699                                                          SourceLocation Loc) {
11700   QualType LHSType = LHS.get()->getType();
11701   QualType RHSType = RHS.get()->getType();
11702   // Dig out the original argument type and expression before implicit casts
11703   // were applied. These are the types/expressions we need to check the
11704   // [expr.spaceship] requirements against.
11705   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11706   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11707   QualType LHSStrippedType = LHSStripped.get()->getType();
11708   QualType RHSStrippedType = RHSStripped.get()->getType();
11709 
11710   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11711   // other is not, the program is ill-formed.
11712   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11713     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11714     return QualType();
11715   }
11716 
11717   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11718   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11719                     RHSStrippedType->isEnumeralType();
11720   if (NumEnumArgs == 1) {
11721     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11722     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11723     if (OtherTy->hasFloatingRepresentation()) {
11724       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11725       return QualType();
11726     }
11727   }
11728   if (NumEnumArgs == 2) {
11729     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11730     // type E, the operator yields the result of converting the operands
11731     // to the underlying type of E and applying <=> to the converted operands.
11732     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11733       S.InvalidOperands(Loc, LHS, RHS);
11734       return QualType();
11735     }
11736     QualType IntType =
11737         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11738     assert(IntType->isArithmeticType());
11739 
11740     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11741     // promote the boolean type, and all other promotable integer types, to
11742     // avoid this.
11743     if (IntType->isPromotableIntegerType())
11744       IntType = S.Context.getPromotedIntegerType(IntType);
11745 
11746     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11747     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11748     LHSType = RHSType = IntType;
11749   }
11750 
11751   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11752   // usual arithmetic conversions are applied to the operands.
11753   QualType Type =
11754       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11755   if (LHS.isInvalid() || RHS.isInvalid())
11756     return QualType();
11757   if (Type.isNull())
11758     return S.InvalidOperands(Loc, LHS, RHS);
11759 
11760   Optional<ComparisonCategoryType> CCT =
11761       getComparisonCategoryForBuiltinCmp(Type);
11762   if (!CCT)
11763     return S.InvalidOperands(Loc, LHS, RHS);
11764 
11765   bool HasNarrowing = checkThreeWayNarrowingConversion(
11766       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11767   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11768                                                    RHS.get()->getBeginLoc());
11769   if (HasNarrowing)
11770     return QualType();
11771 
11772   assert(!Type.isNull() && "composite type for <=> has not been set");
11773 
11774   return S.CheckComparisonCategoryType(
11775       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11776 }
11777 
11778 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11779                                                  ExprResult &RHS,
11780                                                  SourceLocation Loc,
11781                                                  BinaryOperatorKind Opc) {
11782   if (Opc == BO_Cmp)
11783     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11784 
11785   // C99 6.5.8p3 / C99 6.5.9p4
11786   QualType Type =
11787       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11788   if (LHS.isInvalid() || RHS.isInvalid())
11789     return QualType();
11790   if (Type.isNull())
11791     return S.InvalidOperands(Loc, LHS, RHS);
11792   assert(Type->isArithmeticType() || Type->isEnumeralType());
11793 
11794   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11795     return S.InvalidOperands(Loc, LHS, RHS);
11796 
11797   // Check for comparisons of floating point operands using != and ==.
11798   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11799     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11800 
11801   // The result of comparisons is 'bool' in C++, 'int' in C.
11802   return S.Context.getLogicalOperationType();
11803 }
11804 
11805 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11806   if (!NullE.get()->getType()->isAnyPointerType())
11807     return;
11808   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11809   if (!E.get()->getType()->isAnyPointerType() &&
11810       E.get()->isNullPointerConstant(Context,
11811                                      Expr::NPC_ValueDependentIsNotNull) ==
11812         Expr::NPCK_ZeroExpression) {
11813     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11814       if (CL->getValue() == 0)
11815         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11816             << NullValue
11817             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11818                                             NullValue ? "NULL" : "(void *)0");
11819     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11820         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11821         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11822         if (T == Context.CharTy)
11823           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11824               << NullValue
11825               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11826                                               NullValue ? "NULL" : "(void *)0");
11827       }
11828   }
11829 }
11830 
11831 // C99 6.5.8, C++ [expr.rel]
11832 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11833                                     SourceLocation Loc,
11834                                     BinaryOperatorKind Opc) {
11835   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11836   bool IsThreeWay = Opc == BO_Cmp;
11837   bool IsOrdered = IsRelational || IsThreeWay;
11838   auto IsAnyPointerType = [](ExprResult E) {
11839     QualType Ty = E.get()->getType();
11840     return Ty->isPointerType() || Ty->isMemberPointerType();
11841   };
11842 
11843   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11844   // type, array-to-pointer, ..., conversions are performed on both operands to
11845   // bring them to their composite type.
11846   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11847   // any type-related checks.
11848   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11849     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11850     if (LHS.isInvalid())
11851       return QualType();
11852     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11853     if (RHS.isInvalid())
11854       return QualType();
11855   } else {
11856     LHS = DefaultLvalueConversion(LHS.get());
11857     if (LHS.isInvalid())
11858       return QualType();
11859     RHS = DefaultLvalueConversion(RHS.get());
11860     if (RHS.isInvalid())
11861       return QualType();
11862   }
11863 
11864   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11865   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11866     CheckPtrComparisonWithNullChar(LHS, RHS);
11867     CheckPtrComparisonWithNullChar(RHS, LHS);
11868   }
11869 
11870   // Handle vector comparisons separately.
11871   if (LHS.get()->getType()->isVectorType() ||
11872       RHS.get()->getType()->isVectorType())
11873     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11874 
11875   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11876   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11877 
11878   QualType LHSType = LHS.get()->getType();
11879   QualType RHSType = RHS.get()->getType();
11880   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11881       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11882     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11883 
11884   const Expr::NullPointerConstantKind LHSNullKind =
11885       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11886   const Expr::NullPointerConstantKind RHSNullKind =
11887       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11888   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11889   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11890 
11891   auto computeResultTy = [&]() {
11892     if (Opc != BO_Cmp)
11893       return Context.getLogicalOperationType();
11894     assert(getLangOpts().CPlusPlus);
11895     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11896 
11897     QualType CompositeTy = LHS.get()->getType();
11898     assert(!CompositeTy->isReferenceType());
11899 
11900     Optional<ComparisonCategoryType> CCT =
11901         getComparisonCategoryForBuiltinCmp(CompositeTy);
11902     if (!CCT)
11903       return InvalidOperands(Loc, LHS, RHS);
11904 
11905     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11906       // P0946R0: Comparisons between a null pointer constant and an object
11907       // pointer result in std::strong_equality, which is ill-formed under
11908       // P1959R0.
11909       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11910           << (LHSIsNull ? LHS.get()->getSourceRange()
11911                         : RHS.get()->getSourceRange());
11912       return QualType();
11913     }
11914 
11915     return CheckComparisonCategoryType(
11916         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11917   };
11918 
11919   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11920     bool IsEquality = Opc == BO_EQ;
11921     if (RHSIsNull)
11922       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11923                                    RHS.get()->getSourceRange());
11924     else
11925       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11926                                    LHS.get()->getSourceRange());
11927   }
11928 
11929   if (IsOrdered && LHSType->isFunctionPointerType() &&
11930       RHSType->isFunctionPointerType()) {
11931     // Valid unless a relational comparison of function pointers
11932     bool IsError = Opc == BO_Cmp;
11933     auto DiagID =
11934         IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
11935         : getLangOpts().CPlusPlus
11936             ? diag::warn_typecheck_ordered_comparison_of_function_pointers
11937             : diag::ext_typecheck_ordered_comparison_of_function_pointers;
11938     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11939                       << RHS.get()->getSourceRange();
11940     if (IsError)
11941       return QualType();
11942   }
11943 
11944   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11945       (RHSType->isIntegerType() && !RHSIsNull)) {
11946     // Skip normal pointer conversion checks in this case; we have better
11947     // diagnostics for this below.
11948   } else if (getLangOpts().CPlusPlus) {
11949     // Equality comparison of a function pointer to a void pointer is invalid,
11950     // but we allow it as an extension.
11951     // FIXME: If we really want to allow this, should it be part of composite
11952     // pointer type computation so it works in conditionals too?
11953     if (!IsOrdered &&
11954         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11955          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11956       // This is a gcc extension compatibility comparison.
11957       // In a SFINAE context, we treat this as a hard error to maintain
11958       // conformance with the C++ standard.
11959       diagnoseFunctionPointerToVoidComparison(
11960           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11961 
11962       if (isSFINAEContext())
11963         return QualType();
11964 
11965       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11966       return computeResultTy();
11967     }
11968 
11969     // C++ [expr.eq]p2:
11970     //   If at least one operand is a pointer [...] bring them to their
11971     //   composite pointer type.
11972     // C++ [expr.spaceship]p6
11973     //  If at least one of the operands is of pointer type, [...] bring them
11974     //  to their composite pointer type.
11975     // C++ [expr.rel]p2:
11976     //   If both operands are pointers, [...] bring them to their composite
11977     //   pointer type.
11978     // For <=>, the only valid non-pointer types are arrays and functions, and
11979     // we already decayed those, so this is really the same as the relational
11980     // comparison rule.
11981     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11982             (IsOrdered ? 2 : 1) &&
11983         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11984                                          RHSType->isObjCObjectPointerType()))) {
11985       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11986         return QualType();
11987       return computeResultTy();
11988     }
11989   } else if (LHSType->isPointerType() &&
11990              RHSType->isPointerType()) { // C99 6.5.8p2
11991     // All of the following pointer-related warnings are GCC extensions, except
11992     // when handling null pointer constants.
11993     QualType LCanPointeeTy =
11994       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11995     QualType RCanPointeeTy =
11996       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11997 
11998     // C99 6.5.9p2 and C99 6.5.8p2
11999     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12000                                    RCanPointeeTy.getUnqualifiedType())) {
12001       if (IsRelational) {
12002         // Pointers both need to point to complete or incomplete types
12003         if ((LCanPointeeTy->isIncompleteType() !=
12004              RCanPointeeTy->isIncompleteType()) &&
12005             !getLangOpts().C11) {
12006           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12007               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12008               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12009               << RCanPointeeTy->isIncompleteType();
12010         }
12011       }
12012     } else if (!IsRelational &&
12013                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12014       // Valid unless comparison between non-null pointer and function pointer
12015       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12016           && !LHSIsNull && !RHSIsNull)
12017         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12018                                                 /*isError*/false);
12019     } else {
12020       // Invalid
12021       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12022     }
12023     if (LCanPointeeTy != RCanPointeeTy) {
12024       // Treat NULL constant as a special case in OpenCL.
12025       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12026         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12027           Diag(Loc,
12028                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12029               << LHSType << RHSType << 0 /* comparison */
12030               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12031         }
12032       }
12033       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12034       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12035       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12036                                                : CK_BitCast;
12037       if (LHSIsNull && !RHSIsNull)
12038         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12039       else
12040         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12041     }
12042     return computeResultTy();
12043   }
12044 
12045   if (getLangOpts().CPlusPlus) {
12046     // C++ [expr.eq]p4:
12047     //   Two operands of type std::nullptr_t or one operand of type
12048     //   std::nullptr_t and the other a null pointer constant compare equal.
12049     if (!IsOrdered && LHSIsNull && RHSIsNull) {
12050       if (LHSType->isNullPtrType()) {
12051         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12052         return computeResultTy();
12053       }
12054       if (RHSType->isNullPtrType()) {
12055         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12056         return computeResultTy();
12057       }
12058     }
12059 
12060     // Comparison of Objective-C pointers and block pointers against nullptr_t.
12061     // These aren't covered by the composite pointer type rules.
12062     if (!IsOrdered && RHSType->isNullPtrType() &&
12063         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12064       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12065       return computeResultTy();
12066     }
12067     if (!IsOrdered && LHSType->isNullPtrType() &&
12068         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12069       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12070       return computeResultTy();
12071     }
12072 
12073     if (IsRelational &&
12074         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12075          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12076       // HACK: Relational comparison of nullptr_t against a pointer type is
12077       // invalid per DR583, but we allow it within std::less<> and friends,
12078       // since otherwise common uses of it break.
12079       // FIXME: Consider removing this hack once LWG fixes std::less<> and
12080       // friends to have std::nullptr_t overload candidates.
12081       DeclContext *DC = CurContext;
12082       if (isa<FunctionDecl>(DC))
12083         DC = DC->getParent();
12084       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12085         if (CTSD->isInStdNamespace() &&
12086             llvm::StringSwitch<bool>(CTSD->getName())
12087                 .Cases("less", "less_equal", "greater", "greater_equal", true)
12088                 .Default(false)) {
12089           if (RHSType->isNullPtrType())
12090             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12091           else
12092             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12093           return computeResultTy();
12094         }
12095       }
12096     }
12097 
12098     // C++ [expr.eq]p2:
12099     //   If at least one operand is a pointer to member, [...] bring them to
12100     //   their composite pointer type.
12101     if (!IsOrdered &&
12102         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12103       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12104         return QualType();
12105       else
12106         return computeResultTy();
12107     }
12108   }
12109 
12110   // Handle block pointer types.
12111   if (!IsOrdered && LHSType->isBlockPointerType() &&
12112       RHSType->isBlockPointerType()) {
12113     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12114     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12115 
12116     if (!LHSIsNull && !RHSIsNull &&
12117         !Context.typesAreCompatible(lpointee, rpointee)) {
12118       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12119         << LHSType << RHSType << LHS.get()->getSourceRange()
12120         << RHS.get()->getSourceRange();
12121     }
12122     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12123     return computeResultTy();
12124   }
12125 
12126   // Allow block pointers to be compared with null pointer constants.
12127   if (!IsOrdered
12128       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12129           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12130     if (!LHSIsNull && !RHSIsNull) {
12131       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12132              ->getPointeeType()->isVoidType())
12133             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12134                 ->getPointeeType()->isVoidType())))
12135         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12136           << LHSType << RHSType << LHS.get()->getSourceRange()
12137           << RHS.get()->getSourceRange();
12138     }
12139     if (LHSIsNull && !RHSIsNull)
12140       LHS = ImpCastExprToType(LHS.get(), RHSType,
12141                               RHSType->isPointerType() ? CK_BitCast
12142                                 : CK_AnyPointerToBlockPointerCast);
12143     else
12144       RHS = ImpCastExprToType(RHS.get(), LHSType,
12145                               LHSType->isPointerType() ? CK_BitCast
12146                                 : CK_AnyPointerToBlockPointerCast);
12147     return computeResultTy();
12148   }
12149 
12150   if (LHSType->isObjCObjectPointerType() ||
12151       RHSType->isObjCObjectPointerType()) {
12152     const PointerType *LPT = LHSType->getAs<PointerType>();
12153     const PointerType *RPT = RHSType->getAs<PointerType>();
12154     if (LPT || RPT) {
12155       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12156       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12157 
12158       if (!LPtrToVoid && !RPtrToVoid &&
12159           !Context.typesAreCompatible(LHSType, RHSType)) {
12160         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12161                                           /*isError*/false);
12162       }
12163       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12164       // the RHS, but we have test coverage for this behavior.
12165       // FIXME: Consider using convertPointersToCompositeType in C++.
12166       if (LHSIsNull && !RHSIsNull) {
12167         Expr *E = LHS.get();
12168         if (getLangOpts().ObjCAutoRefCount)
12169           CheckObjCConversion(SourceRange(), RHSType, E,
12170                               CCK_ImplicitConversion);
12171         LHS = ImpCastExprToType(E, RHSType,
12172                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12173       }
12174       else {
12175         Expr *E = RHS.get();
12176         if (getLangOpts().ObjCAutoRefCount)
12177           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12178                               /*Diagnose=*/true,
12179                               /*DiagnoseCFAudited=*/false, Opc);
12180         RHS = ImpCastExprToType(E, LHSType,
12181                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12182       }
12183       return computeResultTy();
12184     }
12185     if (LHSType->isObjCObjectPointerType() &&
12186         RHSType->isObjCObjectPointerType()) {
12187       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12188         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12189                                           /*isError*/false);
12190       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12191         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12192 
12193       if (LHSIsNull && !RHSIsNull)
12194         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12195       else
12196         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12197       return computeResultTy();
12198     }
12199 
12200     if (!IsOrdered && LHSType->isBlockPointerType() &&
12201         RHSType->isBlockCompatibleObjCPointerType(Context)) {
12202       LHS = ImpCastExprToType(LHS.get(), RHSType,
12203                               CK_BlockPointerToObjCPointerCast);
12204       return computeResultTy();
12205     } else if (!IsOrdered &&
12206                LHSType->isBlockCompatibleObjCPointerType(Context) &&
12207                RHSType->isBlockPointerType()) {
12208       RHS = ImpCastExprToType(RHS.get(), LHSType,
12209                               CK_BlockPointerToObjCPointerCast);
12210       return computeResultTy();
12211     }
12212   }
12213   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12214       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12215     unsigned DiagID = 0;
12216     bool isError = false;
12217     if (LangOpts.DebuggerSupport) {
12218       // Under a debugger, allow the comparison of pointers to integers,
12219       // since users tend to want to compare addresses.
12220     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12221                (RHSIsNull && RHSType->isIntegerType())) {
12222       if (IsOrdered) {
12223         isError = getLangOpts().CPlusPlus;
12224         DiagID =
12225           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12226                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12227       }
12228     } else if (getLangOpts().CPlusPlus) {
12229       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12230       isError = true;
12231     } else if (IsOrdered)
12232       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12233     else
12234       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12235 
12236     if (DiagID) {
12237       Diag(Loc, DiagID)
12238         << LHSType << RHSType << LHS.get()->getSourceRange()
12239         << RHS.get()->getSourceRange();
12240       if (isError)
12241         return QualType();
12242     }
12243 
12244     if (LHSType->isIntegerType())
12245       LHS = ImpCastExprToType(LHS.get(), RHSType,
12246                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12247     else
12248       RHS = ImpCastExprToType(RHS.get(), LHSType,
12249                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12250     return computeResultTy();
12251   }
12252 
12253   // Handle block pointers.
12254   if (!IsOrdered && RHSIsNull
12255       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12256     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12257     return computeResultTy();
12258   }
12259   if (!IsOrdered && LHSIsNull
12260       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12261     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12262     return computeResultTy();
12263   }
12264 
12265   if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12266     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12267       return computeResultTy();
12268     }
12269 
12270     if (LHSType->isQueueT() && RHSType->isQueueT()) {
12271       return computeResultTy();
12272     }
12273 
12274     if (LHSIsNull && RHSType->isQueueT()) {
12275       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12276       return computeResultTy();
12277     }
12278 
12279     if (LHSType->isQueueT() && RHSIsNull) {
12280       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12281       return computeResultTy();
12282     }
12283   }
12284 
12285   return InvalidOperands(Loc, LHS, RHS);
12286 }
12287 
12288 // Return a signed ext_vector_type that is of identical size and number of
12289 // elements. For floating point vectors, return an integer type of identical
12290 // size and number of elements. In the non ext_vector_type case, search from
12291 // the largest type to the smallest type to avoid cases where long long == long,
12292 // where long gets picked over long long.
12293 QualType Sema::GetSignedVectorType(QualType V) {
12294   const VectorType *VTy = V->castAs<VectorType>();
12295   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12296 
12297   if (isa<ExtVectorType>(VTy)) {
12298     if (TypeSize == Context.getTypeSize(Context.CharTy))
12299       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12300     if (TypeSize == Context.getTypeSize(Context.ShortTy))
12301       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12302     if (TypeSize == Context.getTypeSize(Context.IntTy))
12303       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12304     if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12305       return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
12306     if (TypeSize == Context.getTypeSize(Context.LongTy))
12307       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12308     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12309            "Unhandled vector element size in vector compare");
12310     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12311   }
12312 
12313   if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12314     return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
12315                                  VectorType::GenericVector);
12316   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12317     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12318                                  VectorType::GenericVector);
12319   if (TypeSize == Context.getTypeSize(Context.LongTy))
12320     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12321                                  VectorType::GenericVector);
12322   if (TypeSize == Context.getTypeSize(Context.IntTy))
12323     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12324                                  VectorType::GenericVector);
12325   if (TypeSize == Context.getTypeSize(Context.ShortTy))
12326     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12327                                  VectorType::GenericVector);
12328   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12329          "Unhandled vector element size in vector compare");
12330   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12331                                VectorType::GenericVector);
12332 }
12333 
12334 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12335 /// operates on extended vector types.  Instead of producing an IntTy result,
12336 /// like a scalar comparison, a vector comparison produces a vector of integer
12337 /// types.
12338 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12339                                           SourceLocation Loc,
12340                                           BinaryOperatorKind Opc) {
12341   if (Opc == BO_Cmp) {
12342     Diag(Loc, diag::err_three_way_vector_comparison);
12343     return QualType();
12344   }
12345 
12346   // Check to make sure we're operating on vectors of the same type and width,
12347   // Allowing one side to be a scalar of element type.
12348   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
12349                               /*AllowBothBool*/true,
12350                               /*AllowBoolConversions*/getLangOpts().ZVector);
12351   if (vType.isNull())
12352     return vType;
12353 
12354   QualType LHSType = LHS.get()->getType();
12355 
12356   // Determine the return type of a vector compare. By default clang will return
12357   // a scalar for all vector compares except vector bool and vector pixel.
12358   // With the gcc compiler we will always return a vector type and with the xl
12359   // compiler we will always return a scalar type. This switch allows choosing
12360   // which behavior is prefered.
12361   if (getLangOpts().AltiVec) {
12362     switch (getLangOpts().getAltivecSrcCompat()) {
12363     case LangOptions::AltivecSrcCompatKind::Mixed:
12364       // If AltiVec, the comparison results in a numeric type, i.e.
12365       // bool for C++, int for C
12366       if (vType->castAs<VectorType>()->getVectorKind() ==
12367           VectorType::AltiVecVector)
12368         return Context.getLogicalOperationType();
12369       else
12370         Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12371       break;
12372     case LangOptions::AltivecSrcCompatKind::GCC:
12373       // For GCC we always return the vector type.
12374       break;
12375     case LangOptions::AltivecSrcCompatKind::XL:
12376       return Context.getLogicalOperationType();
12377       break;
12378     }
12379   }
12380 
12381   // For non-floating point types, check for self-comparisons of the form
12382   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12383   // often indicate logic errors in the program.
12384   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12385 
12386   // Check for comparisons of floating point operands using != and ==.
12387   if (BinaryOperator::isEqualityOp(Opc) &&
12388       LHSType->hasFloatingRepresentation()) {
12389     assert(RHS.get()->getType()->hasFloatingRepresentation());
12390     CheckFloatComparison(Loc, LHS.get(), RHS.get());
12391   }
12392 
12393   // Return a signed type for the vector.
12394   return GetSignedVectorType(vType);
12395 }
12396 
12397 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12398                                     const ExprResult &XorRHS,
12399                                     const SourceLocation Loc) {
12400   // Do not diagnose macros.
12401   if (Loc.isMacroID())
12402     return;
12403 
12404   // Do not diagnose if both LHS and RHS are macros.
12405   if (XorLHS.get()->getExprLoc().isMacroID() &&
12406       XorRHS.get()->getExprLoc().isMacroID())
12407     return;
12408 
12409   bool Negative = false;
12410   bool ExplicitPlus = false;
12411   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12412   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12413 
12414   if (!LHSInt)
12415     return;
12416   if (!RHSInt) {
12417     // Check negative literals.
12418     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12419       UnaryOperatorKind Opc = UO->getOpcode();
12420       if (Opc != UO_Minus && Opc != UO_Plus)
12421         return;
12422       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12423       if (!RHSInt)
12424         return;
12425       Negative = (Opc == UO_Minus);
12426       ExplicitPlus = !Negative;
12427     } else {
12428       return;
12429     }
12430   }
12431 
12432   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12433   llvm::APInt RightSideValue = RHSInt->getValue();
12434   if (LeftSideValue != 2 && LeftSideValue != 10)
12435     return;
12436 
12437   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12438     return;
12439 
12440   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12441       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12442   llvm::StringRef ExprStr =
12443       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12444 
12445   CharSourceRange XorRange =
12446       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12447   llvm::StringRef XorStr =
12448       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12449   // Do not diagnose if xor keyword/macro is used.
12450   if (XorStr == "xor")
12451     return;
12452 
12453   std::string LHSStr = std::string(Lexer::getSourceText(
12454       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12455       S.getSourceManager(), S.getLangOpts()));
12456   std::string RHSStr = std::string(Lexer::getSourceText(
12457       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12458       S.getSourceManager(), S.getLangOpts()));
12459 
12460   if (Negative) {
12461     RightSideValue = -RightSideValue;
12462     RHSStr = "-" + RHSStr;
12463   } else if (ExplicitPlus) {
12464     RHSStr = "+" + RHSStr;
12465   }
12466 
12467   StringRef LHSStrRef = LHSStr;
12468   StringRef RHSStrRef = RHSStr;
12469   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12470   // literals.
12471   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12472       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12473       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12474       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12475       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12476       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12477       LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12478     return;
12479 
12480   bool SuggestXor =
12481       S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12482   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12483   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12484   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12485     std::string SuggestedExpr = "1 << " + RHSStr;
12486     bool Overflow = false;
12487     llvm::APInt One = (LeftSideValue - 1);
12488     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12489     if (Overflow) {
12490       if (RightSideIntValue < 64)
12491         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12492             << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12493             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12494       else if (RightSideIntValue == 64)
12495         S.Diag(Loc, diag::warn_xor_used_as_pow)
12496             << ExprStr << toString(XorValue, 10, true);
12497       else
12498         return;
12499     } else {
12500       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12501           << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12502           << toString(PowValue, 10, true)
12503           << FixItHint::CreateReplacement(
12504                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12505     }
12506 
12507     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12508         << ("0x2 ^ " + RHSStr) << SuggestXor;
12509   } else if (LeftSideValue == 10) {
12510     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12511     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12512         << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12513         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12514     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12515         << ("0xA ^ " + RHSStr) << SuggestXor;
12516   }
12517 }
12518 
12519 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12520                                           SourceLocation Loc) {
12521   // Ensure that either both operands are of the same vector type, or
12522   // one operand is of a vector type and the other is of its element type.
12523   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12524                                        /*AllowBothBool*/true,
12525                                        /*AllowBoolConversions*/false);
12526   if (vType.isNull())
12527     return InvalidOperands(Loc, LHS, RHS);
12528   if (getLangOpts().OpenCL &&
12529       getLangOpts().getOpenCLCompatibleVersion() < 120 &&
12530       vType->hasFloatingRepresentation())
12531     return InvalidOperands(Loc, LHS, RHS);
12532   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12533   //        usage of the logical operators && and || with vectors in C. This
12534   //        check could be notionally dropped.
12535   if (!getLangOpts().CPlusPlus &&
12536       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12537     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12538 
12539   return GetSignedVectorType(LHS.get()->getType());
12540 }
12541 
12542 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12543                                               SourceLocation Loc,
12544                                               bool IsCompAssign) {
12545   if (!IsCompAssign) {
12546     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12547     if (LHS.isInvalid())
12548       return QualType();
12549   }
12550   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12551   if (RHS.isInvalid())
12552     return QualType();
12553 
12554   // For conversion purposes, we ignore any qualifiers.
12555   // For example, "const float" and "float" are equivalent.
12556   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12557   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12558 
12559   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12560   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12561   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12562 
12563   if (Context.hasSameType(LHSType, RHSType))
12564     return LHSType;
12565 
12566   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12567   // case we have to return InvalidOperands.
12568   ExprResult OriginalLHS = LHS;
12569   ExprResult OriginalRHS = RHS;
12570   if (LHSMatType && !RHSMatType) {
12571     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12572     if (!RHS.isInvalid())
12573       return LHSType;
12574 
12575     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12576   }
12577 
12578   if (!LHSMatType && RHSMatType) {
12579     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12580     if (!LHS.isInvalid())
12581       return RHSType;
12582     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12583   }
12584 
12585   return InvalidOperands(Loc, LHS, RHS);
12586 }
12587 
12588 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12589                                            SourceLocation Loc,
12590                                            bool IsCompAssign) {
12591   if (!IsCompAssign) {
12592     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12593     if (LHS.isInvalid())
12594       return QualType();
12595   }
12596   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12597   if (RHS.isInvalid())
12598     return QualType();
12599 
12600   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12601   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12602   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12603 
12604   if (LHSMatType && RHSMatType) {
12605     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12606       return InvalidOperands(Loc, LHS, RHS);
12607 
12608     if (!Context.hasSameType(LHSMatType->getElementType(),
12609                              RHSMatType->getElementType()))
12610       return InvalidOperands(Loc, LHS, RHS);
12611 
12612     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12613                                          LHSMatType->getNumRows(),
12614                                          RHSMatType->getNumColumns());
12615   }
12616   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12617 }
12618 
12619 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12620                                            SourceLocation Loc,
12621                                            BinaryOperatorKind Opc) {
12622   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12623 
12624   bool IsCompAssign =
12625       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12626 
12627   if (LHS.get()->getType()->isVectorType() ||
12628       RHS.get()->getType()->isVectorType()) {
12629     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12630         RHS.get()->getType()->hasIntegerRepresentation())
12631       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12632                         /*AllowBothBool*/true,
12633                         /*AllowBoolConversions*/getLangOpts().ZVector);
12634     return InvalidOperands(Loc, LHS, RHS);
12635   }
12636 
12637   if (Opc == BO_And)
12638     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12639 
12640   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12641       RHS.get()->getType()->hasFloatingRepresentation())
12642     return InvalidOperands(Loc, LHS, RHS);
12643 
12644   ExprResult LHSResult = LHS, RHSResult = RHS;
12645   QualType compType = UsualArithmeticConversions(
12646       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12647   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12648     return QualType();
12649   LHS = LHSResult.get();
12650   RHS = RHSResult.get();
12651 
12652   if (Opc == BO_Xor)
12653     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12654 
12655   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12656     return compType;
12657   return InvalidOperands(Loc, LHS, RHS);
12658 }
12659 
12660 // C99 6.5.[13,14]
12661 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12662                                            SourceLocation Loc,
12663                                            BinaryOperatorKind Opc) {
12664   // Check vector operands differently.
12665   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12666     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12667 
12668   bool EnumConstantInBoolContext = false;
12669   for (const ExprResult &HS : {LHS, RHS}) {
12670     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12671       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12672       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12673         EnumConstantInBoolContext = true;
12674     }
12675   }
12676 
12677   if (EnumConstantInBoolContext)
12678     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12679 
12680   // Diagnose cases where the user write a logical and/or but probably meant a
12681   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12682   // is a constant.
12683   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12684       !LHS.get()->getType()->isBooleanType() &&
12685       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12686       // Don't warn in macros or template instantiations.
12687       !Loc.isMacroID() && !inTemplateInstantiation()) {
12688     // If the RHS can be constant folded, and if it constant folds to something
12689     // that isn't 0 or 1 (which indicate a potential logical operation that
12690     // happened to fold to true/false) then warn.
12691     // Parens on the RHS are ignored.
12692     Expr::EvalResult EVResult;
12693     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12694       llvm::APSInt Result = EVResult.Val.getInt();
12695       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12696            !RHS.get()->getExprLoc().isMacroID()) ||
12697           (Result != 0 && Result != 1)) {
12698         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12699           << RHS.get()->getSourceRange()
12700           << (Opc == BO_LAnd ? "&&" : "||");
12701         // Suggest replacing the logical operator with the bitwise version
12702         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12703             << (Opc == BO_LAnd ? "&" : "|")
12704             << FixItHint::CreateReplacement(SourceRange(
12705                                                  Loc, getLocForEndOfToken(Loc)),
12706                                             Opc == BO_LAnd ? "&" : "|");
12707         if (Opc == BO_LAnd)
12708           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12709           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12710               << FixItHint::CreateRemoval(
12711                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12712                                  RHS.get()->getEndLoc()));
12713       }
12714     }
12715   }
12716 
12717   if (!Context.getLangOpts().CPlusPlus) {
12718     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12719     // not operate on the built-in scalar and vector float types.
12720     if (Context.getLangOpts().OpenCL &&
12721         Context.getLangOpts().OpenCLVersion < 120) {
12722       if (LHS.get()->getType()->isFloatingType() ||
12723           RHS.get()->getType()->isFloatingType())
12724         return InvalidOperands(Loc, LHS, RHS);
12725     }
12726 
12727     LHS = UsualUnaryConversions(LHS.get());
12728     if (LHS.isInvalid())
12729       return QualType();
12730 
12731     RHS = UsualUnaryConversions(RHS.get());
12732     if (RHS.isInvalid())
12733       return QualType();
12734 
12735     if (!LHS.get()->getType()->isScalarType() ||
12736         !RHS.get()->getType()->isScalarType())
12737       return InvalidOperands(Loc, LHS, RHS);
12738 
12739     return Context.IntTy;
12740   }
12741 
12742   // The following is safe because we only use this method for
12743   // non-overloadable operands.
12744 
12745   // C++ [expr.log.and]p1
12746   // C++ [expr.log.or]p1
12747   // The operands are both contextually converted to type bool.
12748   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12749   if (LHSRes.isInvalid())
12750     return InvalidOperands(Loc, LHS, RHS);
12751   LHS = LHSRes;
12752 
12753   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12754   if (RHSRes.isInvalid())
12755     return InvalidOperands(Loc, LHS, RHS);
12756   RHS = RHSRes;
12757 
12758   // C++ [expr.log.and]p2
12759   // C++ [expr.log.or]p2
12760   // The result is a bool.
12761   return Context.BoolTy;
12762 }
12763 
12764 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12765   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12766   if (!ME) return false;
12767   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12768   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12769       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12770   if (!Base) return false;
12771   return Base->getMethodDecl() != nullptr;
12772 }
12773 
12774 /// Is the given expression (which must be 'const') a reference to a
12775 /// variable which was originally non-const, but which has become
12776 /// 'const' due to being captured within a block?
12777 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12778 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12779   assert(E->isLValue() && E->getType().isConstQualified());
12780   E = E->IgnoreParens();
12781 
12782   // Must be a reference to a declaration from an enclosing scope.
12783   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12784   if (!DRE) return NCCK_None;
12785   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12786 
12787   // The declaration must be a variable which is not declared 'const'.
12788   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12789   if (!var) return NCCK_None;
12790   if (var->getType().isConstQualified()) return NCCK_None;
12791   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12792 
12793   // Decide whether the first capture was for a block or a lambda.
12794   DeclContext *DC = S.CurContext, *Prev = nullptr;
12795   // Decide whether the first capture was for a block or a lambda.
12796   while (DC) {
12797     // For init-capture, it is possible that the variable belongs to the
12798     // template pattern of the current context.
12799     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12800       if (var->isInitCapture() &&
12801           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12802         break;
12803     if (DC == var->getDeclContext())
12804       break;
12805     Prev = DC;
12806     DC = DC->getParent();
12807   }
12808   // Unless we have an init-capture, we've gone one step too far.
12809   if (!var->isInitCapture())
12810     DC = Prev;
12811   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12812 }
12813 
12814 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12815   Ty = Ty.getNonReferenceType();
12816   if (IsDereference && Ty->isPointerType())
12817     Ty = Ty->getPointeeType();
12818   return !Ty.isConstQualified();
12819 }
12820 
12821 // Update err_typecheck_assign_const and note_typecheck_assign_const
12822 // when this enum is changed.
12823 enum {
12824   ConstFunction,
12825   ConstVariable,
12826   ConstMember,
12827   ConstMethod,
12828   NestedConstMember,
12829   ConstUnknown,  // Keep as last element
12830 };
12831 
12832 /// Emit the "read-only variable not assignable" error and print notes to give
12833 /// more information about why the variable is not assignable, such as pointing
12834 /// to the declaration of a const variable, showing that a method is const, or
12835 /// that the function is returning a const reference.
12836 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12837                                     SourceLocation Loc) {
12838   SourceRange ExprRange = E->getSourceRange();
12839 
12840   // Only emit one error on the first const found.  All other consts will emit
12841   // a note to the error.
12842   bool DiagnosticEmitted = false;
12843 
12844   // Track if the current expression is the result of a dereference, and if the
12845   // next checked expression is the result of a dereference.
12846   bool IsDereference = false;
12847   bool NextIsDereference = false;
12848 
12849   // Loop to process MemberExpr chains.
12850   while (true) {
12851     IsDereference = NextIsDereference;
12852 
12853     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12854     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12855       NextIsDereference = ME->isArrow();
12856       const ValueDecl *VD = ME->getMemberDecl();
12857       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12858         // Mutable fields can be modified even if the class is const.
12859         if (Field->isMutable()) {
12860           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12861           break;
12862         }
12863 
12864         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12865           if (!DiagnosticEmitted) {
12866             S.Diag(Loc, diag::err_typecheck_assign_const)
12867                 << ExprRange << ConstMember << false /*static*/ << Field
12868                 << Field->getType();
12869             DiagnosticEmitted = true;
12870           }
12871           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12872               << ConstMember << false /*static*/ << Field << Field->getType()
12873               << Field->getSourceRange();
12874         }
12875         E = ME->getBase();
12876         continue;
12877       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12878         if (VDecl->getType().isConstQualified()) {
12879           if (!DiagnosticEmitted) {
12880             S.Diag(Loc, diag::err_typecheck_assign_const)
12881                 << ExprRange << ConstMember << true /*static*/ << VDecl
12882                 << VDecl->getType();
12883             DiagnosticEmitted = true;
12884           }
12885           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12886               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12887               << VDecl->getSourceRange();
12888         }
12889         // Static fields do not inherit constness from parents.
12890         break;
12891       }
12892       break; // End MemberExpr
12893     } else if (const ArraySubscriptExpr *ASE =
12894                    dyn_cast<ArraySubscriptExpr>(E)) {
12895       E = ASE->getBase()->IgnoreParenImpCasts();
12896       continue;
12897     } else if (const ExtVectorElementExpr *EVE =
12898                    dyn_cast<ExtVectorElementExpr>(E)) {
12899       E = EVE->getBase()->IgnoreParenImpCasts();
12900       continue;
12901     }
12902     break;
12903   }
12904 
12905   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12906     // Function calls
12907     const FunctionDecl *FD = CE->getDirectCallee();
12908     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12909       if (!DiagnosticEmitted) {
12910         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12911                                                       << ConstFunction << FD;
12912         DiagnosticEmitted = true;
12913       }
12914       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12915              diag::note_typecheck_assign_const)
12916           << ConstFunction << FD << FD->getReturnType()
12917           << FD->getReturnTypeSourceRange();
12918     }
12919   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12920     // Point to variable declaration.
12921     if (const ValueDecl *VD = DRE->getDecl()) {
12922       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12923         if (!DiagnosticEmitted) {
12924           S.Diag(Loc, diag::err_typecheck_assign_const)
12925               << ExprRange << ConstVariable << VD << VD->getType();
12926           DiagnosticEmitted = true;
12927         }
12928         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12929             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12930       }
12931     }
12932   } else if (isa<CXXThisExpr>(E)) {
12933     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12934       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12935         if (MD->isConst()) {
12936           if (!DiagnosticEmitted) {
12937             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12938                                                           << ConstMethod << MD;
12939             DiagnosticEmitted = true;
12940           }
12941           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12942               << ConstMethod << MD << MD->getSourceRange();
12943         }
12944       }
12945     }
12946   }
12947 
12948   if (DiagnosticEmitted)
12949     return;
12950 
12951   // Can't determine a more specific message, so display the generic error.
12952   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12953 }
12954 
12955 enum OriginalExprKind {
12956   OEK_Variable,
12957   OEK_Member,
12958   OEK_LValue
12959 };
12960 
12961 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12962                                          const RecordType *Ty,
12963                                          SourceLocation Loc, SourceRange Range,
12964                                          OriginalExprKind OEK,
12965                                          bool &DiagnosticEmitted) {
12966   std::vector<const RecordType *> RecordTypeList;
12967   RecordTypeList.push_back(Ty);
12968   unsigned NextToCheckIndex = 0;
12969   // We walk the record hierarchy breadth-first to ensure that we print
12970   // diagnostics in field nesting order.
12971   while (RecordTypeList.size() > NextToCheckIndex) {
12972     bool IsNested = NextToCheckIndex > 0;
12973     for (const FieldDecl *Field :
12974          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12975       // First, check every field for constness.
12976       QualType FieldTy = Field->getType();
12977       if (FieldTy.isConstQualified()) {
12978         if (!DiagnosticEmitted) {
12979           S.Diag(Loc, diag::err_typecheck_assign_const)
12980               << Range << NestedConstMember << OEK << VD
12981               << IsNested << Field;
12982           DiagnosticEmitted = true;
12983         }
12984         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12985             << NestedConstMember << IsNested << Field
12986             << FieldTy << Field->getSourceRange();
12987       }
12988 
12989       // Then we append it to the list to check next in order.
12990       FieldTy = FieldTy.getCanonicalType();
12991       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12992         if (!llvm::is_contained(RecordTypeList, FieldRecTy))
12993           RecordTypeList.push_back(FieldRecTy);
12994       }
12995     }
12996     ++NextToCheckIndex;
12997   }
12998 }
12999 
13000 /// Emit an error for the case where a record we are trying to assign to has a
13001 /// const-qualified field somewhere in its hierarchy.
13002 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13003                                          SourceLocation Loc) {
13004   QualType Ty = E->getType();
13005   assert(Ty->isRecordType() && "lvalue was not record?");
13006   SourceRange Range = E->getSourceRange();
13007   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13008   bool DiagEmitted = false;
13009 
13010   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13011     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13012             Range, OEK_Member, DiagEmitted);
13013   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13014     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13015             Range, OEK_Variable, DiagEmitted);
13016   else
13017     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13018             Range, OEK_LValue, DiagEmitted);
13019   if (!DiagEmitted)
13020     DiagnoseConstAssignment(S, E, Loc);
13021 }
13022 
13023 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
13024 /// emit an error and return true.  If so, return false.
13025 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
13026   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13027 
13028   S.CheckShadowingDeclModification(E, Loc);
13029 
13030   SourceLocation OrigLoc = Loc;
13031   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
13032                                                               &Loc);
13033   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13034     IsLV = Expr::MLV_InvalidMessageExpression;
13035   if (IsLV == Expr::MLV_Valid)
13036     return false;
13037 
13038   unsigned DiagID = 0;
13039   bool NeedType = false;
13040   switch (IsLV) { // C99 6.5.16p2
13041   case Expr::MLV_ConstQualified:
13042     // Use a specialized diagnostic when we're assigning to an object
13043     // from an enclosing function or block.
13044     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
13045       if (NCCK == NCCK_Block)
13046         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13047       else
13048         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13049       break;
13050     }
13051 
13052     // In ARC, use some specialized diagnostics for occasions where we
13053     // infer 'const'.  These are always pseudo-strong variables.
13054     if (S.getLangOpts().ObjCAutoRefCount) {
13055       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13056       if (declRef && isa<VarDecl>(declRef->getDecl())) {
13057         VarDecl *var = cast<VarDecl>(declRef->getDecl());
13058 
13059         // Use the normal diagnostic if it's pseudo-__strong but the
13060         // user actually wrote 'const'.
13061         if (var->isARCPseudoStrong() &&
13062             (!var->getTypeSourceInfo() ||
13063              !var->getTypeSourceInfo()->getType().isConstQualified())) {
13064           // There are three pseudo-strong cases:
13065           //  - self
13066           ObjCMethodDecl *method = S.getCurMethodDecl();
13067           if (method && var == method->getSelfDecl()) {
13068             DiagID = method->isClassMethod()
13069               ? diag::err_typecheck_arc_assign_self_class_method
13070               : diag::err_typecheck_arc_assign_self;
13071 
13072           //  - Objective-C externally_retained attribute.
13073           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13074                      isa<ParmVarDecl>(var)) {
13075             DiagID = diag::err_typecheck_arc_assign_externally_retained;
13076 
13077           //  - fast enumeration variables
13078           } else {
13079             DiagID = diag::err_typecheck_arr_assign_enumeration;
13080           }
13081 
13082           SourceRange Assign;
13083           if (Loc != OrigLoc)
13084             Assign = SourceRange(OrigLoc, OrigLoc);
13085           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13086           // We need to preserve the AST regardless, so migration tool
13087           // can do its job.
13088           return false;
13089         }
13090       }
13091     }
13092 
13093     // If none of the special cases above are triggered, then this is a
13094     // simple const assignment.
13095     if (DiagID == 0) {
13096       DiagnoseConstAssignment(S, E, Loc);
13097       return true;
13098     }
13099 
13100     break;
13101   case Expr::MLV_ConstAddrSpace:
13102     DiagnoseConstAssignment(S, E, Loc);
13103     return true;
13104   case Expr::MLV_ConstQualifiedField:
13105     DiagnoseRecursiveConstFields(S, E, Loc);
13106     return true;
13107   case Expr::MLV_ArrayType:
13108   case Expr::MLV_ArrayTemporary:
13109     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13110     NeedType = true;
13111     break;
13112   case Expr::MLV_NotObjectType:
13113     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13114     NeedType = true;
13115     break;
13116   case Expr::MLV_LValueCast:
13117     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13118     break;
13119   case Expr::MLV_Valid:
13120     llvm_unreachable("did not take early return for MLV_Valid");
13121   case Expr::MLV_InvalidExpression:
13122   case Expr::MLV_MemberFunction:
13123   case Expr::MLV_ClassTemporary:
13124     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13125     break;
13126   case Expr::MLV_IncompleteType:
13127   case Expr::MLV_IncompleteVoidType:
13128     return S.RequireCompleteType(Loc, E->getType(),
13129              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13130   case Expr::MLV_DuplicateVectorComponents:
13131     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13132     break;
13133   case Expr::MLV_NoSetterProperty:
13134     llvm_unreachable("readonly properties should be processed differently");
13135   case Expr::MLV_InvalidMessageExpression:
13136     DiagID = diag::err_readonly_message_assignment;
13137     break;
13138   case Expr::MLV_SubObjCPropertySetting:
13139     DiagID = diag::err_no_subobject_property_setting;
13140     break;
13141   }
13142 
13143   SourceRange Assign;
13144   if (Loc != OrigLoc)
13145     Assign = SourceRange(OrigLoc, OrigLoc);
13146   if (NeedType)
13147     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13148   else
13149     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13150   return true;
13151 }
13152 
13153 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13154                                          SourceLocation Loc,
13155                                          Sema &Sema) {
13156   if (Sema.inTemplateInstantiation())
13157     return;
13158   if (Sema.isUnevaluatedContext())
13159     return;
13160   if (Loc.isInvalid() || Loc.isMacroID())
13161     return;
13162   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13163     return;
13164 
13165   // C / C++ fields
13166   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13167   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13168   if (ML && MR) {
13169     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13170       return;
13171     const ValueDecl *LHSDecl =
13172         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13173     const ValueDecl *RHSDecl =
13174         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13175     if (LHSDecl != RHSDecl)
13176       return;
13177     if (LHSDecl->getType().isVolatileQualified())
13178       return;
13179     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13180       if (RefTy->getPointeeType().isVolatileQualified())
13181         return;
13182 
13183     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13184   }
13185 
13186   // Objective-C instance variables
13187   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13188   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13189   if (OL && OR && OL->getDecl() == OR->getDecl()) {
13190     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13191     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13192     if (RL && RR && RL->getDecl() == RR->getDecl())
13193       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13194   }
13195 }
13196 
13197 // C99 6.5.16.1
13198 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13199                                        SourceLocation Loc,
13200                                        QualType CompoundType) {
13201   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13202 
13203   // Verify that LHS is a modifiable lvalue, and emit error if not.
13204   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13205     return QualType();
13206 
13207   QualType LHSType = LHSExpr->getType();
13208   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13209                                              CompoundType;
13210   // OpenCL v1.2 s6.1.1.1 p2:
13211   // The half data type can only be used to declare a pointer to a buffer that
13212   // contains half values
13213   if (getLangOpts().OpenCL &&
13214       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13215       LHSType->isHalfType()) {
13216     Diag(Loc, diag::err_opencl_half_load_store) << 1
13217         << LHSType.getUnqualifiedType();
13218     return QualType();
13219   }
13220 
13221   AssignConvertType ConvTy;
13222   if (CompoundType.isNull()) {
13223     Expr *RHSCheck = RHS.get();
13224 
13225     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13226 
13227     QualType LHSTy(LHSType);
13228     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13229     if (RHS.isInvalid())
13230       return QualType();
13231     // Special case of NSObject attributes on c-style pointer types.
13232     if (ConvTy == IncompatiblePointer &&
13233         ((Context.isObjCNSObjectType(LHSType) &&
13234           RHSType->isObjCObjectPointerType()) ||
13235          (Context.isObjCNSObjectType(RHSType) &&
13236           LHSType->isObjCObjectPointerType())))
13237       ConvTy = Compatible;
13238 
13239     if (ConvTy == Compatible &&
13240         LHSType->isObjCObjectType())
13241         Diag(Loc, diag::err_objc_object_assignment)
13242           << LHSType;
13243 
13244     // If the RHS is a unary plus or minus, check to see if they = and + are
13245     // right next to each other.  If so, the user may have typo'd "x =+ 4"
13246     // instead of "x += 4".
13247     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13248       RHSCheck = ICE->getSubExpr();
13249     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13250       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13251           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13252           // Only if the two operators are exactly adjacent.
13253           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13254           // And there is a space or other character before the subexpr of the
13255           // unary +/-.  We don't want to warn on "x=-1".
13256           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13257           UO->getSubExpr()->getBeginLoc().isFileID()) {
13258         Diag(Loc, diag::warn_not_compound_assign)
13259           << (UO->getOpcode() == UO_Plus ? "+" : "-")
13260           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13261       }
13262     }
13263 
13264     if (ConvTy == Compatible) {
13265       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13266         // Warn about retain cycles where a block captures the LHS, but
13267         // not if the LHS is a simple variable into which the block is
13268         // being stored...unless that variable can be captured by reference!
13269         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13270         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13271         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13272           checkRetainCycles(LHSExpr, RHS.get());
13273       }
13274 
13275       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13276           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13277         // It is safe to assign a weak reference into a strong variable.
13278         // Although this code can still have problems:
13279         //   id x = self.weakProp;
13280         //   id y = self.weakProp;
13281         // we do not warn to warn spuriously when 'x' and 'y' are on separate
13282         // paths through the function. This should be revisited if
13283         // -Wrepeated-use-of-weak is made flow-sensitive.
13284         // For ObjCWeak only, we do not warn if the assign is to a non-weak
13285         // variable, which will be valid for the current autorelease scope.
13286         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13287                              RHS.get()->getBeginLoc()))
13288           getCurFunction()->markSafeWeakUse(RHS.get());
13289 
13290       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13291         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13292       }
13293     }
13294   } else {
13295     // Compound assignment "x += y"
13296     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13297   }
13298 
13299   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13300                                RHS.get(), AA_Assigning))
13301     return QualType();
13302 
13303   CheckForNullPointerDereference(*this, LHSExpr);
13304 
13305   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13306     if (CompoundType.isNull()) {
13307       // C++2a [expr.ass]p5:
13308       //   A simple-assignment whose left operand is of a volatile-qualified
13309       //   type is deprecated unless the assignment is either a discarded-value
13310       //   expression or an unevaluated operand
13311       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13312     } else {
13313       // C++2a [expr.ass]p6:
13314       //   [Compound-assignment] expressions are deprecated if E1 has
13315       //   volatile-qualified type
13316       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13317     }
13318   }
13319 
13320   // C99 6.5.16p3: The type of an assignment expression is the type of the
13321   // left operand unless the left operand has qualified type, in which case
13322   // it is the unqualified version of the type of the left operand.
13323   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
13324   // is converted to the type of the assignment expression (above).
13325   // C++ 5.17p1: the type of the assignment expression is that of its left
13326   // operand.
13327   return (getLangOpts().CPlusPlus
13328           ? LHSType : LHSType.getUnqualifiedType());
13329 }
13330 
13331 // Only ignore explicit casts to void.
13332 static bool IgnoreCommaOperand(const Expr *E) {
13333   E = E->IgnoreParens();
13334 
13335   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13336     if (CE->getCastKind() == CK_ToVoid) {
13337       return true;
13338     }
13339 
13340     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13341     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13342         CE->getSubExpr()->getType()->isDependentType()) {
13343       return true;
13344     }
13345   }
13346 
13347   return false;
13348 }
13349 
13350 // Look for instances where it is likely the comma operator is confused with
13351 // another operator.  There is an explicit list of acceptable expressions for
13352 // the left hand side of the comma operator, otherwise emit a warning.
13353 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13354   // No warnings in macros
13355   if (Loc.isMacroID())
13356     return;
13357 
13358   // Don't warn in template instantiations.
13359   if (inTemplateInstantiation())
13360     return;
13361 
13362   // Scope isn't fine-grained enough to explicitly list the specific cases, so
13363   // instead, skip more than needed, then call back into here with the
13364   // CommaVisitor in SemaStmt.cpp.
13365   // The listed locations are the initialization and increment portions
13366   // of a for loop.  The additional checks are on the condition of
13367   // if statements, do/while loops, and for loops.
13368   // Differences in scope flags for C89 mode requires the extra logic.
13369   const unsigned ForIncrementFlags =
13370       getLangOpts().C99 || getLangOpts().CPlusPlus
13371           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13372           : Scope::ContinueScope | Scope::BreakScope;
13373   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13374   const unsigned ScopeFlags = getCurScope()->getFlags();
13375   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13376       (ScopeFlags & ForInitFlags) == ForInitFlags)
13377     return;
13378 
13379   // If there are multiple comma operators used together, get the RHS of the
13380   // of the comma operator as the LHS.
13381   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13382     if (BO->getOpcode() != BO_Comma)
13383       break;
13384     LHS = BO->getRHS();
13385   }
13386 
13387   // Only allow some expressions on LHS to not warn.
13388   if (IgnoreCommaOperand(LHS))
13389     return;
13390 
13391   Diag(Loc, diag::warn_comma_operator);
13392   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13393       << LHS->getSourceRange()
13394       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13395                                     LangOpts.CPlusPlus ? "static_cast<void>("
13396                                                        : "(void)(")
13397       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13398                                     ")");
13399 }
13400 
13401 // C99 6.5.17
13402 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13403                                    SourceLocation Loc) {
13404   LHS = S.CheckPlaceholderExpr(LHS.get());
13405   RHS = S.CheckPlaceholderExpr(RHS.get());
13406   if (LHS.isInvalid() || RHS.isInvalid())
13407     return QualType();
13408 
13409   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13410   // operands, but not unary promotions.
13411   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13412 
13413   // So we treat the LHS as a ignored value, and in C++ we allow the
13414   // containing site to determine what should be done with the RHS.
13415   LHS = S.IgnoredValueConversions(LHS.get());
13416   if (LHS.isInvalid())
13417     return QualType();
13418 
13419   S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13420 
13421   if (!S.getLangOpts().CPlusPlus) {
13422     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13423     if (RHS.isInvalid())
13424       return QualType();
13425     if (!RHS.get()->getType()->isVoidType())
13426       S.RequireCompleteType(Loc, RHS.get()->getType(),
13427                             diag::err_incomplete_type);
13428   }
13429 
13430   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13431     S.DiagnoseCommaOperator(LHS.get(), Loc);
13432 
13433   return RHS.get()->getType();
13434 }
13435 
13436 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13437 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13438 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13439                                                ExprValueKind &VK,
13440                                                ExprObjectKind &OK,
13441                                                SourceLocation OpLoc,
13442                                                bool IsInc, bool IsPrefix) {
13443   if (Op->isTypeDependent())
13444     return S.Context.DependentTy;
13445 
13446   QualType ResType = Op->getType();
13447   // Atomic types can be used for increment / decrement where the non-atomic
13448   // versions can, so ignore the _Atomic() specifier for the purpose of
13449   // checking.
13450   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13451     ResType = ResAtomicType->getValueType();
13452 
13453   assert(!ResType.isNull() && "no type for increment/decrement expression");
13454 
13455   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13456     // Decrement of bool is not allowed.
13457     if (!IsInc) {
13458       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13459       return QualType();
13460     }
13461     // Increment of bool sets it to true, but is deprecated.
13462     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13463                                               : diag::warn_increment_bool)
13464       << Op->getSourceRange();
13465   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13466     // Error on enum increments and decrements in C++ mode
13467     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13468     return QualType();
13469   } else if (ResType->isRealType()) {
13470     // OK!
13471   } else if (ResType->isPointerType()) {
13472     // C99 6.5.2.4p2, 6.5.6p2
13473     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13474       return QualType();
13475   } else if (ResType->isObjCObjectPointerType()) {
13476     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13477     // Otherwise, we just need a complete type.
13478     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13479         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13480       return QualType();
13481   } else if (ResType->isAnyComplexType()) {
13482     // C99 does not support ++/-- on complex types, we allow as an extension.
13483     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13484       << ResType << Op->getSourceRange();
13485   } else if (ResType->isPlaceholderType()) {
13486     ExprResult PR = S.CheckPlaceholderExpr(Op);
13487     if (PR.isInvalid()) return QualType();
13488     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13489                                           IsInc, IsPrefix);
13490   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13491     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13492   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13493              (ResType->castAs<VectorType>()->getVectorKind() !=
13494               VectorType::AltiVecBool)) {
13495     // The z vector extensions allow ++ and -- for non-bool vectors.
13496   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13497             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13498     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13499   } else {
13500     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13501       << ResType << int(IsInc) << Op->getSourceRange();
13502     return QualType();
13503   }
13504   // At this point, we know we have a real, complex or pointer type.
13505   // Now make sure the operand is a modifiable lvalue.
13506   if (CheckForModifiableLvalue(Op, OpLoc, S))
13507     return QualType();
13508   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13509     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13510     //   An operand with volatile-qualified type is deprecated
13511     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13512         << IsInc << ResType;
13513   }
13514   // In C++, a prefix increment is the same type as the operand. Otherwise
13515   // (in C or with postfix), the increment is the unqualified type of the
13516   // operand.
13517   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13518     VK = VK_LValue;
13519     OK = Op->getObjectKind();
13520     return ResType;
13521   } else {
13522     VK = VK_PRValue;
13523     return ResType.getUnqualifiedType();
13524   }
13525 }
13526 
13527 
13528 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13529 /// This routine allows us to typecheck complex/recursive expressions
13530 /// where the declaration is needed for type checking. We only need to
13531 /// handle cases when the expression references a function designator
13532 /// or is an lvalue. Here are some examples:
13533 ///  - &(x) => x
13534 ///  - &*****f => f for f a function designator.
13535 ///  - &s.xx => s
13536 ///  - &s.zz[1].yy -> s, if zz is an array
13537 ///  - *(x + 1) -> x, if x is an array
13538 ///  - &"123"[2] -> 0
13539 ///  - & __real__ x -> x
13540 ///
13541 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13542 /// members.
13543 static ValueDecl *getPrimaryDecl(Expr *E) {
13544   switch (E->getStmtClass()) {
13545   case Stmt::DeclRefExprClass:
13546     return cast<DeclRefExpr>(E)->getDecl();
13547   case Stmt::MemberExprClass:
13548     // If this is an arrow operator, the address is an offset from
13549     // the base's value, so the object the base refers to is
13550     // irrelevant.
13551     if (cast<MemberExpr>(E)->isArrow())
13552       return nullptr;
13553     // Otherwise, the expression refers to a part of the base
13554     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13555   case Stmt::ArraySubscriptExprClass: {
13556     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13557     // promotion of register arrays earlier.
13558     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13559     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13560       if (ICE->getSubExpr()->getType()->isArrayType())
13561         return getPrimaryDecl(ICE->getSubExpr());
13562     }
13563     return nullptr;
13564   }
13565   case Stmt::UnaryOperatorClass: {
13566     UnaryOperator *UO = cast<UnaryOperator>(E);
13567 
13568     switch(UO->getOpcode()) {
13569     case UO_Real:
13570     case UO_Imag:
13571     case UO_Extension:
13572       return getPrimaryDecl(UO->getSubExpr());
13573     default:
13574       return nullptr;
13575     }
13576   }
13577   case Stmt::ParenExprClass:
13578     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13579   case Stmt::ImplicitCastExprClass:
13580     // If the result of an implicit cast is an l-value, we care about
13581     // the sub-expression; otherwise, the result here doesn't matter.
13582     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13583   case Stmt::CXXUuidofExprClass:
13584     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13585   default:
13586     return nullptr;
13587   }
13588 }
13589 
13590 namespace {
13591 enum {
13592   AO_Bit_Field = 0,
13593   AO_Vector_Element = 1,
13594   AO_Property_Expansion = 2,
13595   AO_Register_Variable = 3,
13596   AO_Matrix_Element = 4,
13597   AO_No_Error = 5
13598 };
13599 }
13600 /// Diagnose invalid operand for address of operations.
13601 ///
13602 /// \param Type The type of operand which cannot have its address taken.
13603 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13604                                          Expr *E, unsigned Type) {
13605   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13606 }
13607 
13608 /// CheckAddressOfOperand - The operand of & must be either a function
13609 /// designator or an lvalue designating an object. If it is an lvalue, the
13610 /// object cannot be declared with storage class register or be a bit field.
13611 /// Note: The usual conversions are *not* applied to the operand of the &
13612 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13613 /// In C++, the operand might be an overloaded function name, in which case
13614 /// we allow the '&' but retain the overloaded-function type.
13615 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13616   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13617     if (PTy->getKind() == BuiltinType::Overload) {
13618       Expr *E = OrigOp.get()->IgnoreParens();
13619       if (!isa<OverloadExpr>(E)) {
13620         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13621         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13622           << OrigOp.get()->getSourceRange();
13623         return QualType();
13624       }
13625 
13626       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13627       if (isa<UnresolvedMemberExpr>(Ovl))
13628         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13629           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13630             << OrigOp.get()->getSourceRange();
13631           return QualType();
13632         }
13633 
13634       return Context.OverloadTy;
13635     }
13636 
13637     if (PTy->getKind() == BuiltinType::UnknownAny)
13638       return Context.UnknownAnyTy;
13639 
13640     if (PTy->getKind() == BuiltinType::BoundMember) {
13641       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13642         << OrigOp.get()->getSourceRange();
13643       return QualType();
13644     }
13645 
13646     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13647     if (OrigOp.isInvalid()) return QualType();
13648   }
13649 
13650   if (OrigOp.get()->isTypeDependent())
13651     return Context.DependentTy;
13652 
13653   assert(!OrigOp.get()->hasPlaceholderType());
13654 
13655   // Make sure to ignore parentheses in subsequent checks
13656   Expr *op = OrigOp.get()->IgnoreParens();
13657 
13658   // In OpenCL captures for blocks called as lambda functions
13659   // are located in the private address space. Blocks used in
13660   // enqueue_kernel can be located in a different address space
13661   // depending on a vendor implementation. Thus preventing
13662   // taking an address of the capture to avoid invalid AS casts.
13663   if (LangOpts.OpenCL) {
13664     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13665     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13666       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13667       return QualType();
13668     }
13669   }
13670 
13671   if (getLangOpts().C99) {
13672     // Implement C99-only parts of addressof rules.
13673     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13674       if (uOp->getOpcode() == UO_Deref)
13675         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13676         // (assuming the deref expression is valid).
13677         return uOp->getSubExpr()->getType();
13678     }
13679     // Technically, there should be a check for array subscript
13680     // expressions here, but the result of one is always an lvalue anyway.
13681   }
13682   ValueDecl *dcl = getPrimaryDecl(op);
13683 
13684   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13685     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13686                                            op->getBeginLoc()))
13687       return QualType();
13688 
13689   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13690   unsigned AddressOfError = AO_No_Error;
13691 
13692   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13693     bool sfinae = (bool)isSFINAEContext();
13694     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13695                                   : diag::ext_typecheck_addrof_temporary)
13696       << op->getType() << op->getSourceRange();
13697     if (sfinae)
13698       return QualType();
13699     // Materialize the temporary as an lvalue so that we can take its address.
13700     OrigOp = op =
13701         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13702   } else if (isa<ObjCSelectorExpr>(op)) {
13703     return Context.getPointerType(op->getType());
13704   } else if (lval == Expr::LV_MemberFunction) {
13705     // If it's an instance method, make a member pointer.
13706     // The expression must have exactly the form &A::foo.
13707 
13708     // If the underlying expression isn't a decl ref, give up.
13709     if (!isa<DeclRefExpr>(op)) {
13710       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13711         << OrigOp.get()->getSourceRange();
13712       return QualType();
13713     }
13714     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13715     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13716 
13717     // The id-expression was parenthesized.
13718     if (OrigOp.get() != DRE) {
13719       Diag(OpLoc, diag::err_parens_pointer_member_function)
13720         << OrigOp.get()->getSourceRange();
13721 
13722     // The method was named without a qualifier.
13723     } else if (!DRE->getQualifier()) {
13724       if (MD->getParent()->getName().empty())
13725         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13726           << op->getSourceRange();
13727       else {
13728         SmallString<32> Str;
13729         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13730         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13731           << op->getSourceRange()
13732           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13733       }
13734     }
13735 
13736     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13737     if (isa<CXXDestructorDecl>(MD))
13738       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13739 
13740     QualType MPTy = Context.getMemberPointerType(
13741         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13742     // Under the MS ABI, lock down the inheritance model now.
13743     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13744       (void)isCompleteType(OpLoc, MPTy);
13745     return MPTy;
13746   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13747     // C99 6.5.3.2p1
13748     // The operand must be either an l-value or a function designator
13749     if (!op->getType()->isFunctionType()) {
13750       // Use a special diagnostic for loads from property references.
13751       if (isa<PseudoObjectExpr>(op)) {
13752         AddressOfError = AO_Property_Expansion;
13753       } else {
13754         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13755           << op->getType() << op->getSourceRange();
13756         return QualType();
13757       }
13758     }
13759   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13760     // The operand cannot be a bit-field
13761     AddressOfError = AO_Bit_Field;
13762   } else if (op->getObjectKind() == OK_VectorComponent) {
13763     // The operand cannot be an element of a vector
13764     AddressOfError = AO_Vector_Element;
13765   } else if (op->getObjectKind() == OK_MatrixComponent) {
13766     // The operand cannot be an element of a matrix.
13767     AddressOfError = AO_Matrix_Element;
13768   } else if (dcl) { // C99 6.5.3.2p1
13769     // We have an lvalue with a decl. Make sure the decl is not declared
13770     // with the register storage-class specifier.
13771     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13772       // in C++ it is not error to take address of a register
13773       // variable (c++03 7.1.1P3)
13774       if (vd->getStorageClass() == SC_Register &&
13775           !getLangOpts().CPlusPlus) {
13776         AddressOfError = AO_Register_Variable;
13777       }
13778     } else if (isa<MSPropertyDecl>(dcl)) {
13779       AddressOfError = AO_Property_Expansion;
13780     } else if (isa<FunctionTemplateDecl>(dcl)) {
13781       return Context.OverloadTy;
13782     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13783       // Okay: we can take the address of a field.
13784       // Could be a pointer to member, though, if there is an explicit
13785       // scope qualifier for the class.
13786       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13787         DeclContext *Ctx = dcl->getDeclContext();
13788         if (Ctx && Ctx->isRecord()) {
13789           if (dcl->getType()->isReferenceType()) {
13790             Diag(OpLoc,
13791                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13792               << dcl->getDeclName() << dcl->getType();
13793             return QualType();
13794           }
13795 
13796           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13797             Ctx = Ctx->getParent();
13798 
13799           QualType MPTy = Context.getMemberPointerType(
13800               op->getType(),
13801               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13802           // Under the MS ABI, lock down the inheritance model now.
13803           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13804             (void)isCompleteType(OpLoc, MPTy);
13805           return MPTy;
13806         }
13807       }
13808     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13809                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13810       llvm_unreachable("Unknown/unexpected decl type");
13811   }
13812 
13813   if (AddressOfError != AO_No_Error) {
13814     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13815     return QualType();
13816   }
13817 
13818   if (lval == Expr::LV_IncompleteVoidType) {
13819     // Taking the address of a void variable is technically illegal, but we
13820     // allow it in cases which are otherwise valid.
13821     // Example: "extern void x; void* y = &x;".
13822     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13823   }
13824 
13825   // If the operand has type "type", the result has type "pointer to type".
13826   if (op->getType()->isObjCObjectType())
13827     return Context.getObjCObjectPointerType(op->getType());
13828 
13829   CheckAddressOfPackedMember(op);
13830 
13831   return Context.getPointerType(op->getType());
13832 }
13833 
13834 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13835   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13836   if (!DRE)
13837     return;
13838   const Decl *D = DRE->getDecl();
13839   if (!D)
13840     return;
13841   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13842   if (!Param)
13843     return;
13844   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13845     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13846       return;
13847   if (FunctionScopeInfo *FD = S.getCurFunction())
13848     if (!FD->ModifiedNonNullParams.count(Param))
13849       FD->ModifiedNonNullParams.insert(Param);
13850 }
13851 
13852 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13853 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13854                                         SourceLocation OpLoc) {
13855   if (Op->isTypeDependent())
13856     return S.Context.DependentTy;
13857 
13858   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13859   if (ConvResult.isInvalid())
13860     return QualType();
13861   Op = ConvResult.get();
13862   QualType OpTy = Op->getType();
13863   QualType Result;
13864 
13865   if (isa<CXXReinterpretCastExpr>(Op)) {
13866     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13867     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13868                                      Op->getSourceRange());
13869   }
13870 
13871   if (const PointerType *PT = OpTy->getAs<PointerType>())
13872   {
13873     Result = PT->getPointeeType();
13874   }
13875   else if (const ObjCObjectPointerType *OPT =
13876              OpTy->getAs<ObjCObjectPointerType>())
13877     Result = OPT->getPointeeType();
13878   else {
13879     ExprResult PR = S.CheckPlaceholderExpr(Op);
13880     if (PR.isInvalid()) return QualType();
13881     if (PR.get() != Op)
13882       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13883   }
13884 
13885   if (Result.isNull()) {
13886     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13887       << OpTy << Op->getSourceRange();
13888     return QualType();
13889   }
13890 
13891   // Note that per both C89 and C99, indirection is always legal, even if Result
13892   // is an incomplete type or void.  It would be possible to warn about
13893   // dereferencing a void pointer, but it's completely well-defined, and such a
13894   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13895   // for pointers to 'void' but is fine for any other pointer type:
13896   //
13897   // C++ [expr.unary.op]p1:
13898   //   [...] the expression to which [the unary * operator] is applied shall
13899   //   be a pointer to an object type, or a pointer to a function type
13900   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13901     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13902       << OpTy << Op->getSourceRange();
13903 
13904   // Dereferences are usually l-values...
13905   VK = VK_LValue;
13906 
13907   // ...except that certain expressions are never l-values in C.
13908   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13909     VK = VK_PRValue;
13910 
13911   return Result;
13912 }
13913 
13914 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13915   BinaryOperatorKind Opc;
13916   switch (Kind) {
13917   default: llvm_unreachable("Unknown binop!");
13918   case tok::periodstar:           Opc = BO_PtrMemD; break;
13919   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13920   case tok::star:                 Opc = BO_Mul; break;
13921   case tok::slash:                Opc = BO_Div; break;
13922   case tok::percent:              Opc = BO_Rem; break;
13923   case tok::plus:                 Opc = BO_Add; break;
13924   case tok::minus:                Opc = BO_Sub; break;
13925   case tok::lessless:             Opc = BO_Shl; break;
13926   case tok::greatergreater:       Opc = BO_Shr; break;
13927   case tok::lessequal:            Opc = BO_LE; break;
13928   case tok::less:                 Opc = BO_LT; break;
13929   case tok::greaterequal:         Opc = BO_GE; break;
13930   case tok::greater:              Opc = BO_GT; break;
13931   case tok::exclaimequal:         Opc = BO_NE; break;
13932   case tok::equalequal:           Opc = BO_EQ; break;
13933   case tok::spaceship:            Opc = BO_Cmp; break;
13934   case tok::amp:                  Opc = BO_And; break;
13935   case tok::caret:                Opc = BO_Xor; break;
13936   case tok::pipe:                 Opc = BO_Or; break;
13937   case tok::ampamp:               Opc = BO_LAnd; break;
13938   case tok::pipepipe:             Opc = BO_LOr; break;
13939   case tok::equal:                Opc = BO_Assign; break;
13940   case tok::starequal:            Opc = BO_MulAssign; break;
13941   case tok::slashequal:           Opc = BO_DivAssign; break;
13942   case tok::percentequal:         Opc = BO_RemAssign; break;
13943   case tok::plusequal:            Opc = BO_AddAssign; break;
13944   case tok::minusequal:           Opc = BO_SubAssign; break;
13945   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13946   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13947   case tok::ampequal:             Opc = BO_AndAssign; break;
13948   case tok::caretequal:           Opc = BO_XorAssign; break;
13949   case tok::pipeequal:            Opc = BO_OrAssign; break;
13950   case tok::comma:                Opc = BO_Comma; break;
13951   }
13952   return Opc;
13953 }
13954 
13955 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13956   tok::TokenKind Kind) {
13957   UnaryOperatorKind Opc;
13958   switch (Kind) {
13959   default: llvm_unreachable("Unknown unary op!");
13960   case tok::plusplus:     Opc = UO_PreInc; break;
13961   case tok::minusminus:   Opc = UO_PreDec; break;
13962   case tok::amp:          Opc = UO_AddrOf; break;
13963   case tok::star:         Opc = UO_Deref; break;
13964   case tok::plus:         Opc = UO_Plus; break;
13965   case tok::minus:        Opc = UO_Minus; break;
13966   case tok::tilde:        Opc = UO_Not; break;
13967   case tok::exclaim:      Opc = UO_LNot; break;
13968   case tok::kw___real:    Opc = UO_Real; break;
13969   case tok::kw___imag:    Opc = UO_Imag; break;
13970   case tok::kw___extension__: Opc = UO_Extension; break;
13971   }
13972   return Opc;
13973 }
13974 
13975 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13976 /// This warning suppressed in the event of macro expansions.
13977 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13978                                    SourceLocation OpLoc, bool IsBuiltin) {
13979   if (S.inTemplateInstantiation())
13980     return;
13981   if (S.isUnevaluatedContext())
13982     return;
13983   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13984     return;
13985   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13986   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13987   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13988   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13989   if (!LHSDeclRef || !RHSDeclRef ||
13990       LHSDeclRef->getLocation().isMacroID() ||
13991       RHSDeclRef->getLocation().isMacroID())
13992     return;
13993   const ValueDecl *LHSDecl =
13994     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13995   const ValueDecl *RHSDecl =
13996     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13997   if (LHSDecl != RHSDecl)
13998     return;
13999   if (LHSDecl->getType().isVolatileQualified())
14000     return;
14001   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14002     if (RefTy->getPointeeType().isVolatileQualified())
14003       return;
14004 
14005   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14006                           : diag::warn_self_assignment_overloaded)
14007       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14008       << RHSExpr->getSourceRange();
14009 }
14010 
14011 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
14012 /// is usually indicative of introspection within the Objective-C pointer.
14013 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
14014                                           SourceLocation OpLoc) {
14015   if (!S.getLangOpts().ObjC)
14016     return;
14017 
14018   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14019   const Expr *LHS = L.get();
14020   const Expr *RHS = R.get();
14021 
14022   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14023     ObjCPointerExpr = LHS;
14024     OtherExpr = RHS;
14025   }
14026   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14027     ObjCPointerExpr = RHS;
14028     OtherExpr = LHS;
14029   }
14030 
14031   // This warning is deliberately made very specific to reduce false
14032   // positives with logic that uses '&' for hashing.  This logic mainly
14033   // looks for code trying to introspect into tagged pointers, which
14034   // code should generally never do.
14035   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14036     unsigned Diag = diag::warn_objc_pointer_masking;
14037     // Determine if we are introspecting the result of performSelectorXXX.
14038     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14039     // Special case messages to -performSelector and friends, which
14040     // can return non-pointer values boxed in a pointer value.
14041     // Some clients may wish to silence warnings in this subcase.
14042     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14043       Selector S = ME->getSelector();
14044       StringRef SelArg0 = S.getNameForSlot(0);
14045       if (SelArg0.startswith("performSelector"))
14046         Diag = diag::warn_objc_pointer_masking_performSelector;
14047     }
14048 
14049     S.Diag(OpLoc, Diag)
14050       << ObjCPointerExpr->getSourceRange();
14051   }
14052 }
14053 
14054 static NamedDecl *getDeclFromExpr(Expr *E) {
14055   if (!E)
14056     return nullptr;
14057   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14058     return DRE->getDecl();
14059   if (auto *ME = dyn_cast<MemberExpr>(E))
14060     return ME->getMemberDecl();
14061   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14062     return IRE->getDecl();
14063   return nullptr;
14064 }
14065 
14066 // This helper function promotes a binary operator's operands (which are of a
14067 // half vector type) to a vector of floats and then truncates the result to
14068 // a vector of either half or short.
14069 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
14070                                       BinaryOperatorKind Opc, QualType ResultTy,
14071                                       ExprValueKind VK, ExprObjectKind OK,
14072                                       bool IsCompAssign, SourceLocation OpLoc,
14073                                       FPOptionsOverride FPFeatures) {
14074   auto &Context = S.getASTContext();
14075   assert((isVector(ResultTy, Context.HalfTy) ||
14076           isVector(ResultTy, Context.ShortTy)) &&
14077          "Result must be a vector of half or short");
14078   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14079          isVector(RHS.get()->getType(), Context.HalfTy) &&
14080          "both operands expected to be a half vector");
14081 
14082   RHS = convertVector(RHS.get(), Context.FloatTy, S);
14083   QualType BinOpResTy = RHS.get()->getType();
14084 
14085   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14086   // change BinOpResTy to a vector of ints.
14087   if (isVector(ResultTy, Context.ShortTy))
14088     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14089 
14090   if (IsCompAssign)
14091     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14092                                           ResultTy, VK, OK, OpLoc, FPFeatures,
14093                                           BinOpResTy, BinOpResTy);
14094 
14095   LHS = convertVector(LHS.get(), Context.FloatTy, S);
14096   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14097                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
14098   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14099 }
14100 
14101 static std::pair<ExprResult, ExprResult>
14102 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14103                            Expr *RHSExpr) {
14104   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14105   if (!S.Context.isDependenceAllowed()) {
14106     // C cannot handle TypoExpr nodes on either side of a binop because it
14107     // doesn't handle dependent types properly, so make sure any TypoExprs have
14108     // been dealt with before checking the operands.
14109     LHS = S.CorrectDelayedTyposInExpr(LHS);
14110     RHS = S.CorrectDelayedTyposInExpr(
14111         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14112         [Opc, LHS](Expr *E) {
14113           if (Opc != BO_Assign)
14114             return ExprResult(E);
14115           // Avoid correcting the RHS to the same Expr as the LHS.
14116           Decl *D = getDeclFromExpr(E);
14117           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14118         });
14119   }
14120   return std::make_pair(LHS, RHS);
14121 }
14122 
14123 /// Returns true if conversion between vectors of halfs and vectors of floats
14124 /// is needed.
14125 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14126                                      Expr *E0, Expr *E1 = nullptr) {
14127   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14128       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14129     return false;
14130 
14131   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14132     QualType Ty = E->IgnoreImplicit()->getType();
14133 
14134     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14135     // to vectors of floats. Although the element type of the vectors is __fp16,
14136     // the vectors shouldn't be treated as storage-only types. See the
14137     // discussion here: https://reviews.llvm.org/rG825235c140e7
14138     if (const VectorType *VT = Ty->getAs<VectorType>()) {
14139       if (VT->getVectorKind() == VectorType::NeonVector)
14140         return false;
14141       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14142     }
14143     return false;
14144   };
14145 
14146   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14147 }
14148 
14149 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
14150 /// operator @p Opc at location @c TokLoc. This routine only supports
14151 /// built-in operations; ActOnBinOp handles overloaded operators.
14152 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14153                                     BinaryOperatorKind Opc,
14154                                     Expr *LHSExpr, Expr *RHSExpr) {
14155   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14156     // The syntax only allows initializer lists on the RHS of assignment,
14157     // so we don't need to worry about accepting invalid code for
14158     // non-assignment operators.
14159     // C++11 5.17p9:
14160     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14161     //   of x = {} is x = T().
14162     InitializationKind Kind = InitializationKind::CreateDirectList(
14163         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14164     InitializedEntity Entity =
14165         InitializedEntity::InitializeTemporary(LHSExpr->getType());
14166     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14167     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14168     if (Init.isInvalid())
14169       return Init;
14170     RHSExpr = Init.get();
14171   }
14172 
14173   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14174   QualType ResultTy;     // Result type of the binary operator.
14175   // The following two variables are used for compound assignment operators
14176   QualType CompLHSTy;    // Type of LHS after promotions for computation
14177   QualType CompResultTy; // Type of computation result
14178   ExprValueKind VK = VK_PRValue;
14179   ExprObjectKind OK = OK_Ordinary;
14180   bool ConvertHalfVec = false;
14181 
14182   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14183   if (!LHS.isUsable() || !RHS.isUsable())
14184     return ExprError();
14185 
14186   if (getLangOpts().OpenCL) {
14187     QualType LHSTy = LHSExpr->getType();
14188     QualType RHSTy = RHSExpr->getType();
14189     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14190     // the ATOMIC_VAR_INIT macro.
14191     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14192       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14193       if (BO_Assign == Opc)
14194         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14195       else
14196         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14197       return ExprError();
14198     }
14199 
14200     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14201     // only with a builtin functions and therefore should be disallowed here.
14202     if (LHSTy->isImageType() || RHSTy->isImageType() ||
14203         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14204         LHSTy->isPipeType() || RHSTy->isPipeType() ||
14205         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14206       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14207       return ExprError();
14208     }
14209   }
14210 
14211   checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14212   checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14213 
14214   switch (Opc) {
14215   case BO_Assign:
14216     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14217     if (getLangOpts().CPlusPlus &&
14218         LHS.get()->getObjectKind() != OK_ObjCProperty) {
14219       VK = LHS.get()->getValueKind();
14220       OK = LHS.get()->getObjectKind();
14221     }
14222     if (!ResultTy.isNull()) {
14223       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14224       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14225 
14226       // Avoid copying a block to the heap if the block is assigned to a local
14227       // auto variable that is declared in the same scope as the block. This
14228       // optimization is unsafe if the local variable is declared in an outer
14229       // scope. For example:
14230       //
14231       // BlockTy b;
14232       // {
14233       //   b = ^{...};
14234       // }
14235       // // It is unsafe to invoke the block here if it wasn't copied to the
14236       // // heap.
14237       // b();
14238 
14239       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14240         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14241           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14242             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14243               BE->getBlockDecl()->setCanAvoidCopyToHeap();
14244 
14245       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14246         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14247                               NTCUC_Assignment, NTCUK_Copy);
14248     }
14249     RecordModifiableNonNullParam(*this, LHS.get());
14250     break;
14251   case BO_PtrMemD:
14252   case BO_PtrMemI:
14253     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14254                                             Opc == BO_PtrMemI);
14255     break;
14256   case BO_Mul:
14257   case BO_Div:
14258     ConvertHalfVec = true;
14259     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14260                                            Opc == BO_Div);
14261     break;
14262   case BO_Rem:
14263     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14264     break;
14265   case BO_Add:
14266     ConvertHalfVec = true;
14267     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14268     break;
14269   case BO_Sub:
14270     ConvertHalfVec = true;
14271     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14272     break;
14273   case BO_Shl:
14274   case BO_Shr:
14275     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14276     break;
14277   case BO_LE:
14278   case BO_LT:
14279   case BO_GE:
14280   case BO_GT:
14281     ConvertHalfVec = true;
14282     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14283     break;
14284   case BO_EQ:
14285   case BO_NE:
14286     ConvertHalfVec = true;
14287     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14288     break;
14289   case BO_Cmp:
14290     ConvertHalfVec = true;
14291     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14292     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14293     break;
14294   case BO_And:
14295     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14296     LLVM_FALLTHROUGH;
14297   case BO_Xor:
14298   case BO_Or:
14299     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14300     break;
14301   case BO_LAnd:
14302   case BO_LOr:
14303     ConvertHalfVec = true;
14304     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14305     break;
14306   case BO_MulAssign:
14307   case BO_DivAssign:
14308     ConvertHalfVec = true;
14309     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14310                                                Opc == BO_DivAssign);
14311     CompLHSTy = CompResultTy;
14312     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14313       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14314     break;
14315   case BO_RemAssign:
14316     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14317     CompLHSTy = CompResultTy;
14318     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14319       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14320     break;
14321   case BO_AddAssign:
14322     ConvertHalfVec = true;
14323     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14324     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14325       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14326     break;
14327   case BO_SubAssign:
14328     ConvertHalfVec = true;
14329     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14330     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14331       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14332     break;
14333   case BO_ShlAssign:
14334   case BO_ShrAssign:
14335     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14336     CompLHSTy = CompResultTy;
14337     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14338       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14339     break;
14340   case BO_AndAssign:
14341   case BO_OrAssign: // fallthrough
14342     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14343     LLVM_FALLTHROUGH;
14344   case BO_XorAssign:
14345     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14346     CompLHSTy = CompResultTy;
14347     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14348       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14349     break;
14350   case BO_Comma:
14351     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14352     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14353       VK = RHS.get()->getValueKind();
14354       OK = RHS.get()->getObjectKind();
14355     }
14356     break;
14357   }
14358   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14359     return ExprError();
14360 
14361   // Some of the binary operations require promoting operands of half vector to
14362   // float vectors and truncating the result back to half vector. For now, we do
14363   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14364   // arm64).
14365   assert(
14366       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14367                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
14368       "both sides are half vectors or neither sides are");
14369   ConvertHalfVec =
14370       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14371 
14372   // Check for array bounds violations for both sides of the BinaryOperator
14373   CheckArrayAccess(LHS.get());
14374   CheckArrayAccess(RHS.get());
14375 
14376   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14377     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14378                                                  &Context.Idents.get("object_setClass"),
14379                                                  SourceLocation(), LookupOrdinaryName);
14380     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14381       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14382       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14383           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14384                                         "object_setClass(")
14385           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14386                                           ",")
14387           << FixItHint::CreateInsertion(RHSLocEnd, ")");
14388     }
14389     else
14390       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14391   }
14392   else if (const ObjCIvarRefExpr *OIRE =
14393            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14394     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14395 
14396   // Opc is not a compound assignment if CompResultTy is null.
14397   if (CompResultTy.isNull()) {
14398     if (ConvertHalfVec)
14399       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14400                                  OpLoc, CurFPFeatureOverrides());
14401     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14402                                   VK, OK, OpLoc, CurFPFeatureOverrides());
14403   }
14404 
14405   // Handle compound assignments.
14406   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14407       OK_ObjCProperty) {
14408     VK = VK_LValue;
14409     OK = LHS.get()->getObjectKind();
14410   }
14411 
14412   // The LHS is not converted to the result type for fixed-point compound
14413   // assignment as the common type is computed on demand. Reset the CompLHSTy
14414   // to the LHS type we would have gotten after unary conversions.
14415   if (CompResultTy->isFixedPointType())
14416     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14417 
14418   if (ConvertHalfVec)
14419     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14420                                OpLoc, CurFPFeatureOverrides());
14421 
14422   return CompoundAssignOperator::Create(
14423       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14424       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14425 }
14426 
14427 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14428 /// operators are mixed in a way that suggests that the programmer forgot that
14429 /// comparison operators have higher precedence. The most typical example of
14430 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14431 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14432                                       SourceLocation OpLoc, Expr *LHSExpr,
14433                                       Expr *RHSExpr) {
14434   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14435   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14436 
14437   // Check that one of the sides is a comparison operator and the other isn't.
14438   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14439   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14440   if (isLeftComp == isRightComp)
14441     return;
14442 
14443   // Bitwise operations are sometimes used as eager logical ops.
14444   // Don't diagnose this.
14445   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14446   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14447   if (isLeftBitwise || isRightBitwise)
14448     return;
14449 
14450   SourceRange DiagRange = isLeftComp
14451                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14452                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14453   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14454   SourceRange ParensRange =
14455       isLeftComp
14456           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14457           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14458 
14459   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14460     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14461   SuggestParentheses(Self, OpLoc,
14462     Self.PDiag(diag::note_precedence_silence) << OpStr,
14463     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14464   SuggestParentheses(Self, OpLoc,
14465     Self.PDiag(diag::note_precedence_bitwise_first)
14466       << BinaryOperator::getOpcodeStr(Opc),
14467     ParensRange);
14468 }
14469 
14470 /// It accepts a '&&' expr that is inside a '||' one.
14471 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14472 /// in parentheses.
14473 static void
14474 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14475                                        BinaryOperator *Bop) {
14476   assert(Bop->getOpcode() == BO_LAnd);
14477   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14478       << Bop->getSourceRange() << OpLoc;
14479   SuggestParentheses(Self, Bop->getOperatorLoc(),
14480     Self.PDiag(diag::note_precedence_silence)
14481       << Bop->getOpcodeStr(),
14482     Bop->getSourceRange());
14483 }
14484 
14485 /// Returns true if the given expression can be evaluated as a constant
14486 /// 'true'.
14487 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14488   bool Res;
14489   return !E->isValueDependent() &&
14490          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14491 }
14492 
14493 /// Returns true if the given expression can be evaluated as a constant
14494 /// 'false'.
14495 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14496   bool Res;
14497   return !E->isValueDependent() &&
14498          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14499 }
14500 
14501 /// Look for '&&' in the left hand of a '||' expr.
14502 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14503                                              Expr *LHSExpr, Expr *RHSExpr) {
14504   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14505     if (Bop->getOpcode() == BO_LAnd) {
14506       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14507       if (EvaluatesAsFalse(S, RHSExpr))
14508         return;
14509       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14510       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14511         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14512     } else if (Bop->getOpcode() == BO_LOr) {
14513       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14514         // If it's "a || b && 1 || c" we didn't warn earlier for
14515         // "a || b && 1", but warn now.
14516         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14517           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14518       }
14519     }
14520   }
14521 }
14522 
14523 /// Look for '&&' in the right hand of a '||' expr.
14524 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14525                                              Expr *LHSExpr, Expr *RHSExpr) {
14526   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14527     if (Bop->getOpcode() == BO_LAnd) {
14528       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14529       if (EvaluatesAsFalse(S, LHSExpr))
14530         return;
14531       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14532       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14533         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14534     }
14535   }
14536 }
14537 
14538 /// Look for bitwise op in the left or right hand of a bitwise op with
14539 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14540 /// the '&' expression in parentheses.
14541 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14542                                          SourceLocation OpLoc, Expr *SubExpr) {
14543   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14544     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14545       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14546         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14547         << Bop->getSourceRange() << OpLoc;
14548       SuggestParentheses(S, Bop->getOperatorLoc(),
14549         S.PDiag(diag::note_precedence_silence)
14550           << Bop->getOpcodeStr(),
14551         Bop->getSourceRange());
14552     }
14553   }
14554 }
14555 
14556 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14557                                     Expr *SubExpr, StringRef Shift) {
14558   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14559     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14560       StringRef Op = Bop->getOpcodeStr();
14561       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14562           << Bop->getSourceRange() << OpLoc << Shift << Op;
14563       SuggestParentheses(S, Bop->getOperatorLoc(),
14564           S.PDiag(diag::note_precedence_silence) << Op,
14565           Bop->getSourceRange());
14566     }
14567   }
14568 }
14569 
14570 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14571                                  Expr *LHSExpr, Expr *RHSExpr) {
14572   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14573   if (!OCE)
14574     return;
14575 
14576   FunctionDecl *FD = OCE->getDirectCallee();
14577   if (!FD || !FD->isOverloadedOperator())
14578     return;
14579 
14580   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14581   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14582     return;
14583 
14584   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14585       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14586       << (Kind == OO_LessLess);
14587   SuggestParentheses(S, OCE->getOperatorLoc(),
14588                      S.PDiag(diag::note_precedence_silence)
14589                          << (Kind == OO_LessLess ? "<<" : ">>"),
14590                      OCE->getSourceRange());
14591   SuggestParentheses(
14592       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14593       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14594 }
14595 
14596 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14597 /// precedence.
14598 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14599                                     SourceLocation OpLoc, Expr *LHSExpr,
14600                                     Expr *RHSExpr){
14601   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14602   if (BinaryOperator::isBitwiseOp(Opc))
14603     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14604 
14605   // Diagnose "arg1 & arg2 | arg3"
14606   if ((Opc == BO_Or || Opc == BO_Xor) &&
14607       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14608     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14609     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14610   }
14611 
14612   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14613   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14614   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14615     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14616     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14617   }
14618 
14619   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14620       || Opc == BO_Shr) {
14621     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14622     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14623     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14624   }
14625 
14626   // Warn on overloaded shift operators and comparisons, such as:
14627   // cout << 5 == 4;
14628   if (BinaryOperator::isComparisonOp(Opc))
14629     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14630 }
14631 
14632 // Binary Operators.  'Tok' is the token for the operator.
14633 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14634                             tok::TokenKind Kind,
14635                             Expr *LHSExpr, Expr *RHSExpr) {
14636   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14637   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14638   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14639 
14640   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14641   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14642 
14643   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14644 }
14645 
14646 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14647                        UnresolvedSetImpl &Functions) {
14648   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14649   if (OverOp != OO_None && OverOp != OO_Equal)
14650     LookupOverloadedOperatorName(OverOp, S, Functions);
14651 
14652   // In C++20 onwards, we may have a second operator to look up.
14653   if (getLangOpts().CPlusPlus20) {
14654     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14655       LookupOverloadedOperatorName(ExtraOp, S, Functions);
14656   }
14657 }
14658 
14659 /// Build an overloaded binary operator expression in the given scope.
14660 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14661                                        BinaryOperatorKind Opc,
14662                                        Expr *LHS, Expr *RHS) {
14663   switch (Opc) {
14664   case BO_Assign:
14665   case BO_DivAssign:
14666   case BO_RemAssign:
14667   case BO_SubAssign:
14668   case BO_AndAssign:
14669   case BO_OrAssign:
14670   case BO_XorAssign:
14671     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14672     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14673     break;
14674   default:
14675     break;
14676   }
14677 
14678   // Find all of the overloaded operators visible from this point.
14679   UnresolvedSet<16> Functions;
14680   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14681 
14682   // Build the (potentially-overloaded, potentially-dependent)
14683   // binary operation.
14684   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14685 }
14686 
14687 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14688                             BinaryOperatorKind Opc,
14689                             Expr *LHSExpr, Expr *RHSExpr) {
14690   ExprResult LHS, RHS;
14691   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14692   if (!LHS.isUsable() || !RHS.isUsable())
14693     return ExprError();
14694   LHSExpr = LHS.get();
14695   RHSExpr = RHS.get();
14696 
14697   // We want to end up calling one of checkPseudoObjectAssignment
14698   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14699   // both expressions are overloadable or either is type-dependent),
14700   // or CreateBuiltinBinOp (in any other case).  We also want to get
14701   // any placeholder types out of the way.
14702 
14703   // Handle pseudo-objects in the LHS.
14704   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14705     // Assignments with a pseudo-object l-value need special analysis.
14706     if (pty->getKind() == BuiltinType::PseudoObject &&
14707         BinaryOperator::isAssignmentOp(Opc))
14708       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14709 
14710     // Don't resolve overloads if the other type is overloadable.
14711     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14712       // We can't actually test that if we still have a placeholder,
14713       // though.  Fortunately, none of the exceptions we see in that
14714       // code below are valid when the LHS is an overload set.  Note
14715       // that an overload set can be dependently-typed, but it never
14716       // instantiates to having an overloadable type.
14717       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14718       if (resolvedRHS.isInvalid()) return ExprError();
14719       RHSExpr = resolvedRHS.get();
14720 
14721       if (RHSExpr->isTypeDependent() ||
14722           RHSExpr->getType()->isOverloadableType())
14723         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14724     }
14725 
14726     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14727     // template, diagnose the missing 'template' keyword instead of diagnosing
14728     // an invalid use of a bound member function.
14729     //
14730     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14731     // to C++1z [over.over]/1.4, but we already checked for that case above.
14732     if (Opc == BO_LT && inTemplateInstantiation() &&
14733         (pty->getKind() == BuiltinType::BoundMember ||
14734          pty->getKind() == BuiltinType::Overload)) {
14735       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14736       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14737           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14738             return isa<FunctionTemplateDecl>(ND);
14739           })) {
14740         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14741                                 : OE->getNameLoc(),
14742              diag::err_template_kw_missing)
14743           << OE->getName().getAsString() << "";
14744         return ExprError();
14745       }
14746     }
14747 
14748     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14749     if (LHS.isInvalid()) return ExprError();
14750     LHSExpr = LHS.get();
14751   }
14752 
14753   // Handle pseudo-objects in the RHS.
14754   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14755     // An overload in the RHS can potentially be resolved by the type
14756     // being assigned to.
14757     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14758       if (getLangOpts().CPlusPlus &&
14759           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14760            LHSExpr->getType()->isOverloadableType()))
14761         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14762 
14763       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14764     }
14765 
14766     // Don't resolve overloads if the other type is overloadable.
14767     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14768         LHSExpr->getType()->isOverloadableType())
14769       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14770 
14771     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14772     if (!resolvedRHS.isUsable()) return ExprError();
14773     RHSExpr = resolvedRHS.get();
14774   }
14775 
14776   if (getLangOpts().CPlusPlus) {
14777     // If either expression is type-dependent, always build an
14778     // overloaded op.
14779     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14780       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14781 
14782     // Otherwise, build an overloaded op if either expression has an
14783     // overloadable type.
14784     if (LHSExpr->getType()->isOverloadableType() ||
14785         RHSExpr->getType()->isOverloadableType())
14786       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14787   }
14788 
14789   if (getLangOpts().RecoveryAST &&
14790       (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
14791     assert(!getLangOpts().CPlusPlus);
14792     assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
14793            "Should only occur in error-recovery path.");
14794     if (BinaryOperator::isCompoundAssignmentOp(Opc))
14795       // C [6.15.16] p3:
14796       // An assignment expression has the value of the left operand after the
14797       // assignment, but is not an lvalue.
14798       return CompoundAssignOperator::Create(
14799           Context, LHSExpr, RHSExpr, Opc,
14800           LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
14801           OpLoc, CurFPFeatureOverrides());
14802     QualType ResultType;
14803     switch (Opc) {
14804     case BO_Assign:
14805       ResultType = LHSExpr->getType().getUnqualifiedType();
14806       break;
14807     case BO_LT:
14808     case BO_GT:
14809     case BO_LE:
14810     case BO_GE:
14811     case BO_EQ:
14812     case BO_NE:
14813     case BO_LAnd:
14814     case BO_LOr:
14815       // These operators have a fixed result type regardless of operands.
14816       ResultType = Context.IntTy;
14817       break;
14818     case BO_Comma:
14819       ResultType = RHSExpr->getType();
14820       break;
14821     default:
14822       ResultType = Context.DependentTy;
14823       break;
14824     }
14825     return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
14826                                   VK_PRValue, OK_Ordinary, OpLoc,
14827                                   CurFPFeatureOverrides());
14828   }
14829 
14830   // Build a built-in binary operation.
14831   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14832 }
14833 
14834 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14835   if (T.isNull() || T->isDependentType())
14836     return false;
14837 
14838   if (!T->isPromotableIntegerType())
14839     return true;
14840 
14841   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14842 }
14843 
14844 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14845                                       UnaryOperatorKind Opc,
14846                                       Expr *InputExpr) {
14847   ExprResult Input = InputExpr;
14848   ExprValueKind VK = VK_PRValue;
14849   ExprObjectKind OK = OK_Ordinary;
14850   QualType resultType;
14851   bool CanOverflow = false;
14852 
14853   bool ConvertHalfVec = false;
14854   if (getLangOpts().OpenCL) {
14855     QualType Ty = InputExpr->getType();
14856     // The only legal unary operation for atomics is '&'.
14857     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14858     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14859     // only with a builtin functions and therefore should be disallowed here.
14860         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14861         || Ty->isBlockPointerType())) {
14862       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14863                        << InputExpr->getType()
14864                        << Input.get()->getSourceRange());
14865     }
14866   }
14867 
14868   switch (Opc) {
14869   case UO_PreInc:
14870   case UO_PreDec:
14871   case UO_PostInc:
14872   case UO_PostDec:
14873     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14874                                                 OpLoc,
14875                                                 Opc == UO_PreInc ||
14876                                                 Opc == UO_PostInc,
14877                                                 Opc == UO_PreInc ||
14878                                                 Opc == UO_PreDec);
14879     CanOverflow = isOverflowingIntegerType(Context, resultType);
14880     break;
14881   case UO_AddrOf:
14882     resultType = CheckAddressOfOperand(Input, OpLoc);
14883     CheckAddressOfNoDeref(InputExpr);
14884     RecordModifiableNonNullParam(*this, InputExpr);
14885     break;
14886   case UO_Deref: {
14887     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14888     if (Input.isInvalid()) return ExprError();
14889     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14890     break;
14891   }
14892   case UO_Plus:
14893   case UO_Minus:
14894     CanOverflow = Opc == UO_Minus &&
14895                   isOverflowingIntegerType(Context, Input.get()->getType());
14896     Input = UsualUnaryConversions(Input.get());
14897     if (Input.isInvalid()) return ExprError();
14898     // Unary plus and minus require promoting an operand of half vector to a
14899     // float vector and truncating the result back to a half vector. For now, we
14900     // do this only when HalfArgsAndReturns is set (that is, when the target is
14901     // arm or arm64).
14902     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14903 
14904     // If the operand is a half vector, promote it to a float vector.
14905     if (ConvertHalfVec)
14906       Input = convertVector(Input.get(), Context.FloatTy, *this);
14907     resultType = Input.get()->getType();
14908     if (resultType->isDependentType())
14909       break;
14910     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14911       break;
14912     else if (resultType->isVectorType() &&
14913              // The z vector extensions don't allow + or - with bool vectors.
14914              (!Context.getLangOpts().ZVector ||
14915               resultType->castAs<VectorType>()->getVectorKind() !=
14916               VectorType::AltiVecBool))
14917       break;
14918     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14919              Opc == UO_Plus &&
14920              resultType->isPointerType())
14921       break;
14922 
14923     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14924       << resultType << Input.get()->getSourceRange());
14925 
14926   case UO_Not: // bitwise complement
14927     Input = UsualUnaryConversions(Input.get());
14928     if (Input.isInvalid())
14929       return ExprError();
14930     resultType = Input.get()->getType();
14931     if (resultType->isDependentType())
14932       break;
14933     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14934     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14935       // C99 does not support '~' for complex conjugation.
14936       Diag(OpLoc, diag::ext_integer_complement_complex)
14937           << resultType << Input.get()->getSourceRange();
14938     else if (resultType->hasIntegerRepresentation())
14939       break;
14940     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14941       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14942       // on vector float types.
14943       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14944       if (!T->isIntegerType())
14945         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14946                           << resultType << Input.get()->getSourceRange());
14947     } else {
14948       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14949                        << resultType << Input.get()->getSourceRange());
14950     }
14951     break;
14952 
14953   case UO_LNot: // logical negation
14954     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14955     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14956     if (Input.isInvalid()) return ExprError();
14957     resultType = Input.get()->getType();
14958 
14959     // Though we still have to promote half FP to float...
14960     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14961       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14962       resultType = Context.FloatTy;
14963     }
14964 
14965     if (resultType->isDependentType())
14966       break;
14967     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14968       // C99 6.5.3.3p1: ok, fallthrough;
14969       if (Context.getLangOpts().CPlusPlus) {
14970         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14971         // operand contextually converted to bool.
14972         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14973                                   ScalarTypeToBooleanCastKind(resultType));
14974       } else if (Context.getLangOpts().OpenCL &&
14975                  Context.getLangOpts().OpenCLVersion < 120) {
14976         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14977         // operate on scalar float types.
14978         if (!resultType->isIntegerType() && !resultType->isPointerType())
14979           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14980                            << resultType << Input.get()->getSourceRange());
14981       }
14982     } else if (resultType->isExtVectorType()) {
14983       if (Context.getLangOpts().OpenCL &&
14984           Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
14985         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14986         // operate on vector float types.
14987         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14988         if (!T->isIntegerType())
14989           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14990                            << resultType << Input.get()->getSourceRange());
14991       }
14992       // Vector logical not returns the signed variant of the operand type.
14993       resultType = GetSignedVectorType(resultType);
14994       break;
14995     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14996       const VectorType *VTy = resultType->castAs<VectorType>();
14997       if (VTy->getVectorKind() != VectorType::GenericVector)
14998         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14999                          << resultType << Input.get()->getSourceRange());
15000 
15001       // Vector logical not returns the signed variant of the operand type.
15002       resultType = GetSignedVectorType(resultType);
15003       break;
15004     } else {
15005       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15006         << resultType << Input.get()->getSourceRange());
15007     }
15008 
15009     // LNot always has type int. C99 6.5.3.3p5.
15010     // In C++, it's bool. C++ 5.3.1p8
15011     resultType = Context.getLogicalOperationType();
15012     break;
15013   case UO_Real:
15014   case UO_Imag:
15015     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15016     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
15017     // complex l-values to ordinary l-values and all other values to r-values.
15018     if (Input.isInvalid()) return ExprError();
15019     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15020       if (Input.get()->isGLValue() &&
15021           Input.get()->getObjectKind() == OK_Ordinary)
15022         VK = Input.get()->getValueKind();
15023     } else if (!getLangOpts().CPlusPlus) {
15024       // In C, a volatile scalar is read by __imag. In C++, it is not.
15025       Input = DefaultLvalueConversion(Input.get());
15026     }
15027     break;
15028   case UO_Extension:
15029     resultType = Input.get()->getType();
15030     VK = Input.get()->getValueKind();
15031     OK = Input.get()->getObjectKind();
15032     break;
15033   case UO_Coawait:
15034     // It's unnecessary to represent the pass-through operator co_await in the
15035     // AST; just return the input expression instead.
15036     assert(!Input.get()->getType()->isDependentType() &&
15037                    "the co_await expression must be non-dependant before "
15038                    "building operator co_await");
15039     return Input;
15040   }
15041   if (resultType.isNull() || Input.isInvalid())
15042     return ExprError();
15043 
15044   // Check for array bounds violations in the operand of the UnaryOperator,
15045   // except for the '*' and '&' operators that have to be handled specially
15046   // by CheckArrayAccess (as there are special cases like &array[arraysize]
15047   // that are explicitly defined as valid by the standard).
15048   if (Opc != UO_AddrOf && Opc != UO_Deref)
15049     CheckArrayAccess(Input.get());
15050 
15051   auto *UO =
15052       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15053                             OpLoc, CanOverflow, CurFPFeatureOverrides());
15054 
15055   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15056       !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15057       !isUnevaluatedContext())
15058     ExprEvalContexts.back().PossibleDerefs.insert(UO);
15059 
15060   // Convert the result back to a half vector.
15061   if (ConvertHalfVec)
15062     return convertVector(UO, Context.HalfTy, *this);
15063   return UO;
15064 }
15065 
15066 /// Determine whether the given expression is a qualified member
15067 /// access expression, of a form that could be turned into a pointer to member
15068 /// with the address-of operator.
15069 bool Sema::isQualifiedMemberAccess(Expr *E) {
15070   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15071     if (!DRE->getQualifier())
15072       return false;
15073 
15074     ValueDecl *VD = DRE->getDecl();
15075     if (!VD->isCXXClassMember())
15076       return false;
15077 
15078     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15079       return true;
15080     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15081       return Method->isInstance();
15082 
15083     return false;
15084   }
15085 
15086   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15087     if (!ULE->getQualifier())
15088       return false;
15089 
15090     for (NamedDecl *D : ULE->decls()) {
15091       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15092         if (Method->isInstance())
15093           return true;
15094       } else {
15095         // Overload set does not contain methods.
15096         break;
15097       }
15098     }
15099 
15100     return false;
15101   }
15102 
15103   return false;
15104 }
15105 
15106 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15107                               UnaryOperatorKind Opc, Expr *Input) {
15108   // First things first: handle placeholders so that the
15109   // overloaded-operator check considers the right type.
15110   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15111     // Increment and decrement of pseudo-object references.
15112     if (pty->getKind() == BuiltinType::PseudoObject &&
15113         UnaryOperator::isIncrementDecrementOp(Opc))
15114       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15115 
15116     // extension is always a builtin operator.
15117     if (Opc == UO_Extension)
15118       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15119 
15120     // & gets special logic for several kinds of placeholder.
15121     // The builtin code knows what to do.
15122     if (Opc == UO_AddrOf &&
15123         (pty->getKind() == BuiltinType::Overload ||
15124          pty->getKind() == BuiltinType::UnknownAny ||
15125          pty->getKind() == BuiltinType::BoundMember))
15126       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15127 
15128     // Anything else needs to be handled now.
15129     ExprResult Result = CheckPlaceholderExpr(Input);
15130     if (Result.isInvalid()) return ExprError();
15131     Input = Result.get();
15132   }
15133 
15134   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15135       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15136       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15137     // Find all of the overloaded operators visible from this point.
15138     UnresolvedSet<16> Functions;
15139     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15140     if (S && OverOp != OO_None)
15141       LookupOverloadedOperatorName(OverOp, S, Functions);
15142 
15143     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15144   }
15145 
15146   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15147 }
15148 
15149 // Unary Operators.  'Tok' is the token for the operator.
15150 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
15151                               tok::TokenKind Op, Expr *Input) {
15152   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
15153 }
15154 
15155 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15156 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15157                                 LabelDecl *TheDecl) {
15158   TheDecl->markUsed(Context);
15159   // Create the AST node.  The address of a label always has type 'void*'.
15160   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
15161                                      Context.getPointerType(Context.VoidTy));
15162 }
15163 
15164 void Sema::ActOnStartStmtExpr() {
15165   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15166 }
15167 
15168 void Sema::ActOnStmtExprError() {
15169   // Note that function is also called by TreeTransform when leaving a
15170   // StmtExpr scope without rebuilding anything.
15171 
15172   DiscardCleanupsInEvaluationContext();
15173   PopExpressionEvaluationContext();
15174 }
15175 
15176 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15177                                SourceLocation RPLoc) {
15178   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15179 }
15180 
15181 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15182                                SourceLocation RPLoc, unsigned TemplateDepth) {
15183   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15184   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15185 
15186   if (hasAnyUnrecoverableErrorsInThisFunction())
15187     DiscardCleanupsInEvaluationContext();
15188   assert(!Cleanup.exprNeedsCleanups() &&
15189          "cleanups within StmtExpr not correctly bound!");
15190   PopExpressionEvaluationContext();
15191 
15192   // FIXME: there are a variety of strange constraints to enforce here, for
15193   // example, it is not possible to goto into a stmt expression apparently.
15194   // More semantic analysis is needed.
15195 
15196   // If there are sub-stmts in the compound stmt, take the type of the last one
15197   // as the type of the stmtexpr.
15198   QualType Ty = Context.VoidTy;
15199   bool StmtExprMayBindToTemp = false;
15200   if (!Compound->body_empty()) {
15201     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15202     if (const auto *LastStmt =
15203             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15204       if (const Expr *Value = LastStmt->getExprStmt()) {
15205         StmtExprMayBindToTemp = true;
15206         Ty = Value->getType();
15207       }
15208     }
15209   }
15210 
15211   // FIXME: Check that expression type is complete/non-abstract; statement
15212   // expressions are not lvalues.
15213   Expr *ResStmtExpr =
15214       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15215   if (StmtExprMayBindToTemp)
15216     return MaybeBindToTemporary(ResStmtExpr);
15217   return ResStmtExpr;
15218 }
15219 
15220 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15221   if (ER.isInvalid())
15222     return ExprError();
15223 
15224   // Do function/array conversion on the last expression, but not
15225   // lvalue-to-rvalue.  However, initialize an unqualified type.
15226   ER = DefaultFunctionArrayConversion(ER.get());
15227   if (ER.isInvalid())
15228     return ExprError();
15229   Expr *E = ER.get();
15230 
15231   if (E->isTypeDependent())
15232     return E;
15233 
15234   // In ARC, if the final expression ends in a consume, splice
15235   // the consume out and bind it later.  In the alternate case
15236   // (when dealing with a retainable type), the result
15237   // initialization will create a produce.  In both cases the
15238   // result will be +1, and we'll need to balance that out with
15239   // a bind.
15240   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15241   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15242     return Cast->getSubExpr();
15243 
15244   // FIXME: Provide a better location for the initialization.
15245   return PerformCopyInitialization(
15246       InitializedEntity::InitializeStmtExprResult(
15247           E->getBeginLoc(), E->getType().getUnqualifiedType()),
15248       SourceLocation(), E);
15249 }
15250 
15251 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15252                                       TypeSourceInfo *TInfo,
15253                                       ArrayRef<OffsetOfComponent> Components,
15254                                       SourceLocation RParenLoc) {
15255   QualType ArgTy = TInfo->getType();
15256   bool Dependent = ArgTy->isDependentType();
15257   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15258 
15259   // We must have at least one component that refers to the type, and the first
15260   // one is known to be a field designator.  Verify that the ArgTy represents
15261   // a struct/union/class.
15262   if (!Dependent && !ArgTy->isRecordType())
15263     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15264                        << ArgTy << TypeRange);
15265 
15266   // Type must be complete per C99 7.17p3 because a declaring a variable
15267   // with an incomplete type would be ill-formed.
15268   if (!Dependent
15269       && RequireCompleteType(BuiltinLoc, ArgTy,
15270                              diag::err_offsetof_incomplete_type, TypeRange))
15271     return ExprError();
15272 
15273   bool DidWarnAboutNonPOD = false;
15274   QualType CurrentType = ArgTy;
15275   SmallVector<OffsetOfNode, 4> Comps;
15276   SmallVector<Expr*, 4> Exprs;
15277   for (const OffsetOfComponent &OC : Components) {
15278     if (OC.isBrackets) {
15279       // Offset of an array sub-field.  TODO: Should we allow vector elements?
15280       if (!CurrentType->isDependentType()) {
15281         const ArrayType *AT = Context.getAsArrayType(CurrentType);
15282         if(!AT)
15283           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15284                            << CurrentType);
15285         CurrentType = AT->getElementType();
15286       } else
15287         CurrentType = Context.DependentTy;
15288 
15289       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15290       if (IdxRval.isInvalid())
15291         return ExprError();
15292       Expr *Idx = IdxRval.get();
15293 
15294       // The expression must be an integral expression.
15295       // FIXME: An integral constant expression?
15296       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15297           !Idx->getType()->isIntegerType())
15298         return ExprError(
15299             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15300             << Idx->getSourceRange());
15301 
15302       // Record this array index.
15303       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15304       Exprs.push_back(Idx);
15305       continue;
15306     }
15307 
15308     // Offset of a field.
15309     if (CurrentType->isDependentType()) {
15310       // We have the offset of a field, but we can't look into the dependent
15311       // type. Just record the identifier of the field.
15312       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15313       CurrentType = Context.DependentTy;
15314       continue;
15315     }
15316 
15317     // We need to have a complete type to look into.
15318     if (RequireCompleteType(OC.LocStart, CurrentType,
15319                             diag::err_offsetof_incomplete_type))
15320       return ExprError();
15321 
15322     // Look for the designated field.
15323     const RecordType *RC = CurrentType->getAs<RecordType>();
15324     if (!RC)
15325       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15326                        << CurrentType);
15327     RecordDecl *RD = RC->getDecl();
15328 
15329     // C++ [lib.support.types]p5:
15330     //   The macro offsetof accepts a restricted set of type arguments in this
15331     //   International Standard. type shall be a POD structure or a POD union
15332     //   (clause 9).
15333     // C++11 [support.types]p4:
15334     //   If type is not a standard-layout class (Clause 9), the results are
15335     //   undefined.
15336     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15337       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15338       unsigned DiagID =
15339         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15340                             : diag::ext_offsetof_non_pod_type;
15341 
15342       if (!IsSafe && !DidWarnAboutNonPOD &&
15343           DiagRuntimeBehavior(BuiltinLoc, nullptr,
15344                               PDiag(DiagID)
15345                               << SourceRange(Components[0].LocStart, OC.LocEnd)
15346                               << CurrentType))
15347         DidWarnAboutNonPOD = true;
15348     }
15349 
15350     // Look for the field.
15351     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15352     LookupQualifiedName(R, RD);
15353     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15354     IndirectFieldDecl *IndirectMemberDecl = nullptr;
15355     if (!MemberDecl) {
15356       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15357         MemberDecl = IndirectMemberDecl->getAnonField();
15358     }
15359 
15360     if (!MemberDecl)
15361       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15362                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15363                                                               OC.LocEnd));
15364 
15365     // C99 7.17p3:
15366     //   (If the specified member is a bit-field, the behavior is undefined.)
15367     //
15368     // We diagnose this as an error.
15369     if (MemberDecl->isBitField()) {
15370       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15371         << MemberDecl->getDeclName()
15372         << SourceRange(BuiltinLoc, RParenLoc);
15373       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15374       return ExprError();
15375     }
15376 
15377     RecordDecl *Parent = MemberDecl->getParent();
15378     if (IndirectMemberDecl)
15379       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15380 
15381     // If the member was found in a base class, introduce OffsetOfNodes for
15382     // the base class indirections.
15383     CXXBasePaths Paths;
15384     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15385                       Paths)) {
15386       if (Paths.getDetectedVirtual()) {
15387         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15388           << MemberDecl->getDeclName()
15389           << SourceRange(BuiltinLoc, RParenLoc);
15390         return ExprError();
15391       }
15392 
15393       CXXBasePath &Path = Paths.front();
15394       for (const CXXBasePathElement &B : Path)
15395         Comps.push_back(OffsetOfNode(B.Base));
15396     }
15397 
15398     if (IndirectMemberDecl) {
15399       for (auto *FI : IndirectMemberDecl->chain()) {
15400         assert(isa<FieldDecl>(FI));
15401         Comps.push_back(OffsetOfNode(OC.LocStart,
15402                                      cast<FieldDecl>(FI), OC.LocEnd));
15403       }
15404     } else
15405       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15406 
15407     CurrentType = MemberDecl->getType().getNonReferenceType();
15408   }
15409 
15410   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15411                               Comps, Exprs, RParenLoc);
15412 }
15413 
15414 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15415                                       SourceLocation BuiltinLoc,
15416                                       SourceLocation TypeLoc,
15417                                       ParsedType ParsedArgTy,
15418                                       ArrayRef<OffsetOfComponent> Components,
15419                                       SourceLocation RParenLoc) {
15420 
15421   TypeSourceInfo *ArgTInfo;
15422   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15423   if (ArgTy.isNull())
15424     return ExprError();
15425 
15426   if (!ArgTInfo)
15427     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15428 
15429   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15430 }
15431 
15432 
15433 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15434                                  Expr *CondExpr,
15435                                  Expr *LHSExpr, Expr *RHSExpr,
15436                                  SourceLocation RPLoc) {
15437   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15438 
15439   ExprValueKind VK = VK_PRValue;
15440   ExprObjectKind OK = OK_Ordinary;
15441   QualType resType;
15442   bool CondIsTrue = false;
15443   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15444     resType = Context.DependentTy;
15445   } else {
15446     // The conditional expression is required to be a constant expression.
15447     llvm::APSInt condEval(32);
15448     ExprResult CondICE = VerifyIntegerConstantExpression(
15449         CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15450     if (CondICE.isInvalid())
15451       return ExprError();
15452     CondExpr = CondICE.get();
15453     CondIsTrue = condEval.getZExtValue();
15454 
15455     // If the condition is > zero, then the AST type is the same as the LHSExpr.
15456     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15457 
15458     resType = ActiveExpr->getType();
15459     VK = ActiveExpr->getValueKind();
15460     OK = ActiveExpr->getObjectKind();
15461   }
15462 
15463   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15464                                   resType, VK, OK, RPLoc, CondIsTrue);
15465 }
15466 
15467 //===----------------------------------------------------------------------===//
15468 // Clang Extensions.
15469 //===----------------------------------------------------------------------===//
15470 
15471 /// ActOnBlockStart - This callback is invoked when a block literal is started.
15472 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15473   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15474 
15475   if (LangOpts.CPlusPlus) {
15476     MangleNumberingContext *MCtx;
15477     Decl *ManglingContextDecl;
15478     std::tie(MCtx, ManglingContextDecl) =
15479         getCurrentMangleNumberContext(Block->getDeclContext());
15480     if (MCtx) {
15481       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15482       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15483     }
15484   }
15485 
15486   PushBlockScope(CurScope, Block);
15487   CurContext->addDecl(Block);
15488   if (CurScope)
15489     PushDeclContext(CurScope, Block);
15490   else
15491     CurContext = Block;
15492 
15493   getCurBlock()->HasImplicitReturnType = true;
15494 
15495   // Enter a new evaluation context to insulate the block from any
15496   // cleanups from the enclosing full-expression.
15497   PushExpressionEvaluationContext(
15498       ExpressionEvaluationContext::PotentiallyEvaluated);
15499 }
15500 
15501 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15502                                Scope *CurScope) {
15503   assert(ParamInfo.getIdentifier() == nullptr &&
15504          "block-id should have no identifier!");
15505   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15506   BlockScopeInfo *CurBlock = getCurBlock();
15507 
15508   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15509   QualType T = Sig->getType();
15510 
15511   // FIXME: We should allow unexpanded parameter packs here, but that would,
15512   // in turn, make the block expression contain unexpanded parameter packs.
15513   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15514     // Drop the parameters.
15515     FunctionProtoType::ExtProtoInfo EPI;
15516     EPI.HasTrailingReturn = false;
15517     EPI.TypeQuals.addConst();
15518     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15519     Sig = Context.getTrivialTypeSourceInfo(T);
15520   }
15521 
15522   // GetTypeForDeclarator always produces a function type for a block
15523   // literal signature.  Furthermore, it is always a FunctionProtoType
15524   // unless the function was written with a typedef.
15525   assert(T->isFunctionType() &&
15526          "GetTypeForDeclarator made a non-function block signature");
15527 
15528   // Look for an explicit signature in that function type.
15529   FunctionProtoTypeLoc ExplicitSignature;
15530 
15531   if ((ExplicitSignature = Sig->getTypeLoc()
15532                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15533 
15534     // Check whether that explicit signature was synthesized by
15535     // GetTypeForDeclarator.  If so, don't save that as part of the
15536     // written signature.
15537     if (ExplicitSignature.getLocalRangeBegin() ==
15538         ExplicitSignature.getLocalRangeEnd()) {
15539       // This would be much cheaper if we stored TypeLocs instead of
15540       // TypeSourceInfos.
15541       TypeLoc Result = ExplicitSignature.getReturnLoc();
15542       unsigned Size = Result.getFullDataSize();
15543       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15544       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15545 
15546       ExplicitSignature = FunctionProtoTypeLoc();
15547     }
15548   }
15549 
15550   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15551   CurBlock->FunctionType = T;
15552 
15553   const auto *Fn = T->castAs<FunctionType>();
15554   QualType RetTy = Fn->getReturnType();
15555   bool isVariadic =
15556       (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15557 
15558   CurBlock->TheDecl->setIsVariadic(isVariadic);
15559 
15560   // Context.DependentTy is used as a placeholder for a missing block
15561   // return type.  TODO:  what should we do with declarators like:
15562   //   ^ * { ... }
15563   // If the answer is "apply template argument deduction"....
15564   if (RetTy != Context.DependentTy) {
15565     CurBlock->ReturnType = RetTy;
15566     CurBlock->TheDecl->setBlockMissingReturnType(false);
15567     CurBlock->HasImplicitReturnType = false;
15568   }
15569 
15570   // Push block parameters from the declarator if we had them.
15571   SmallVector<ParmVarDecl*, 8> Params;
15572   if (ExplicitSignature) {
15573     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15574       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15575       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15576           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15577         // Diagnose this as an extension in C17 and earlier.
15578         if (!getLangOpts().C2x)
15579           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15580       }
15581       Params.push_back(Param);
15582     }
15583 
15584   // Fake up parameter variables if we have a typedef, like
15585   //   ^ fntype { ... }
15586   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15587     for (const auto &I : Fn->param_types()) {
15588       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15589           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15590       Params.push_back(Param);
15591     }
15592   }
15593 
15594   // Set the parameters on the block decl.
15595   if (!Params.empty()) {
15596     CurBlock->TheDecl->setParams(Params);
15597     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15598                              /*CheckParameterNames=*/false);
15599   }
15600 
15601   // Finally we can process decl attributes.
15602   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15603 
15604   // Put the parameter variables in scope.
15605   for (auto AI : CurBlock->TheDecl->parameters()) {
15606     AI->setOwningFunction(CurBlock->TheDecl);
15607 
15608     // If this has an identifier, add it to the scope stack.
15609     if (AI->getIdentifier()) {
15610       CheckShadow(CurBlock->TheScope, AI);
15611 
15612       PushOnScopeChains(AI, CurBlock->TheScope);
15613     }
15614   }
15615 }
15616 
15617 /// ActOnBlockError - If there is an error parsing a block, this callback
15618 /// is invoked to pop the information about the block from the action impl.
15619 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15620   // Leave the expression-evaluation context.
15621   DiscardCleanupsInEvaluationContext();
15622   PopExpressionEvaluationContext();
15623 
15624   // Pop off CurBlock, handle nested blocks.
15625   PopDeclContext();
15626   PopFunctionScopeInfo();
15627 }
15628 
15629 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15630 /// literal was successfully completed.  ^(int x){...}
15631 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15632                                     Stmt *Body, Scope *CurScope) {
15633   // If blocks are disabled, emit an error.
15634   if (!LangOpts.Blocks)
15635     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15636 
15637   // Leave the expression-evaluation context.
15638   if (hasAnyUnrecoverableErrorsInThisFunction())
15639     DiscardCleanupsInEvaluationContext();
15640   assert(!Cleanup.exprNeedsCleanups() &&
15641          "cleanups within block not correctly bound!");
15642   PopExpressionEvaluationContext();
15643 
15644   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15645   BlockDecl *BD = BSI->TheDecl;
15646 
15647   if (BSI->HasImplicitReturnType)
15648     deduceClosureReturnType(*BSI);
15649 
15650   QualType RetTy = Context.VoidTy;
15651   if (!BSI->ReturnType.isNull())
15652     RetTy = BSI->ReturnType;
15653 
15654   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15655   QualType BlockTy;
15656 
15657   // If the user wrote a function type in some form, try to use that.
15658   if (!BSI->FunctionType.isNull()) {
15659     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15660 
15661     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15662     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15663 
15664     // Turn protoless block types into nullary block types.
15665     if (isa<FunctionNoProtoType>(FTy)) {
15666       FunctionProtoType::ExtProtoInfo EPI;
15667       EPI.ExtInfo = Ext;
15668       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15669 
15670     // Otherwise, if we don't need to change anything about the function type,
15671     // preserve its sugar structure.
15672     } else if (FTy->getReturnType() == RetTy &&
15673                (!NoReturn || FTy->getNoReturnAttr())) {
15674       BlockTy = BSI->FunctionType;
15675 
15676     // Otherwise, make the minimal modifications to the function type.
15677     } else {
15678       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15679       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15680       EPI.TypeQuals = Qualifiers();
15681       EPI.ExtInfo = Ext;
15682       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15683     }
15684 
15685   // If we don't have a function type, just build one from nothing.
15686   } else {
15687     FunctionProtoType::ExtProtoInfo EPI;
15688     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15689     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15690   }
15691 
15692   DiagnoseUnusedParameters(BD->parameters());
15693   BlockTy = Context.getBlockPointerType(BlockTy);
15694 
15695   // If needed, diagnose invalid gotos and switches in the block.
15696   if (getCurFunction()->NeedsScopeChecking() &&
15697       !PP.isCodeCompletionEnabled())
15698     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15699 
15700   BD->setBody(cast<CompoundStmt>(Body));
15701 
15702   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15703     DiagnoseUnguardedAvailabilityViolations(BD);
15704 
15705   // Try to apply the named return value optimization. We have to check again
15706   // if we can do this, though, because blocks keep return statements around
15707   // to deduce an implicit return type.
15708   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15709       !BD->isDependentContext())
15710     computeNRVO(Body, BSI);
15711 
15712   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15713       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15714     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15715                           NTCUK_Destruct|NTCUK_Copy);
15716 
15717   PopDeclContext();
15718 
15719   // Set the captured variables on the block.
15720   SmallVector<BlockDecl::Capture, 4> Captures;
15721   for (Capture &Cap : BSI->Captures) {
15722     if (Cap.isInvalid() || Cap.isThisCapture())
15723       continue;
15724 
15725     VarDecl *Var = Cap.getVariable();
15726     Expr *CopyExpr = nullptr;
15727     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15728       if (const RecordType *Record =
15729               Cap.getCaptureType()->getAs<RecordType>()) {
15730         // The capture logic needs the destructor, so make sure we mark it.
15731         // Usually this is unnecessary because most local variables have
15732         // their destructors marked at declaration time, but parameters are
15733         // an exception because it's technically only the call site that
15734         // actually requires the destructor.
15735         if (isa<ParmVarDecl>(Var))
15736           FinalizeVarWithDestructor(Var, Record);
15737 
15738         // Enter a separate potentially-evaluated context while building block
15739         // initializers to isolate their cleanups from those of the block
15740         // itself.
15741         // FIXME: Is this appropriate even when the block itself occurs in an
15742         // unevaluated operand?
15743         EnterExpressionEvaluationContext EvalContext(
15744             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15745 
15746         SourceLocation Loc = Cap.getLocation();
15747 
15748         ExprResult Result = BuildDeclarationNameExpr(
15749             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15750 
15751         // According to the blocks spec, the capture of a variable from
15752         // the stack requires a const copy constructor.  This is not true
15753         // of the copy/move done to move a __block variable to the heap.
15754         if (!Result.isInvalid() &&
15755             !Result.get()->getType().isConstQualified()) {
15756           Result = ImpCastExprToType(Result.get(),
15757                                      Result.get()->getType().withConst(),
15758                                      CK_NoOp, VK_LValue);
15759         }
15760 
15761         if (!Result.isInvalid()) {
15762           Result = PerformCopyInitialization(
15763               InitializedEntity::InitializeBlock(Var->getLocation(),
15764                                                  Cap.getCaptureType()),
15765               Loc, Result.get());
15766         }
15767 
15768         // Build a full-expression copy expression if initialization
15769         // succeeded and used a non-trivial constructor.  Recover from
15770         // errors by pretending that the copy isn't necessary.
15771         if (!Result.isInvalid() &&
15772             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15773                 ->isTrivial()) {
15774           Result = MaybeCreateExprWithCleanups(Result);
15775           CopyExpr = Result.get();
15776         }
15777       }
15778     }
15779 
15780     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15781                               CopyExpr);
15782     Captures.push_back(NewCap);
15783   }
15784   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15785 
15786   // Pop the block scope now but keep it alive to the end of this function.
15787   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15788   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15789 
15790   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15791 
15792   // If the block isn't obviously global, i.e. it captures anything at
15793   // all, then we need to do a few things in the surrounding context:
15794   if (Result->getBlockDecl()->hasCaptures()) {
15795     // First, this expression has a new cleanup object.
15796     ExprCleanupObjects.push_back(Result->getBlockDecl());
15797     Cleanup.setExprNeedsCleanups(true);
15798 
15799     // It also gets a branch-protected scope if any of the captured
15800     // variables needs destruction.
15801     for (const auto &CI : Result->getBlockDecl()->captures()) {
15802       const VarDecl *var = CI.getVariable();
15803       if (var->getType().isDestructedType() != QualType::DK_none) {
15804         setFunctionHasBranchProtectedScope();
15805         break;
15806       }
15807     }
15808   }
15809 
15810   if (getCurFunction())
15811     getCurFunction()->addBlock(BD);
15812 
15813   return Result;
15814 }
15815 
15816 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15817                             SourceLocation RPLoc) {
15818   TypeSourceInfo *TInfo;
15819   GetTypeFromParser(Ty, &TInfo);
15820   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15821 }
15822 
15823 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15824                                 Expr *E, TypeSourceInfo *TInfo,
15825                                 SourceLocation RPLoc) {
15826   Expr *OrigExpr = E;
15827   bool IsMS = false;
15828 
15829   // CUDA device code does not support varargs.
15830   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15831     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15832       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15833       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15834         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15835     }
15836   }
15837 
15838   // NVPTX does not support va_arg expression.
15839   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15840       Context.getTargetInfo().getTriple().isNVPTX())
15841     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15842 
15843   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15844   // as Microsoft ABI on an actual Microsoft platform, where
15845   // __builtin_ms_va_list and __builtin_va_list are the same.)
15846   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15847       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15848     QualType MSVaListType = Context.getBuiltinMSVaListType();
15849     if (Context.hasSameType(MSVaListType, E->getType())) {
15850       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15851         return ExprError();
15852       IsMS = true;
15853     }
15854   }
15855 
15856   // Get the va_list type
15857   QualType VaListType = Context.getBuiltinVaListType();
15858   if (!IsMS) {
15859     if (VaListType->isArrayType()) {
15860       // Deal with implicit array decay; for example, on x86-64,
15861       // va_list is an array, but it's supposed to decay to
15862       // a pointer for va_arg.
15863       VaListType = Context.getArrayDecayedType(VaListType);
15864       // Make sure the input expression also decays appropriately.
15865       ExprResult Result = UsualUnaryConversions(E);
15866       if (Result.isInvalid())
15867         return ExprError();
15868       E = Result.get();
15869     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15870       // If va_list is a record type and we are compiling in C++ mode,
15871       // check the argument using reference binding.
15872       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15873           Context, Context.getLValueReferenceType(VaListType), false);
15874       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15875       if (Init.isInvalid())
15876         return ExprError();
15877       E = Init.getAs<Expr>();
15878     } else {
15879       // Otherwise, the va_list argument must be an l-value because
15880       // it is modified by va_arg.
15881       if (!E->isTypeDependent() &&
15882           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15883         return ExprError();
15884     }
15885   }
15886 
15887   if (!IsMS && !E->isTypeDependent() &&
15888       !Context.hasSameType(VaListType, E->getType()))
15889     return ExprError(
15890         Diag(E->getBeginLoc(),
15891              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15892         << OrigExpr->getType() << E->getSourceRange());
15893 
15894   if (!TInfo->getType()->isDependentType()) {
15895     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15896                             diag::err_second_parameter_to_va_arg_incomplete,
15897                             TInfo->getTypeLoc()))
15898       return ExprError();
15899 
15900     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15901                                TInfo->getType(),
15902                                diag::err_second_parameter_to_va_arg_abstract,
15903                                TInfo->getTypeLoc()))
15904       return ExprError();
15905 
15906     if (!TInfo->getType().isPODType(Context)) {
15907       Diag(TInfo->getTypeLoc().getBeginLoc(),
15908            TInfo->getType()->isObjCLifetimeType()
15909              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15910              : diag::warn_second_parameter_to_va_arg_not_pod)
15911         << TInfo->getType()
15912         << TInfo->getTypeLoc().getSourceRange();
15913     }
15914 
15915     // Check for va_arg where arguments of the given type will be promoted
15916     // (i.e. this va_arg is guaranteed to have undefined behavior).
15917     QualType PromoteType;
15918     if (TInfo->getType()->isPromotableIntegerType()) {
15919       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15920       // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
15921       // and C2x 7.16.1.1p2 says, in part:
15922       //   If type is not compatible with the type of the actual next argument
15923       //   (as promoted according to the default argument promotions), the
15924       //   behavior is undefined, except for the following cases:
15925       //     - both types are pointers to qualified or unqualified versions of
15926       //       compatible types;
15927       //     - one type is a signed integer type, the other type is the
15928       //       corresponding unsigned integer type, and the value is
15929       //       representable in both types;
15930       //     - one type is pointer to qualified or unqualified void and the
15931       //       other is a pointer to a qualified or unqualified character type.
15932       // Given that type compatibility is the primary requirement (ignoring
15933       // qualifications), you would think we could call typesAreCompatible()
15934       // directly to test this. However, in C++, that checks for *same type*,
15935       // which causes false positives when passing an enumeration type to
15936       // va_arg. Instead, get the underlying type of the enumeration and pass
15937       // that.
15938       QualType UnderlyingType = TInfo->getType();
15939       if (const auto *ET = UnderlyingType->getAs<EnumType>())
15940         UnderlyingType = ET->getDecl()->getIntegerType();
15941       if (Context.typesAreCompatible(PromoteType, UnderlyingType,
15942                                      /*CompareUnqualified*/ true))
15943         PromoteType = QualType();
15944 
15945       // If the types are still not compatible, we need to test whether the
15946       // promoted type and the underlying type are the same except for
15947       // signedness. Ask the AST for the correctly corresponding type and see
15948       // if that's compatible.
15949       if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
15950           PromoteType->isUnsignedIntegerType() !=
15951               UnderlyingType->isUnsignedIntegerType()) {
15952         UnderlyingType =
15953             UnderlyingType->isUnsignedIntegerType()
15954                 ? Context.getCorrespondingSignedType(UnderlyingType)
15955                 : Context.getCorrespondingUnsignedType(UnderlyingType);
15956         if (Context.typesAreCompatible(PromoteType, UnderlyingType,
15957                                        /*CompareUnqualified*/ true))
15958           PromoteType = QualType();
15959       }
15960     }
15961     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15962       PromoteType = Context.DoubleTy;
15963     if (!PromoteType.isNull())
15964       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15965                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15966                           << TInfo->getType()
15967                           << PromoteType
15968                           << TInfo->getTypeLoc().getSourceRange());
15969   }
15970 
15971   QualType T = TInfo->getType().getNonLValueExprType(Context);
15972   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15973 }
15974 
15975 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15976   // The type of __null will be int or long, depending on the size of
15977   // pointers on the target.
15978   QualType Ty;
15979   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15980   if (pw == Context.getTargetInfo().getIntWidth())
15981     Ty = Context.IntTy;
15982   else if (pw == Context.getTargetInfo().getLongWidth())
15983     Ty = Context.LongTy;
15984   else if (pw == Context.getTargetInfo().getLongLongWidth())
15985     Ty = Context.LongLongTy;
15986   else {
15987     llvm_unreachable("I don't know size of pointer!");
15988   }
15989 
15990   return new (Context) GNUNullExpr(Ty, TokenLoc);
15991 }
15992 
15993 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15994                                     SourceLocation BuiltinLoc,
15995                                     SourceLocation RPLoc) {
15996   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15997 }
15998 
15999 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
16000                                     SourceLocation BuiltinLoc,
16001                                     SourceLocation RPLoc,
16002                                     DeclContext *ParentContext) {
16003   return new (Context)
16004       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
16005 }
16006 
16007 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
16008                                         bool Diagnose) {
16009   if (!getLangOpts().ObjC)
16010     return false;
16011 
16012   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
16013   if (!PT)
16014     return false;
16015   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
16016 
16017   // Ignore any parens, implicit casts (should only be
16018   // array-to-pointer decays), and not-so-opaque values.  The last is
16019   // important for making this trigger for property assignments.
16020   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
16021   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
16022     if (OV->getSourceExpr())
16023       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
16024 
16025   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
16026     if (!PT->isObjCIdType() &&
16027         !(ID && ID->getIdentifier()->isStr("NSString")))
16028       return false;
16029     if (!SL->isAscii())
16030       return false;
16031 
16032     if (Diagnose) {
16033       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
16034           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
16035       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
16036     }
16037     return true;
16038   }
16039 
16040   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
16041       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
16042       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
16043       !SrcExpr->isNullPointerConstant(
16044           getASTContext(), Expr::NPC_NeverValueDependent)) {
16045     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
16046       return false;
16047     if (Diagnose) {
16048       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
16049           << /*number*/1
16050           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
16051       Expr *NumLit =
16052           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
16053       if (NumLit)
16054         Exp = NumLit;
16055     }
16056     return true;
16057   }
16058 
16059   return false;
16060 }
16061 
16062 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
16063                                               const Expr *SrcExpr) {
16064   if (!DstType->isFunctionPointerType() ||
16065       !SrcExpr->getType()->isFunctionType())
16066     return false;
16067 
16068   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16069   if (!DRE)
16070     return false;
16071 
16072   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16073   if (!FD)
16074     return false;
16075 
16076   return !S.checkAddressOfFunctionIsAvailable(FD,
16077                                               /*Complain=*/true,
16078                                               SrcExpr->getBeginLoc());
16079 }
16080 
16081 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16082                                     SourceLocation Loc,
16083                                     QualType DstType, QualType SrcType,
16084                                     Expr *SrcExpr, AssignmentAction Action,
16085                                     bool *Complained) {
16086   if (Complained)
16087     *Complained = false;
16088 
16089   // Decode the result (notice that AST's are still created for extensions).
16090   bool CheckInferredResultType = false;
16091   bool isInvalid = false;
16092   unsigned DiagKind = 0;
16093   ConversionFixItGenerator ConvHints;
16094   bool MayHaveConvFixit = false;
16095   bool MayHaveFunctionDiff = false;
16096   const ObjCInterfaceDecl *IFace = nullptr;
16097   const ObjCProtocolDecl *PDecl = nullptr;
16098 
16099   switch (ConvTy) {
16100   case Compatible:
16101       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16102       return false;
16103 
16104   case PointerToInt:
16105     if (getLangOpts().CPlusPlus) {
16106       DiagKind = diag::err_typecheck_convert_pointer_int;
16107       isInvalid = true;
16108     } else {
16109       DiagKind = diag::ext_typecheck_convert_pointer_int;
16110     }
16111     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16112     MayHaveConvFixit = true;
16113     break;
16114   case IntToPointer:
16115     if (getLangOpts().CPlusPlus) {
16116       DiagKind = diag::err_typecheck_convert_int_pointer;
16117       isInvalid = true;
16118     } else {
16119       DiagKind = diag::ext_typecheck_convert_int_pointer;
16120     }
16121     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16122     MayHaveConvFixit = true;
16123     break;
16124   case IncompatibleFunctionPointer:
16125     if (getLangOpts().CPlusPlus) {
16126       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16127       isInvalid = true;
16128     } else {
16129       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16130     }
16131     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16132     MayHaveConvFixit = true;
16133     break;
16134   case IncompatiblePointer:
16135     if (Action == AA_Passing_CFAudited) {
16136       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16137     } else if (getLangOpts().CPlusPlus) {
16138       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16139       isInvalid = true;
16140     } else {
16141       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16142     }
16143     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16144       SrcType->isObjCObjectPointerType();
16145     if (!CheckInferredResultType) {
16146       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16147     } else if (CheckInferredResultType) {
16148       SrcType = SrcType.getUnqualifiedType();
16149       DstType = DstType.getUnqualifiedType();
16150     }
16151     MayHaveConvFixit = true;
16152     break;
16153   case IncompatiblePointerSign:
16154     if (getLangOpts().CPlusPlus) {
16155       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16156       isInvalid = true;
16157     } else {
16158       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16159     }
16160     break;
16161   case FunctionVoidPointer:
16162     if (getLangOpts().CPlusPlus) {
16163       DiagKind = diag::err_typecheck_convert_pointer_void_func;
16164       isInvalid = true;
16165     } else {
16166       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16167     }
16168     break;
16169   case IncompatiblePointerDiscardsQualifiers: {
16170     // Perform array-to-pointer decay if necessary.
16171     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16172 
16173     isInvalid = true;
16174 
16175     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16176     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16177     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16178       DiagKind = diag::err_typecheck_incompatible_address_space;
16179       break;
16180 
16181     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16182       DiagKind = diag::err_typecheck_incompatible_ownership;
16183       break;
16184     }
16185 
16186     llvm_unreachable("unknown error case for discarding qualifiers!");
16187     // fallthrough
16188   }
16189   case CompatiblePointerDiscardsQualifiers:
16190     // If the qualifiers lost were because we were applying the
16191     // (deprecated) C++ conversion from a string literal to a char*
16192     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
16193     // Ideally, this check would be performed in
16194     // checkPointerTypesForAssignment. However, that would require a
16195     // bit of refactoring (so that the second argument is an
16196     // expression, rather than a type), which should be done as part
16197     // of a larger effort to fix checkPointerTypesForAssignment for
16198     // C++ semantics.
16199     if (getLangOpts().CPlusPlus &&
16200         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16201       return false;
16202     if (getLangOpts().CPlusPlus) {
16203       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
16204       isInvalid = true;
16205     } else {
16206       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
16207     }
16208 
16209     break;
16210   case IncompatibleNestedPointerQualifiers:
16211     if (getLangOpts().CPlusPlus) {
16212       isInvalid = true;
16213       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16214     } else {
16215       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16216     }
16217     break;
16218   case IncompatibleNestedPointerAddressSpaceMismatch:
16219     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16220     isInvalid = true;
16221     break;
16222   case IntToBlockPointer:
16223     DiagKind = diag::err_int_to_block_pointer;
16224     isInvalid = true;
16225     break;
16226   case IncompatibleBlockPointer:
16227     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16228     isInvalid = true;
16229     break;
16230   case IncompatibleObjCQualifiedId: {
16231     if (SrcType->isObjCQualifiedIdType()) {
16232       const ObjCObjectPointerType *srcOPT =
16233                 SrcType->castAs<ObjCObjectPointerType>();
16234       for (auto *srcProto : srcOPT->quals()) {
16235         PDecl = srcProto;
16236         break;
16237       }
16238       if (const ObjCInterfaceType *IFaceT =
16239             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16240         IFace = IFaceT->getDecl();
16241     }
16242     else if (DstType->isObjCQualifiedIdType()) {
16243       const ObjCObjectPointerType *dstOPT =
16244         DstType->castAs<ObjCObjectPointerType>();
16245       for (auto *dstProto : dstOPT->quals()) {
16246         PDecl = dstProto;
16247         break;
16248       }
16249       if (const ObjCInterfaceType *IFaceT =
16250             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16251         IFace = IFaceT->getDecl();
16252     }
16253     if (getLangOpts().CPlusPlus) {
16254       DiagKind = diag::err_incompatible_qualified_id;
16255       isInvalid = true;
16256     } else {
16257       DiagKind = diag::warn_incompatible_qualified_id;
16258     }
16259     break;
16260   }
16261   case IncompatibleVectors:
16262     if (getLangOpts().CPlusPlus) {
16263       DiagKind = diag::err_incompatible_vectors;
16264       isInvalid = true;
16265     } else {
16266       DiagKind = diag::warn_incompatible_vectors;
16267     }
16268     break;
16269   case IncompatibleObjCWeakRef:
16270     DiagKind = diag::err_arc_weak_unavailable_assign;
16271     isInvalid = true;
16272     break;
16273   case Incompatible:
16274     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16275       if (Complained)
16276         *Complained = true;
16277       return true;
16278     }
16279 
16280     DiagKind = diag::err_typecheck_convert_incompatible;
16281     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16282     MayHaveConvFixit = true;
16283     isInvalid = true;
16284     MayHaveFunctionDiff = true;
16285     break;
16286   }
16287 
16288   QualType FirstType, SecondType;
16289   switch (Action) {
16290   case AA_Assigning:
16291   case AA_Initializing:
16292     // The destination type comes first.
16293     FirstType = DstType;
16294     SecondType = SrcType;
16295     break;
16296 
16297   case AA_Returning:
16298   case AA_Passing:
16299   case AA_Passing_CFAudited:
16300   case AA_Converting:
16301   case AA_Sending:
16302   case AA_Casting:
16303     // The source type comes first.
16304     FirstType = SrcType;
16305     SecondType = DstType;
16306     break;
16307   }
16308 
16309   PartialDiagnostic FDiag = PDiag(DiagKind);
16310   if (Action == AA_Passing_CFAudited)
16311     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
16312   else
16313     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
16314 
16315   if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16316       DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16317     auto isPlainChar = [](const clang::Type *Type) {
16318       return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16319              Type->isSpecificBuiltinType(BuiltinType::Char_U);
16320     };
16321     FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16322               isPlainChar(SecondType->getPointeeOrArrayElementType()));
16323   }
16324 
16325   // If we can fix the conversion, suggest the FixIts.
16326   if (!ConvHints.isNull()) {
16327     for (FixItHint &H : ConvHints.Hints)
16328       FDiag << H;
16329   }
16330 
16331   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16332 
16333   if (MayHaveFunctionDiff)
16334     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16335 
16336   Diag(Loc, FDiag);
16337   if ((DiagKind == diag::warn_incompatible_qualified_id ||
16338        DiagKind == diag::err_incompatible_qualified_id) &&
16339       PDecl && IFace && !IFace->hasDefinition())
16340     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16341         << IFace << PDecl;
16342 
16343   if (SecondType == Context.OverloadTy)
16344     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16345                               FirstType, /*TakingAddress=*/true);
16346 
16347   if (CheckInferredResultType)
16348     EmitRelatedResultTypeNote(SrcExpr);
16349 
16350   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16351     EmitRelatedResultTypeNoteForReturn(DstType);
16352 
16353   if (Complained)
16354     *Complained = true;
16355   return isInvalid;
16356 }
16357 
16358 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16359                                                  llvm::APSInt *Result,
16360                                                  AllowFoldKind CanFold) {
16361   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16362   public:
16363     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16364                                              QualType T) override {
16365       return S.Diag(Loc, diag::err_ice_not_integral)
16366              << T << S.LangOpts.CPlusPlus;
16367     }
16368     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16369       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16370     }
16371   } Diagnoser;
16372 
16373   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16374 }
16375 
16376 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16377                                                  llvm::APSInt *Result,
16378                                                  unsigned DiagID,
16379                                                  AllowFoldKind CanFold) {
16380   class IDDiagnoser : public VerifyICEDiagnoser {
16381     unsigned DiagID;
16382 
16383   public:
16384     IDDiagnoser(unsigned DiagID)
16385       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16386 
16387     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16388       return S.Diag(Loc, DiagID);
16389     }
16390   } Diagnoser(DiagID);
16391 
16392   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16393 }
16394 
16395 Sema::SemaDiagnosticBuilder
16396 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
16397                                              QualType T) {
16398   return diagnoseNotICE(S, Loc);
16399 }
16400 
16401 Sema::SemaDiagnosticBuilder
16402 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
16403   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16404 }
16405 
16406 ExprResult
16407 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16408                                       VerifyICEDiagnoser &Diagnoser,
16409                                       AllowFoldKind CanFold) {
16410   SourceLocation DiagLoc = E->getBeginLoc();
16411 
16412   if (getLangOpts().CPlusPlus11) {
16413     // C++11 [expr.const]p5:
16414     //   If an expression of literal class type is used in a context where an
16415     //   integral constant expression is required, then that class type shall
16416     //   have a single non-explicit conversion function to an integral or
16417     //   unscoped enumeration type
16418     ExprResult Converted;
16419     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16420       VerifyICEDiagnoser &BaseDiagnoser;
16421     public:
16422       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16423           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16424                                 BaseDiagnoser.Suppress, true),
16425             BaseDiagnoser(BaseDiagnoser) {}
16426 
16427       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16428                                            QualType T) override {
16429         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16430       }
16431 
16432       SemaDiagnosticBuilder diagnoseIncomplete(
16433           Sema &S, SourceLocation Loc, QualType T) override {
16434         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16435       }
16436 
16437       SemaDiagnosticBuilder diagnoseExplicitConv(
16438           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16439         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16440       }
16441 
16442       SemaDiagnosticBuilder noteExplicitConv(
16443           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16444         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16445                  << ConvTy->isEnumeralType() << ConvTy;
16446       }
16447 
16448       SemaDiagnosticBuilder diagnoseAmbiguous(
16449           Sema &S, SourceLocation Loc, QualType T) override {
16450         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16451       }
16452 
16453       SemaDiagnosticBuilder noteAmbiguous(
16454           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16455         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16456                  << ConvTy->isEnumeralType() << ConvTy;
16457       }
16458 
16459       SemaDiagnosticBuilder diagnoseConversion(
16460           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16461         llvm_unreachable("conversion functions are permitted");
16462       }
16463     } ConvertDiagnoser(Diagnoser);
16464 
16465     Converted = PerformContextualImplicitConversion(DiagLoc, E,
16466                                                     ConvertDiagnoser);
16467     if (Converted.isInvalid())
16468       return Converted;
16469     E = Converted.get();
16470     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16471       return ExprError();
16472   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16473     // An ICE must be of integral or unscoped enumeration type.
16474     if (!Diagnoser.Suppress)
16475       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16476           << E->getSourceRange();
16477     return ExprError();
16478   }
16479 
16480   ExprResult RValueExpr = DefaultLvalueConversion(E);
16481   if (RValueExpr.isInvalid())
16482     return ExprError();
16483 
16484   E = RValueExpr.get();
16485 
16486   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16487   // in the non-ICE case.
16488   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16489     if (Result)
16490       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16491     if (!isa<ConstantExpr>(E))
16492       E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
16493                  : ConstantExpr::Create(Context, E);
16494     return E;
16495   }
16496 
16497   Expr::EvalResult EvalResult;
16498   SmallVector<PartialDiagnosticAt, 8> Notes;
16499   EvalResult.Diag = &Notes;
16500 
16501   // Try to evaluate the expression, and produce diagnostics explaining why it's
16502   // not a constant expression as a side-effect.
16503   bool Folded =
16504       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16505       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16506 
16507   if (!isa<ConstantExpr>(E))
16508     E = ConstantExpr::Create(Context, E, EvalResult.Val);
16509 
16510   // In C++11, we can rely on diagnostics being produced for any expression
16511   // which is not a constant expression. If no diagnostics were produced, then
16512   // this is a constant expression.
16513   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16514     if (Result)
16515       *Result = EvalResult.Val.getInt();
16516     return E;
16517   }
16518 
16519   // If our only note is the usual "invalid subexpression" note, just point
16520   // the caret at its location rather than producing an essentially
16521   // redundant note.
16522   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16523         diag::note_invalid_subexpr_in_const_expr) {
16524     DiagLoc = Notes[0].first;
16525     Notes.clear();
16526   }
16527 
16528   if (!Folded || !CanFold) {
16529     if (!Diagnoser.Suppress) {
16530       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16531       for (const PartialDiagnosticAt &Note : Notes)
16532         Diag(Note.first, Note.second);
16533     }
16534 
16535     return ExprError();
16536   }
16537 
16538   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16539   for (const PartialDiagnosticAt &Note : Notes)
16540     Diag(Note.first, Note.second);
16541 
16542   if (Result)
16543     *Result = EvalResult.Val.getInt();
16544   return E;
16545 }
16546 
16547 namespace {
16548   // Handle the case where we conclude a expression which we speculatively
16549   // considered to be unevaluated is actually evaluated.
16550   class TransformToPE : public TreeTransform<TransformToPE> {
16551     typedef TreeTransform<TransformToPE> BaseTransform;
16552 
16553   public:
16554     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16555 
16556     // Make sure we redo semantic analysis
16557     bool AlwaysRebuild() { return true; }
16558     bool ReplacingOriginal() { return true; }
16559 
16560     // We need to special-case DeclRefExprs referring to FieldDecls which
16561     // are not part of a member pointer formation; normal TreeTransforming
16562     // doesn't catch this case because of the way we represent them in the AST.
16563     // FIXME: This is a bit ugly; is it really the best way to handle this
16564     // case?
16565     //
16566     // Error on DeclRefExprs referring to FieldDecls.
16567     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16568       if (isa<FieldDecl>(E->getDecl()) &&
16569           !SemaRef.isUnevaluatedContext())
16570         return SemaRef.Diag(E->getLocation(),
16571                             diag::err_invalid_non_static_member_use)
16572             << E->getDecl() << E->getSourceRange();
16573 
16574       return BaseTransform::TransformDeclRefExpr(E);
16575     }
16576 
16577     // Exception: filter out member pointer formation
16578     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16579       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16580         return E;
16581 
16582       return BaseTransform::TransformUnaryOperator(E);
16583     }
16584 
16585     // The body of a lambda-expression is in a separate expression evaluation
16586     // context so never needs to be transformed.
16587     // FIXME: Ideally we wouldn't transform the closure type either, and would
16588     // just recreate the capture expressions and lambda expression.
16589     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16590       return SkipLambdaBody(E, Body);
16591     }
16592   };
16593 }
16594 
16595 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16596   assert(isUnevaluatedContext() &&
16597          "Should only transform unevaluated expressions");
16598   ExprEvalContexts.back().Context =
16599       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16600   if (isUnevaluatedContext())
16601     return E;
16602   return TransformToPE(*this).TransformExpr(E);
16603 }
16604 
16605 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
16606   assert(isUnevaluatedContext() &&
16607          "Should only transform unevaluated expressions");
16608   ExprEvalContexts.back().Context =
16609       ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
16610   if (isUnevaluatedContext())
16611     return TInfo;
16612   return TransformToPE(*this).TransformType(TInfo);
16613 }
16614 
16615 void
16616 Sema::PushExpressionEvaluationContext(
16617     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16618     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16619   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16620                                 LambdaContextDecl, ExprContext);
16621 
16622   // Discarded statements and immediate contexts nested in other
16623   // discarded statements or immediate context are themselves
16624   // a discarded statement or an immediate context, respectively.
16625   ExprEvalContexts.back().InDiscardedStatement =
16626       ExprEvalContexts[ExprEvalContexts.size() - 2]
16627           .isDiscardedStatementContext();
16628   ExprEvalContexts.back().InImmediateFunctionContext =
16629       ExprEvalContexts[ExprEvalContexts.size() - 2]
16630           .isImmediateFunctionContext();
16631 
16632   Cleanup.reset();
16633   if (!MaybeODRUseExprs.empty())
16634     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16635 }
16636 
16637 void
16638 Sema::PushExpressionEvaluationContext(
16639     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16640     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16641   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16642   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16643 }
16644 
16645 namespace {
16646 
16647 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16648   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16649   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16650     if (E->getOpcode() == UO_Deref)
16651       return CheckPossibleDeref(S, E->getSubExpr());
16652   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16653     return CheckPossibleDeref(S, E->getBase());
16654   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16655     return CheckPossibleDeref(S, E->getBase());
16656   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16657     QualType Inner;
16658     QualType Ty = E->getType();
16659     if (const auto *Ptr = Ty->getAs<PointerType>())
16660       Inner = Ptr->getPointeeType();
16661     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16662       Inner = Arr->getElementType();
16663     else
16664       return nullptr;
16665 
16666     if (Inner->hasAttr(attr::NoDeref))
16667       return E;
16668   }
16669   return nullptr;
16670 }
16671 
16672 } // namespace
16673 
16674 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16675   for (const Expr *E : Rec.PossibleDerefs) {
16676     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16677     if (DeclRef) {
16678       const ValueDecl *Decl = DeclRef->getDecl();
16679       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16680           << Decl->getName() << E->getSourceRange();
16681       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16682     } else {
16683       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16684           << E->getSourceRange();
16685     }
16686   }
16687   Rec.PossibleDerefs.clear();
16688 }
16689 
16690 /// Check whether E, which is either a discarded-value expression or an
16691 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16692 /// and if so, remove it from the list of volatile-qualified assignments that
16693 /// we are going to warn are deprecated.
16694 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16695   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16696     return;
16697 
16698   // Note: ignoring parens here is not justified by the standard rules, but
16699   // ignoring parentheses seems like a more reasonable approach, and this only
16700   // drives a deprecation warning so doesn't affect conformance.
16701   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16702     if (BO->getOpcode() == BO_Assign) {
16703       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16704       llvm::erase_value(LHSs, BO->getLHS());
16705     }
16706   }
16707 }
16708 
16709 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16710   if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
16711       !Decl->isConsteval() || isConstantEvaluated() ||
16712       RebuildingImmediateInvocation || isImmediateFunctionContext())
16713     return E;
16714 
16715   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16716   /// It's OK if this fails; we'll also remove this in
16717   /// HandleImmediateInvocations, but catching it here allows us to avoid
16718   /// walking the AST looking for it in simple cases.
16719   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16720     if (auto *DeclRef =
16721             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16722       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16723 
16724   E = MaybeCreateExprWithCleanups(E);
16725 
16726   ConstantExpr *Res = ConstantExpr::Create(
16727       getASTContext(), E.get(),
16728       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16729                                    getASTContext()),
16730       /*IsImmediateInvocation*/ true);
16731   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16732   return Res;
16733 }
16734 
16735 static void EvaluateAndDiagnoseImmediateInvocation(
16736     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16737   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16738   Expr::EvalResult Eval;
16739   Eval.Diag = &Notes;
16740   ConstantExpr *CE = Candidate.getPointer();
16741   bool Result = CE->EvaluateAsConstantExpr(
16742       Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
16743   if (!Result || !Notes.empty()) {
16744     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16745     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16746       InnerExpr = FunctionalCast->getSubExpr();
16747     FunctionDecl *FD = nullptr;
16748     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16749       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16750     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16751       FD = Call->getConstructor();
16752     else
16753       llvm_unreachable("unhandled decl kind");
16754     assert(FD->isConsteval());
16755     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16756     for (auto &Note : Notes)
16757       SemaRef.Diag(Note.first, Note.second);
16758     return;
16759   }
16760   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16761 }
16762 
16763 static void RemoveNestedImmediateInvocation(
16764     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16765     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16766   struct ComplexRemove : TreeTransform<ComplexRemove> {
16767     using Base = TreeTransform<ComplexRemove>;
16768     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16769     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16770     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16771         CurrentII;
16772     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16773                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16774                   SmallVector<Sema::ImmediateInvocationCandidate,
16775                               4>::reverse_iterator Current)
16776         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16777     void RemoveImmediateInvocation(ConstantExpr* E) {
16778       auto It = std::find_if(CurrentII, IISet.rend(),
16779                              [E](Sema::ImmediateInvocationCandidate Elem) {
16780                                return Elem.getPointer() == E;
16781                              });
16782       assert(It != IISet.rend() &&
16783              "ConstantExpr marked IsImmediateInvocation should "
16784              "be present");
16785       It->setInt(1); // Mark as deleted
16786     }
16787     ExprResult TransformConstantExpr(ConstantExpr *E) {
16788       if (!E->isImmediateInvocation())
16789         return Base::TransformConstantExpr(E);
16790       RemoveImmediateInvocation(E);
16791       return Base::TransformExpr(E->getSubExpr());
16792     }
16793     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16794     /// we need to remove its DeclRefExpr from the DRSet.
16795     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16796       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16797       return Base::TransformCXXOperatorCallExpr(E);
16798     }
16799     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16800     /// here.
16801     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16802       if (!Init)
16803         return Init;
16804       /// ConstantExpr are the first layer of implicit node to be removed so if
16805       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16806       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16807         if (CE->isImmediateInvocation())
16808           RemoveImmediateInvocation(CE);
16809       return Base::TransformInitializer(Init, NotCopyInit);
16810     }
16811     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16812       DRSet.erase(E);
16813       return E;
16814     }
16815     bool AlwaysRebuild() { return false; }
16816     bool ReplacingOriginal() { return true; }
16817     bool AllowSkippingCXXConstructExpr() {
16818       bool Res = AllowSkippingFirstCXXConstructExpr;
16819       AllowSkippingFirstCXXConstructExpr = true;
16820       return Res;
16821     }
16822     bool AllowSkippingFirstCXXConstructExpr = true;
16823   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16824                 Rec.ImmediateInvocationCandidates, It);
16825 
16826   /// CXXConstructExpr with a single argument are getting skipped by
16827   /// TreeTransform in some situtation because they could be implicit. This
16828   /// can only occur for the top-level CXXConstructExpr because it is used
16829   /// nowhere in the expression being transformed therefore will not be rebuilt.
16830   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16831   /// skipping the first CXXConstructExpr.
16832   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16833     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16834 
16835   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16836   assert(Res.isUsable());
16837   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16838   It->getPointer()->setSubExpr(Res.get());
16839 }
16840 
16841 static void
16842 HandleImmediateInvocations(Sema &SemaRef,
16843                            Sema::ExpressionEvaluationContextRecord &Rec) {
16844   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16845        Rec.ReferenceToConsteval.size() == 0) ||
16846       SemaRef.RebuildingImmediateInvocation)
16847     return;
16848 
16849   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16850   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16851   /// need to remove ReferenceToConsteval in the immediate invocation.
16852   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16853 
16854     /// Prevent sema calls during the tree transform from adding pointers that
16855     /// are already in the sets.
16856     llvm::SaveAndRestore<bool> DisableIITracking(
16857         SemaRef.RebuildingImmediateInvocation, true);
16858 
16859     /// Prevent diagnostic during tree transfrom as they are duplicates
16860     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16861 
16862     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16863          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16864       if (!It->getInt())
16865         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16866   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16867              Rec.ReferenceToConsteval.size()) {
16868     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16869       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16870       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16871       bool VisitDeclRefExpr(DeclRefExpr *E) {
16872         DRSet.erase(E);
16873         return DRSet.size();
16874       }
16875     } Visitor(Rec.ReferenceToConsteval);
16876     Visitor.TraverseStmt(
16877         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16878   }
16879   for (auto CE : Rec.ImmediateInvocationCandidates)
16880     if (!CE.getInt())
16881       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16882   for (auto DR : Rec.ReferenceToConsteval) {
16883     auto *FD = cast<FunctionDecl>(DR->getDecl());
16884     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16885         << FD;
16886     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16887   }
16888 }
16889 
16890 void Sema::PopExpressionEvaluationContext() {
16891   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16892   unsigned NumTypos = Rec.NumTypos;
16893 
16894   if (!Rec.Lambdas.empty()) {
16895     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16896     if (!getLangOpts().CPlusPlus20 &&
16897         (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
16898          Rec.isUnevaluated() ||
16899          (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
16900       unsigned D;
16901       if (Rec.isUnevaluated()) {
16902         // C++11 [expr.prim.lambda]p2:
16903         //   A lambda-expression shall not appear in an unevaluated operand
16904         //   (Clause 5).
16905         D = diag::err_lambda_unevaluated_operand;
16906       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16907         // C++1y [expr.const]p2:
16908         //   A conditional-expression e is a core constant expression unless the
16909         //   evaluation of e, following the rules of the abstract machine, would
16910         //   evaluate [...] a lambda-expression.
16911         D = diag::err_lambda_in_constant_expression;
16912       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16913         // C++17 [expr.prim.lamda]p2:
16914         // A lambda-expression shall not appear [...] in a template-argument.
16915         D = diag::err_lambda_in_invalid_context;
16916       } else
16917         llvm_unreachable("Couldn't infer lambda error message.");
16918 
16919       for (const auto *L : Rec.Lambdas)
16920         Diag(L->getBeginLoc(), D);
16921     }
16922   }
16923 
16924   WarnOnPendingNoDerefs(Rec);
16925   HandleImmediateInvocations(*this, Rec);
16926 
16927   // Warn on any volatile-qualified simple-assignments that are not discarded-
16928   // value expressions nor unevaluated operands (those cases get removed from
16929   // this list by CheckUnusedVolatileAssignment).
16930   for (auto *BO : Rec.VolatileAssignmentLHSs)
16931     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16932         << BO->getType();
16933 
16934   // When are coming out of an unevaluated context, clear out any
16935   // temporaries that we may have created as part of the evaluation of
16936   // the expression in that context: they aren't relevant because they
16937   // will never be constructed.
16938   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16939     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16940                              ExprCleanupObjects.end());
16941     Cleanup = Rec.ParentCleanup;
16942     CleanupVarDeclMarking();
16943     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16944   // Otherwise, merge the contexts together.
16945   } else {
16946     Cleanup.mergeFrom(Rec.ParentCleanup);
16947     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16948                             Rec.SavedMaybeODRUseExprs.end());
16949   }
16950 
16951   // Pop the current expression evaluation context off the stack.
16952   ExprEvalContexts.pop_back();
16953 
16954   // The global expression evaluation context record is never popped.
16955   ExprEvalContexts.back().NumTypos += NumTypos;
16956 }
16957 
16958 void Sema::DiscardCleanupsInEvaluationContext() {
16959   ExprCleanupObjects.erase(
16960          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16961          ExprCleanupObjects.end());
16962   Cleanup.reset();
16963   MaybeODRUseExprs.clear();
16964 }
16965 
16966 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16967   ExprResult Result = CheckPlaceholderExpr(E);
16968   if (Result.isInvalid())
16969     return ExprError();
16970   E = Result.get();
16971   if (!E->getType()->isVariablyModifiedType())
16972     return E;
16973   return TransformToPotentiallyEvaluated(E);
16974 }
16975 
16976 /// Are we in a context that is potentially constant evaluated per C++20
16977 /// [expr.const]p12?
16978 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16979   /// C++2a [expr.const]p12:
16980   //   An expression or conversion is potentially constant evaluated if it is
16981   switch (SemaRef.ExprEvalContexts.back().Context) {
16982     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16983     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
16984 
16985       // -- a manifestly constant-evaluated expression,
16986     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16987     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16988     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16989       // -- a potentially-evaluated expression,
16990     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16991       // -- an immediate subexpression of a braced-init-list,
16992 
16993       // -- [FIXME] an expression of the form & cast-expression that occurs
16994       //    within a templated entity
16995       // -- a subexpression of one of the above that is not a subexpression of
16996       // a nested unevaluated operand.
16997       return true;
16998 
16999     case Sema::ExpressionEvaluationContext::Unevaluated:
17000     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17001       // Expressions in this context are never evaluated.
17002       return false;
17003   }
17004   llvm_unreachable("Invalid context");
17005 }
17006 
17007 /// Return true if this function has a calling convention that requires mangling
17008 /// in the size of the parameter pack.
17009 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
17010   // These manglings don't do anything on non-Windows or non-x86 platforms, so
17011   // we don't need parameter type sizes.
17012   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17013   if (!TT.isOSWindows() || !TT.isX86())
17014     return false;
17015 
17016   // If this is C++ and this isn't an extern "C" function, parameters do not
17017   // need to be complete. In this case, C++ mangling will apply, which doesn't
17018   // use the size of the parameters.
17019   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17020     return false;
17021 
17022   // Stdcall, fastcall, and vectorcall need this special treatment.
17023   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17024   switch (CC) {
17025   case CC_X86StdCall:
17026   case CC_X86FastCall:
17027   case CC_X86VectorCall:
17028     return true;
17029   default:
17030     break;
17031   }
17032   return false;
17033 }
17034 
17035 /// Require that all of the parameter types of function be complete. Normally,
17036 /// parameter types are only required to be complete when a function is called
17037 /// or defined, but to mangle functions with certain calling conventions, the
17038 /// mangler needs to know the size of the parameter list. In this situation,
17039 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17040 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17041 /// result in a linker error. Clang doesn't implement this behavior, and instead
17042 /// attempts to error at compile time.
17043 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
17044                                                   SourceLocation Loc) {
17045   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17046     FunctionDecl *FD;
17047     ParmVarDecl *Param;
17048 
17049   public:
17050     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17051         : FD(FD), Param(Param) {}
17052 
17053     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17054       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17055       StringRef CCName;
17056       switch (CC) {
17057       case CC_X86StdCall:
17058         CCName = "stdcall";
17059         break;
17060       case CC_X86FastCall:
17061         CCName = "fastcall";
17062         break;
17063       case CC_X86VectorCall:
17064         CCName = "vectorcall";
17065         break;
17066       default:
17067         llvm_unreachable("CC does not need mangling");
17068       }
17069 
17070       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17071           << Param->getDeclName() << FD->getDeclName() << CCName;
17072     }
17073   };
17074 
17075   for (ParmVarDecl *Param : FD->parameters()) {
17076     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17077     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17078   }
17079 }
17080 
17081 namespace {
17082 enum class OdrUseContext {
17083   /// Declarations in this context are not odr-used.
17084   None,
17085   /// Declarations in this context are formally odr-used, but this is a
17086   /// dependent context.
17087   Dependent,
17088   /// Declarations in this context are odr-used but not actually used (yet).
17089   FormallyOdrUsed,
17090   /// Declarations in this context are used.
17091   Used
17092 };
17093 }
17094 
17095 /// Are we within a context in which references to resolved functions or to
17096 /// variables result in odr-use?
17097 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17098   OdrUseContext Result;
17099 
17100   switch (SemaRef.ExprEvalContexts.back().Context) {
17101     case Sema::ExpressionEvaluationContext::Unevaluated:
17102     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17103     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17104       return OdrUseContext::None;
17105 
17106     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17107     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17108     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17109       Result = OdrUseContext::Used;
17110       break;
17111 
17112     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17113       Result = OdrUseContext::FormallyOdrUsed;
17114       break;
17115 
17116     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17117       // A default argument formally results in odr-use, but doesn't actually
17118       // result in a use in any real sense until it itself is used.
17119       Result = OdrUseContext::FormallyOdrUsed;
17120       break;
17121   }
17122 
17123   if (SemaRef.CurContext->isDependentContext())
17124     return OdrUseContext::Dependent;
17125 
17126   return Result;
17127 }
17128 
17129 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17130   if (!Func->isConstexpr())
17131     return false;
17132 
17133   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17134     return true;
17135   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17136   return CCD && CCD->getInheritedConstructor();
17137 }
17138 
17139 /// Mark a function referenced, and check whether it is odr-used
17140 /// (C++ [basic.def.odr]p2, C99 6.9p3)
17141 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17142                                   bool MightBeOdrUse) {
17143   assert(Func && "No function?");
17144 
17145   Func->setReferenced();
17146 
17147   // Recursive functions aren't really used until they're used from some other
17148   // context.
17149   bool IsRecursiveCall = CurContext == Func;
17150 
17151   // C++11 [basic.def.odr]p3:
17152   //   A function whose name appears as a potentially-evaluated expression is
17153   //   odr-used if it is the unique lookup result or the selected member of a
17154   //   set of overloaded functions [...].
17155   //
17156   // We (incorrectly) mark overload resolution as an unevaluated context, so we
17157   // can just check that here.
17158   OdrUseContext OdrUse =
17159       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17160   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17161     OdrUse = OdrUseContext::FormallyOdrUsed;
17162 
17163   // Trivial default constructors and destructors are never actually used.
17164   // FIXME: What about other special members?
17165   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17166       OdrUse == OdrUseContext::Used) {
17167     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17168       if (Constructor->isDefaultConstructor())
17169         OdrUse = OdrUseContext::FormallyOdrUsed;
17170     if (isa<CXXDestructorDecl>(Func))
17171       OdrUse = OdrUseContext::FormallyOdrUsed;
17172   }
17173 
17174   // C++20 [expr.const]p12:
17175   //   A function [...] is needed for constant evaluation if it is [...] a
17176   //   constexpr function that is named by an expression that is potentially
17177   //   constant evaluated
17178   bool NeededForConstantEvaluation =
17179       isPotentiallyConstantEvaluatedContext(*this) &&
17180       isImplicitlyDefinableConstexprFunction(Func);
17181 
17182   // Determine whether we require a function definition to exist, per
17183   // C++11 [temp.inst]p3:
17184   //   Unless a function template specialization has been explicitly
17185   //   instantiated or explicitly specialized, the function template
17186   //   specialization is implicitly instantiated when the specialization is
17187   //   referenced in a context that requires a function definition to exist.
17188   // C++20 [temp.inst]p7:
17189   //   The existence of a definition of a [...] function is considered to
17190   //   affect the semantics of the program if the [...] function is needed for
17191   //   constant evaluation by an expression
17192   // C++20 [basic.def.odr]p10:
17193   //   Every program shall contain exactly one definition of every non-inline
17194   //   function or variable that is odr-used in that program outside of a
17195   //   discarded statement
17196   // C++20 [special]p1:
17197   //   The implementation will implicitly define [defaulted special members]
17198   //   if they are odr-used or needed for constant evaluation.
17199   //
17200   // Note that we skip the implicit instantiation of templates that are only
17201   // used in unused default arguments or by recursive calls to themselves.
17202   // This is formally non-conforming, but seems reasonable in practice.
17203   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
17204                                              NeededForConstantEvaluation);
17205 
17206   // C++14 [temp.expl.spec]p6:
17207   //   If a template [...] is explicitly specialized then that specialization
17208   //   shall be declared before the first use of that specialization that would
17209   //   cause an implicit instantiation to take place, in every translation unit
17210   //   in which such a use occurs
17211   if (NeedDefinition &&
17212       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17213        Func->getMemberSpecializationInfo()))
17214     checkSpecializationVisibility(Loc, Func);
17215 
17216   if (getLangOpts().CUDA)
17217     CheckCUDACall(Loc, Func);
17218 
17219   if (getLangOpts().SYCLIsDevice)
17220     checkSYCLDeviceFunction(Loc, Func);
17221 
17222   // If we need a definition, try to create one.
17223   if (NeedDefinition && !Func->getBody()) {
17224     runWithSufficientStackSpace(Loc, [&] {
17225       if (CXXConstructorDecl *Constructor =
17226               dyn_cast<CXXConstructorDecl>(Func)) {
17227         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17228         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17229           if (Constructor->isDefaultConstructor()) {
17230             if (Constructor->isTrivial() &&
17231                 !Constructor->hasAttr<DLLExportAttr>())
17232               return;
17233             DefineImplicitDefaultConstructor(Loc, Constructor);
17234           } else if (Constructor->isCopyConstructor()) {
17235             DefineImplicitCopyConstructor(Loc, Constructor);
17236           } else if (Constructor->isMoveConstructor()) {
17237             DefineImplicitMoveConstructor(Loc, Constructor);
17238           }
17239         } else if (Constructor->getInheritedConstructor()) {
17240           DefineInheritingConstructor(Loc, Constructor);
17241         }
17242       } else if (CXXDestructorDecl *Destructor =
17243                      dyn_cast<CXXDestructorDecl>(Func)) {
17244         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17245         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17246           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17247             return;
17248           DefineImplicitDestructor(Loc, Destructor);
17249         }
17250         if (Destructor->isVirtual() && getLangOpts().AppleKext)
17251           MarkVTableUsed(Loc, Destructor->getParent());
17252       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17253         if (MethodDecl->isOverloadedOperator() &&
17254             MethodDecl->getOverloadedOperator() == OO_Equal) {
17255           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17256           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17257             if (MethodDecl->isCopyAssignmentOperator())
17258               DefineImplicitCopyAssignment(Loc, MethodDecl);
17259             else if (MethodDecl->isMoveAssignmentOperator())
17260               DefineImplicitMoveAssignment(Loc, MethodDecl);
17261           }
17262         } else if (isa<CXXConversionDecl>(MethodDecl) &&
17263                    MethodDecl->getParent()->isLambda()) {
17264           CXXConversionDecl *Conversion =
17265               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17266           if (Conversion->isLambdaToBlockPointerConversion())
17267             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17268           else
17269             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17270         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17271           MarkVTableUsed(Loc, MethodDecl->getParent());
17272       }
17273 
17274       if (Func->isDefaulted() && !Func->isDeleted()) {
17275         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17276         if (DCK != DefaultedComparisonKind::None)
17277           DefineDefaultedComparison(Loc, Func, DCK);
17278       }
17279 
17280       // Implicit instantiation of function templates and member functions of
17281       // class templates.
17282       if (Func->isImplicitlyInstantiable()) {
17283         TemplateSpecializationKind TSK =
17284             Func->getTemplateSpecializationKindForInstantiation();
17285         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17286         bool FirstInstantiation = PointOfInstantiation.isInvalid();
17287         if (FirstInstantiation) {
17288           PointOfInstantiation = Loc;
17289           if (auto *MSI = Func->getMemberSpecializationInfo())
17290             MSI->setPointOfInstantiation(Loc);
17291             // FIXME: Notify listener.
17292           else
17293             Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17294         } else if (TSK != TSK_ImplicitInstantiation) {
17295           // Use the point of use as the point of instantiation, instead of the
17296           // point of explicit instantiation (which we track as the actual point
17297           // of instantiation). This gives better backtraces in diagnostics.
17298           PointOfInstantiation = Loc;
17299         }
17300 
17301         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17302             Func->isConstexpr()) {
17303           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17304               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17305               CodeSynthesisContexts.size())
17306             PendingLocalImplicitInstantiations.push_back(
17307                 std::make_pair(Func, PointOfInstantiation));
17308           else if (Func->isConstexpr())
17309             // Do not defer instantiations of constexpr functions, to avoid the
17310             // expression evaluator needing to call back into Sema if it sees a
17311             // call to such a function.
17312             InstantiateFunctionDefinition(PointOfInstantiation, Func);
17313           else {
17314             Func->setInstantiationIsPending(true);
17315             PendingInstantiations.push_back(
17316                 std::make_pair(Func, PointOfInstantiation));
17317             // Notify the consumer that a function was implicitly instantiated.
17318             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17319           }
17320         }
17321       } else {
17322         // Walk redefinitions, as some of them may be instantiable.
17323         for (auto i : Func->redecls()) {
17324           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17325             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17326         }
17327       }
17328     });
17329   }
17330 
17331   // C++14 [except.spec]p17:
17332   //   An exception-specification is considered to be needed when:
17333   //   - the function is odr-used or, if it appears in an unevaluated operand,
17334   //     would be odr-used if the expression were potentially-evaluated;
17335   //
17336   // Note, we do this even if MightBeOdrUse is false. That indicates that the
17337   // function is a pure virtual function we're calling, and in that case the
17338   // function was selected by overload resolution and we need to resolve its
17339   // exception specification for a different reason.
17340   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17341   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
17342     ResolveExceptionSpec(Loc, FPT);
17343 
17344   // If this is the first "real" use, act on that.
17345   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
17346     // Keep track of used but undefined functions.
17347     if (!Func->isDefined()) {
17348       if (mightHaveNonExternalLinkage(Func))
17349         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17350       else if (Func->getMostRecentDecl()->isInlined() &&
17351                !LangOpts.GNUInline &&
17352                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
17353         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17354       else if (isExternalWithNoLinkageType(Func))
17355         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17356     }
17357 
17358     // Some x86 Windows calling conventions mangle the size of the parameter
17359     // pack into the name. Computing the size of the parameters requires the
17360     // parameter types to be complete. Check that now.
17361     if (funcHasParameterSizeMangling(*this, Func))
17362       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
17363 
17364     // In the MS C++ ABI, the compiler emits destructor variants where they are
17365     // used. If the destructor is used here but defined elsewhere, mark the
17366     // virtual base destructors referenced. If those virtual base destructors
17367     // are inline, this will ensure they are defined when emitting the complete
17368     // destructor variant. This checking may be redundant if the destructor is
17369     // provided later in this TU.
17370     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17371       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
17372         CXXRecordDecl *Parent = Dtor->getParent();
17373         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
17374           CheckCompleteDestructorVariant(Loc, Dtor);
17375       }
17376     }
17377 
17378     Func->markUsed(Context);
17379   }
17380 }
17381 
17382 /// Directly mark a variable odr-used. Given a choice, prefer to use
17383 /// MarkVariableReferenced since it does additional checks and then
17384 /// calls MarkVarDeclODRUsed.
17385 /// If the variable must be captured:
17386 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
17387 ///  - else capture it in the DeclContext that maps to the
17388 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
17389 static void
17390 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
17391                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
17392   // Keep track of used but undefined variables.
17393   // FIXME: We shouldn't suppress this warning for static data members.
17394   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
17395       (!Var->isExternallyVisible() || Var->isInline() ||
17396        SemaRef.isExternalWithNoLinkageType(Var)) &&
17397       !(Var->isStaticDataMember() && Var->hasInit())) {
17398     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
17399     if (old.isInvalid())
17400       old = Loc;
17401   }
17402   QualType CaptureType, DeclRefType;
17403   if (SemaRef.LangOpts.OpenMP)
17404     SemaRef.tryCaptureOpenMPLambdas(Var);
17405   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
17406     /*EllipsisLoc*/ SourceLocation(),
17407     /*BuildAndDiagnose*/ true,
17408     CaptureType, DeclRefType,
17409     FunctionScopeIndexToStopAt);
17410 
17411   if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) {
17412     auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
17413     auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
17414     auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
17415     if (VarTarget == Sema::CVT_Host &&
17416         (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
17417          UserTarget == Sema::CFT_Global)) {
17418       // Diagnose ODR-use of host global variables in device functions.
17419       // Reference of device global variables in host functions is allowed
17420       // through shadow variables therefore it is not diagnosed.
17421       if (SemaRef.LangOpts.CUDAIsDevice) {
17422         SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
17423             << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
17424         SemaRef.targetDiag(Var->getLocation(),
17425                            Var->getType().isConstQualified()
17426                                ? diag::note_cuda_const_var_unpromoted
17427                                : diag::note_cuda_host_var);
17428       }
17429     } else if (VarTarget == Sema::CVT_Device &&
17430                (UserTarget == Sema::CFT_Host ||
17431                 UserTarget == Sema::CFT_HostDevice) &&
17432                !Var->hasExternalStorage()) {
17433       // Record a CUDA/HIP device side variable if it is ODR-used
17434       // by host code. This is done conservatively, when the variable is
17435       // referenced in any of the following contexts:
17436       //   - a non-function context
17437       //   - a host function
17438       //   - a host device function
17439       // This makes the ODR-use of the device side variable by host code to
17440       // be visible in the device compilation for the compiler to be able to
17441       // emit template variables instantiated by host code only and to
17442       // externalize the static device side variable ODR-used by host code.
17443       SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
17444     }
17445   }
17446 
17447   Var->markUsed(SemaRef.Context);
17448 }
17449 
17450 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
17451                                              SourceLocation Loc,
17452                                              unsigned CapturingScopeIndex) {
17453   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
17454 }
17455 
17456 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
17457                                                ValueDecl *var) {
17458   DeclContext *VarDC = var->getDeclContext();
17459 
17460   //  If the parameter still belongs to the translation unit, then
17461   //  we're actually just using one parameter in the declaration of
17462   //  the next.
17463   if (isa<ParmVarDecl>(var) &&
17464       isa<TranslationUnitDecl>(VarDC))
17465     return;
17466 
17467   // For C code, don't diagnose about capture if we're not actually in code
17468   // right now; it's impossible to write a non-constant expression outside of
17469   // function context, so we'll get other (more useful) diagnostics later.
17470   //
17471   // For C++, things get a bit more nasty... it would be nice to suppress this
17472   // diagnostic for certain cases like using a local variable in an array bound
17473   // for a member of a local class, but the correct predicate is not obvious.
17474   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
17475     return;
17476 
17477   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
17478   unsigned ContextKind = 3; // unknown
17479   if (isa<CXXMethodDecl>(VarDC) &&
17480       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
17481     ContextKind = 2;
17482   } else if (isa<FunctionDecl>(VarDC)) {
17483     ContextKind = 0;
17484   } else if (isa<BlockDecl>(VarDC)) {
17485     ContextKind = 1;
17486   }
17487 
17488   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
17489     << var << ValueKind << ContextKind << VarDC;
17490   S.Diag(var->getLocation(), diag::note_entity_declared_at)
17491       << var;
17492 
17493   // FIXME: Add additional diagnostic info about class etc. which prevents
17494   // capture.
17495 }
17496 
17497 
17498 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17499                                       bool &SubCapturesAreNested,
17500                                       QualType &CaptureType,
17501                                       QualType &DeclRefType) {
17502    // Check whether we've already captured it.
17503   if (CSI->CaptureMap.count(Var)) {
17504     // If we found a capture, any subcaptures are nested.
17505     SubCapturesAreNested = true;
17506 
17507     // Retrieve the capture type for this variable.
17508     CaptureType = CSI->getCapture(Var).getCaptureType();
17509 
17510     // Compute the type of an expression that refers to this variable.
17511     DeclRefType = CaptureType.getNonReferenceType();
17512 
17513     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17514     // are mutable in the sense that user can change their value - they are
17515     // private instances of the captured declarations.
17516     const Capture &Cap = CSI->getCapture(Var);
17517     if (Cap.isCopyCapture() &&
17518         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17519         !(isa<CapturedRegionScopeInfo>(CSI) &&
17520           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17521       DeclRefType.addConst();
17522     return true;
17523   }
17524   return false;
17525 }
17526 
17527 // Only block literals, captured statements, and lambda expressions can
17528 // capture; other scopes don't work.
17529 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17530                                  SourceLocation Loc,
17531                                  const bool Diagnose, Sema &S) {
17532   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17533     return getLambdaAwareParentOfDeclContext(DC);
17534   else if (Var->hasLocalStorage()) {
17535     if (Diagnose)
17536        diagnoseUncapturableValueReference(S, Loc, Var);
17537   }
17538   return nullptr;
17539 }
17540 
17541 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17542 // certain types of variables (unnamed, variably modified types etc.)
17543 // so check for eligibility.
17544 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17545                                  SourceLocation Loc,
17546                                  const bool Diagnose, Sema &S) {
17547 
17548   bool IsBlock = isa<BlockScopeInfo>(CSI);
17549   bool IsLambda = isa<LambdaScopeInfo>(CSI);
17550 
17551   // Lambdas are not allowed to capture unnamed variables
17552   // (e.g. anonymous unions).
17553   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17554   // assuming that's the intent.
17555   if (IsLambda && !Var->getDeclName()) {
17556     if (Diagnose) {
17557       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17558       S.Diag(Var->getLocation(), diag::note_declared_at);
17559     }
17560     return false;
17561   }
17562 
17563   // Prohibit variably-modified types in blocks; they're difficult to deal with.
17564   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17565     if (Diagnose) {
17566       S.Diag(Loc, diag::err_ref_vm_type);
17567       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17568     }
17569     return false;
17570   }
17571   // Prohibit structs with flexible array members too.
17572   // We cannot capture what is in the tail end of the struct.
17573   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17574     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17575       if (Diagnose) {
17576         if (IsBlock)
17577           S.Diag(Loc, diag::err_ref_flexarray_type);
17578         else
17579           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17580         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17581       }
17582       return false;
17583     }
17584   }
17585   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17586   // Lambdas and captured statements are not allowed to capture __block
17587   // variables; they don't support the expected semantics.
17588   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17589     if (Diagnose) {
17590       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17591       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17592     }
17593     return false;
17594   }
17595   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17596   if (S.getLangOpts().OpenCL && IsBlock &&
17597       Var->getType()->isBlockPointerType()) {
17598     if (Diagnose)
17599       S.Diag(Loc, diag::err_opencl_block_ref_block);
17600     return false;
17601   }
17602 
17603   return true;
17604 }
17605 
17606 // Returns true if the capture by block was successful.
17607 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17608                                  SourceLocation Loc,
17609                                  const bool BuildAndDiagnose,
17610                                  QualType &CaptureType,
17611                                  QualType &DeclRefType,
17612                                  const bool Nested,
17613                                  Sema &S, bool Invalid) {
17614   bool ByRef = false;
17615 
17616   // Blocks are not allowed to capture arrays, excepting OpenCL.
17617   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17618   // (decayed to pointers).
17619   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17620     if (BuildAndDiagnose) {
17621       S.Diag(Loc, diag::err_ref_array_type);
17622       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17623       Invalid = true;
17624     } else {
17625       return false;
17626     }
17627   }
17628 
17629   // Forbid the block-capture of autoreleasing variables.
17630   if (!Invalid &&
17631       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17632     if (BuildAndDiagnose) {
17633       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17634         << /*block*/ 0;
17635       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17636       Invalid = true;
17637     } else {
17638       return false;
17639     }
17640   }
17641 
17642   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17643   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17644     QualType PointeeTy = PT->getPointeeType();
17645 
17646     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17647         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17648         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17649       if (BuildAndDiagnose) {
17650         SourceLocation VarLoc = Var->getLocation();
17651         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17652         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17653       }
17654     }
17655   }
17656 
17657   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17658   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17659       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17660     // Block capture by reference does not change the capture or
17661     // declaration reference types.
17662     ByRef = true;
17663   } else {
17664     // Block capture by copy introduces 'const'.
17665     CaptureType = CaptureType.getNonReferenceType().withConst();
17666     DeclRefType = CaptureType;
17667   }
17668 
17669   // Actually capture the variable.
17670   if (BuildAndDiagnose)
17671     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17672                     CaptureType, Invalid);
17673 
17674   return !Invalid;
17675 }
17676 
17677 
17678 /// Capture the given variable in the captured region.
17679 static bool captureInCapturedRegion(
17680     CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
17681     const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
17682     const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
17683     bool IsTopScope, Sema &S, bool Invalid) {
17684   // By default, capture variables by reference.
17685   bool ByRef = true;
17686   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17687     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17688   } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17689     // Using an LValue reference type is consistent with Lambdas (see below).
17690     if (S.isOpenMPCapturedDecl(Var)) {
17691       bool HasConst = DeclRefType.isConstQualified();
17692       DeclRefType = DeclRefType.getUnqualifiedType();
17693       // Don't lose diagnostics about assignments to const.
17694       if (HasConst)
17695         DeclRefType.addConst();
17696     }
17697     // Do not capture firstprivates in tasks.
17698     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17699         OMPC_unknown)
17700       return true;
17701     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17702                                     RSI->OpenMPCaptureLevel);
17703   }
17704 
17705   if (ByRef)
17706     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17707   else
17708     CaptureType = DeclRefType;
17709 
17710   // Actually capture the variable.
17711   if (BuildAndDiagnose)
17712     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17713                     Loc, SourceLocation(), CaptureType, Invalid);
17714 
17715   return !Invalid;
17716 }
17717 
17718 /// Capture the given variable in the lambda.
17719 static bool captureInLambda(LambdaScopeInfo *LSI,
17720                             VarDecl *Var,
17721                             SourceLocation Loc,
17722                             const bool BuildAndDiagnose,
17723                             QualType &CaptureType,
17724                             QualType &DeclRefType,
17725                             const bool RefersToCapturedVariable,
17726                             const Sema::TryCaptureKind Kind,
17727                             SourceLocation EllipsisLoc,
17728                             const bool IsTopScope,
17729                             Sema &S, bool Invalid) {
17730   // Determine whether we are capturing by reference or by value.
17731   bool ByRef = false;
17732   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17733     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17734   } else {
17735     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17736   }
17737 
17738   // Compute the type of the field that will capture this variable.
17739   if (ByRef) {
17740     // C++11 [expr.prim.lambda]p15:
17741     //   An entity is captured by reference if it is implicitly or
17742     //   explicitly captured but not captured by copy. It is
17743     //   unspecified whether additional unnamed non-static data
17744     //   members are declared in the closure type for entities
17745     //   captured by reference.
17746     //
17747     // FIXME: It is not clear whether we want to build an lvalue reference
17748     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17749     // to do the former, while EDG does the latter. Core issue 1249 will
17750     // clarify, but for now we follow GCC because it's a more permissive and
17751     // easily defensible position.
17752     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17753   } else {
17754     // C++11 [expr.prim.lambda]p14:
17755     //   For each entity captured by copy, an unnamed non-static
17756     //   data member is declared in the closure type. The
17757     //   declaration order of these members is unspecified. The type
17758     //   of such a data member is the type of the corresponding
17759     //   captured entity if the entity is not a reference to an
17760     //   object, or the referenced type otherwise. [Note: If the
17761     //   captured entity is a reference to a function, the
17762     //   corresponding data member is also a reference to a
17763     //   function. - end note ]
17764     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17765       if (!RefType->getPointeeType()->isFunctionType())
17766         CaptureType = RefType->getPointeeType();
17767     }
17768 
17769     // Forbid the lambda copy-capture of autoreleasing variables.
17770     if (!Invalid &&
17771         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17772       if (BuildAndDiagnose) {
17773         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17774         S.Diag(Var->getLocation(), diag::note_previous_decl)
17775           << Var->getDeclName();
17776         Invalid = true;
17777       } else {
17778         return false;
17779       }
17780     }
17781 
17782     // Make sure that by-copy captures are of a complete and non-abstract type.
17783     if (!Invalid && BuildAndDiagnose) {
17784       if (!CaptureType->isDependentType() &&
17785           S.RequireCompleteSizedType(
17786               Loc, CaptureType,
17787               diag::err_capture_of_incomplete_or_sizeless_type,
17788               Var->getDeclName()))
17789         Invalid = true;
17790       else if (S.RequireNonAbstractType(Loc, CaptureType,
17791                                         diag::err_capture_of_abstract_type))
17792         Invalid = true;
17793     }
17794   }
17795 
17796   // Compute the type of a reference to this captured variable.
17797   if (ByRef)
17798     DeclRefType = CaptureType.getNonReferenceType();
17799   else {
17800     // C++ [expr.prim.lambda]p5:
17801     //   The closure type for a lambda-expression has a public inline
17802     //   function call operator [...]. This function call operator is
17803     //   declared const (9.3.1) if and only if the lambda-expression's
17804     //   parameter-declaration-clause is not followed by mutable.
17805     DeclRefType = CaptureType.getNonReferenceType();
17806     if (!LSI->Mutable && !CaptureType->isReferenceType())
17807       DeclRefType.addConst();
17808   }
17809 
17810   // Add the capture.
17811   if (BuildAndDiagnose)
17812     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17813                     Loc, EllipsisLoc, CaptureType, Invalid);
17814 
17815   return !Invalid;
17816 }
17817 
17818 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
17819   // Offer a Copy fix even if the type is dependent.
17820   if (Var->getType()->isDependentType())
17821     return true;
17822   QualType T = Var->getType().getNonReferenceType();
17823   if (T.isTriviallyCopyableType(Context))
17824     return true;
17825   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
17826 
17827     if (!(RD = RD->getDefinition()))
17828       return false;
17829     if (RD->hasSimpleCopyConstructor())
17830       return true;
17831     if (RD->hasUserDeclaredCopyConstructor())
17832       for (CXXConstructorDecl *Ctor : RD->ctors())
17833         if (Ctor->isCopyConstructor())
17834           return !Ctor->isDeleted();
17835   }
17836   return false;
17837 }
17838 
17839 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
17840 /// default capture. Fixes may be omitted if they aren't allowed by the
17841 /// standard, for example we can't emit a default copy capture fix-it if we
17842 /// already explicitly copy capture capture another variable.
17843 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
17844                                     VarDecl *Var) {
17845   assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
17846   // Don't offer Capture by copy of default capture by copy fixes if Var is
17847   // known not to be copy constructible.
17848   bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
17849 
17850   SmallString<32> FixBuffer;
17851   StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
17852   if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
17853     SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
17854     if (ShouldOfferCopyFix) {
17855       // Offer fixes to insert an explicit capture for the variable.
17856       // [] -> [VarName]
17857       // [OtherCapture] -> [OtherCapture, VarName]
17858       FixBuffer.assign({Separator, Var->getName()});
17859       Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17860           << Var << /*value*/ 0
17861           << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17862     }
17863     // As above but capture by reference.
17864     FixBuffer.assign({Separator, "&", Var->getName()});
17865     Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17866         << Var << /*reference*/ 1
17867         << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17868   }
17869 
17870   // Only try to offer default capture if there are no captures excluding this
17871   // and init captures.
17872   // [this]: OK.
17873   // [X = Y]: OK.
17874   // [&A, &B]: Don't offer.
17875   // [A, B]: Don't offer.
17876   if (llvm::any_of(LSI->Captures, [](Capture &C) {
17877         return !C.isThisCapture() && !C.isInitCapture();
17878       }))
17879     return;
17880 
17881   // The default capture specifiers, '=' or '&', must appear first in the
17882   // capture body.
17883   SourceLocation DefaultInsertLoc =
17884       LSI->IntroducerRange.getBegin().getLocWithOffset(1);
17885 
17886   if (ShouldOfferCopyFix) {
17887     bool CanDefaultCopyCapture = true;
17888     // [=, *this] OK since c++17
17889     // [=, this] OK since c++20
17890     if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
17891       CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
17892                                   ? LSI->getCXXThisCapture().isCopyCapture()
17893                                   : false;
17894     // We can't use default capture by copy if any captures already specified
17895     // capture by copy.
17896     if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
17897           return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
17898         })) {
17899       FixBuffer.assign({"=", Separator});
17900       Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
17901           << /*value*/ 0
17902           << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
17903     }
17904   }
17905 
17906   // We can't use default capture by reference if any captures already specified
17907   // capture by reference.
17908   if (llvm::none_of(LSI->Captures, [](Capture &C) {
17909         return !C.isInitCapture() && C.isReferenceCapture() &&
17910                !C.isThisCapture();
17911       })) {
17912     FixBuffer.assign({"&", Separator});
17913     Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
17914         << /*reference*/ 1
17915         << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
17916   }
17917 }
17918 
17919 bool Sema::tryCaptureVariable(
17920     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17921     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17922     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17923   // An init-capture is notionally from the context surrounding its
17924   // declaration, but its parent DC is the lambda class.
17925   DeclContext *VarDC = Var->getDeclContext();
17926   if (Var->isInitCapture())
17927     VarDC = VarDC->getParent();
17928 
17929   DeclContext *DC = CurContext;
17930   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17931       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17932   // We need to sync up the Declaration Context with the
17933   // FunctionScopeIndexToStopAt
17934   if (FunctionScopeIndexToStopAt) {
17935     unsigned FSIndex = FunctionScopes.size() - 1;
17936     while (FSIndex != MaxFunctionScopesIndex) {
17937       DC = getLambdaAwareParentOfDeclContext(DC);
17938       --FSIndex;
17939     }
17940   }
17941 
17942 
17943   // If the variable is declared in the current context, there is no need to
17944   // capture it.
17945   if (VarDC == DC) return true;
17946 
17947   // Capture global variables if it is required to use private copy of this
17948   // variable.
17949   bool IsGlobal = !Var->hasLocalStorage();
17950   if (IsGlobal &&
17951       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17952                                                 MaxFunctionScopesIndex)))
17953     return true;
17954   Var = Var->getCanonicalDecl();
17955 
17956   // Walk up the stack to determine whether we can capture the variable,
17957   // performing the "simple" checks that don't depend on type. We stop when
17958   // we've either hit the declared scope of the variable or find an existing
17959   // capture of that variable.  We start from the innermost capturing-entity
17960   // (the DC) and ensure that all intervening capturing-entities
17961   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17962   // declcontext can either capture the variable or have already captured
17963   // the variable.
17964   CaptureType = Var->getType();
17965   DeclRefType = CaptureType.getNonReferenceType();
17966   bool Nested = false;
17967   bool Explicit = (Kind != TryCapture_Implicit);
17968   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17969   do {
17970     // Only block literals, captured statements, and lambda expressions can
17971     // capture; other scopes don't work.
17972     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17973                                                               ExprLoc,
17974                                                               BuildAndDiagnose,
17975                                                               *this);
17976     // We need to check for the parent *first* because, if we *have*
17977     // private-captured a global variable, we need to recursively capture it in
17978     // intermediate blocks, lambdas, etc.
17979     if (!ParentDC) {
17980       if (IsGlobal) {
17981         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17982         break;
17983       }
17984       return true;
17985     }
17986 
17987     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17988     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17989 
17990 
17991     // Check whether we've already captured it.
17992     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17993                                              DeclRefType)) {
17994       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17995       break;
17996     }
17997     // If we are instantiating a generic lambda call operator body,
17998     // we do not want to capture new variables.  What was captured
17999     // during either a lambdas transformation or initial parsing
18000     // should be used.
18001     if (isGenericLambdaCallOperatorSpecialization(DC)) {
18002       if (BuildAndDiagnose) {
18003         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18004         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
18005           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18006           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18007           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18008           buildLambdaCaptureFixit(*this, LSI, Var);
18009         } else
18010           diagnoseUncapturableValueReference(*this, ExprLoc, Var);
18011       }
18012       return true;
18013     }
18014 
18015     // Try to capture variable-length arrays types.
18016     if (Var->getType()->isVariablyModifiedType()) {
18017       // We're going to walk down into the type and look for VLA
18018       // expressions.
18019       QualType QTy = Var->getType();
18020       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18021         QTy = PVD->getOriginalType();
18022       captureVariablyModifiedType(Context, QTy, CSI);
18023     }
18024 
18025     if (getLangOpts().OpenMP) {
18026       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18027         // OpenMP private variables should not be captured in outer scope, so
18028         // just break here. Similarly, global variables that are captured in a
18029         // target region should not be captured outside the scope of the region.
18030         if (RSI->CapRegionKind == CR_OpenMP) {
18031           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
18032               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18033           // If the variable is private (i.e. not captured) and has variably
18034           // modified type, we still need to capture the type for correct
18035           // codegen in all regions, associated with the construct. Currently,
18036           // it is captured in the innermost captured region only.
18037           if (IsOpenMPPrivateDecl != OMPC_unknown &&
18038               Var->getType()->isVariablyModifiedType()) {
18039             QualType QTy = Var->getType();
18040             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18041               QTy = PVD->getOriginalType();
18042             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
18043                  I < E; ++I) {
18044               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18045                   FunctionScopes[FunctionScopesIndex - I]);
18046               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
18047                      "Wrong number of captured regions associated with the "
18048                      "OpenMP construct.");
18049               captureVariablyModifiedType(Context, QTy, OuterRSI);
18050             }
18051           }
18052           bool IsTargetCap =
18053               IsOpenMPPrivateDecl != OMPC_private &&
18054               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
18055                                          RSI->OpenMPCaptureLevel);
18056           // Do not capture global if it is not privatized in outer regions.
18057           bool IsGlobalCap =
18058               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
18059                                                      RSI->OpenMPCaptureLevel);
18060 
18061           // When we detect target captures we are looking from inside the
18062           // target region, therefore we need to propagate the capture from the
18063           // enclosing region. Therefore, the capture is not initially nested.
18064           if (IsTargetCap)
18065             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
18066 
18067           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18068               (IsGlobal && !IsGlobalCap)) {
18069             Nested = !IsTargetCap;
18070             bool HasConst = DeclRefType.isConstQualified();
18071             DeclRefType = DeclRefType.getUnqualifiedType();
18072             // Don't lose diagnostics about assignments to const.
18073             if (HasConst)
18074               DeclRefType.addConst();
18075             CaptureType = Context.getLValueReferenceType(DeclRefType);
18076             break;
18077           }
18078         }
18079       }
18080     }
18081     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18082       // No capture-default, and this is not an explicit capture
18083       // so cannot capture this variable.
18084       if (BuildAndDiagnose) {
18085         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18086         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18087         auto *LSI = cast<LambdaScopeInfo>(CSI);
18088         if (LSI->Lambda) {
18089           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18090           buildLambdaCaptureFixit(*this, LSI, Var);
18091         }
18092         // FIXME: If we error out because an outer lambda can not implicitly
18093         // capture a variable that an inner lambda explicitly captures, we
18094         // should have the inner lambda do the explicit capture - because
18095         // it makes for cleaner diagnostics later.  This would purely be done
18096         // so that the diagnostic does not misleadingly claim that a variable
18097         // can not be captured by a lambda implicitly even though it is captured
18098         // explicitly.  Suggestion:
18099         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18100         //    at the function head
18101         //  - cache the StartingDeclContext - this must be a lambda
18102         //  - captureInLambda in the innermost lambda the variable.
18103       }
18104       return true;
18105     }
18106 
18107     FunctionScopesIndex--;
18108     DC = ParentDC;
18109     Explicit = false;
18110   } while (!VarDC->Equals(DC));
18111 
18112   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18113   // computing the type of the capture at each step, checking type-specific
18114   // requirements, and adding captures if requested.
18115   // If the variable had already been captured previously, we start capturing
18116   // at the lambda nested within that one.
18117   bool Invalid = false;
18118   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18119        ++I) {
18120     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18121 
18122     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18123     // certain types of variables (unnamed, variably modified types etc.)
18124     // so check for eligibility.
18125     if (!Invalid)
18126       Invalid =
18127           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18128 
18129     // After encountering an error, if we're actually supposed to capture, keep
18130     // capturing in nested contexts to suppress any follow-on diagnostics.
18131     if (Invalid && !BuildAndDiagnose)
18132       return true;
18133 
18134     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18135       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18136                                DeclRefType, Nested, *this, Invalid);
18137       Nested = true;
18138     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18139       Invalid = !captureInCapturedRegion(
18140           RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18141           Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18142       Nested = true;
18143     } else {
18144       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18145       Invalid =
18146           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18147                            DeclRefType, Nested, Kind, EllipsisLoc,
18148                            /*IsTopScope*/ I == N - 1, *this, Invalid);
18149       Nested = true;
18150     }
18151 
18152     if (Invalid && !BuildAndDiagnose)
18153       return true;
18154   }
18155   return Invalid;
18156 }
18157 
18158 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
18159                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18160   QualType CaptureType;
18161   QualType DeclRefType;
18162   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18163                             /*BuildAndDiagnose=*/true, CaptureType,
18164                             DeclRefType, nullptr);
18165 }
18166 
18167 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
18168   QualType CaptureType;
18169   QualType DeclRefType;
18170   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18171                              /*BuildAndDiagnose=*/false, CaptureType,
18172                              DeclRefType, nullptr);
18173 }
18174 
18175 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
18176   QualType CaptureType;
18177   QualType DeclRefType;
18178 
18179   // Determine whether we can capture this variable.
18180   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18181                          /*BuildAndDiagnose=*/false, CaptureType,
18182                          DeclRefType, nullptr))
18183     return QualType();
18184 
18185   return DeclRefType;
18186 }
18187 
18188 namespace {
18189 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
18190 // The produced TemplateArgumentListInfo* points to data stored within this
18191 // object, so should only be used in contexts where the pointer will not be
18192 // used after the CopiedTemplateArgs object is destroyed.
18193 class CopiedTemplateArgs {
18194   bool HasArgs;
18195   TemplateArgumentListInfo TemplateArgStorage;
18196 public:
18197   template<typename RefExpr>
18198   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
18199     if (HasArgs)
18200       E->copyTemplateArgumentsInto(TemplateArgStorage);
18201   }
18202   operator TemplateArgumentListInfo*()
18203 #ifdef __has_cpp_attribute
18204 #if __has_cpp_attribute(clang::lifetimebound)
18205   [[clang::lifetimebound]]
18206 #endif
18207 #endif
18208   {
18209     return HasArgs ? &TemplateArgStorage : nullptr;
18210   }
18211 };
18212 }
18213 
18214 /// Walk the set of potential results of an expression and mark them all as
18215 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
18216 ///
18217 /// \return A new expression if we found any potential results, ExprEmpty() if
18218 ///         not, and ExprError() if we diagnosed an error.
18219 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
18220                                                       NonOdrUseReason NOUR) {
18221   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
18222   // an object that satisfies the requirements for appearing in a
18223   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
18224   // is immediately applied."  This function handles the lvalue-to-rvalue
18225   // conversion part.
18226   //
18227   // If we encounter a node that claims to be an odr-use but shouldn't be, we
18228   // transform it into the relevant kind of non-odr-use node and rebuild the
18229   // tree of nodes leading to it.
18230   //
18231   // This is a mini-TreeTransform that only transforms a restricted subset of
18232   // nodes (and only certain operands of them).
18233 
18234   // Rebuild a subexpression.
18235   auto Rebuild = [&](Expr *Sub) {
18236     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
18237   };
18238 
18239   // Check whether a potential result satisfies the requirements of NOUR.
18240   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
18241     // Any entity other than a VarDecl is always odr-used whenever it's named
18242     // in a potentially-evaluated expression.
18243     auto *VD = dyn_cast<VarDecl>(D);
18244     if (!VD)
18245       return true;
18246 
18247     // C++2a [basic.def.odr]p4:
18248     //   A variable x whose name appears as a potentially-evalauted expression
18249     //   e is odr-used by e unless
18250     //   -- x is a reference that is usable in constant expressions, or
18251     //   -- x is a variable of non-reference type that is usable in constant
18252     //      expressions and has no mutable subobjects, and e is an element of
18253     //      the set of potential results of an expression of
18254     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18255     //      conversion is applied, or
18256     //   -- x is a variable of non-reference type, and e is an element of the
18257     //      set of potential results of a discarded-value expression to which
18258     //      the lvalue-to-rvalue conversion is not applied
18259     //
18260     // We check the first bullet and the "potentially-evaluated" condition in
18261     // BuildDeclRefExpr. We check the type requirements in the second bullet
18262     // in CheckLValueToRValueConversionOperand below.
18263     switch (NOUR) {
18264     case NOUR_None:
18265     case NOUR_Unevaluated:
18266       llvm_unreachable("unexpected non-odr-use-reason");
18267 
18268     case NOUR_Constant:
18269       // Constant references were handled when they were built.
18270       if (VD->getType()->isReferenceType())
18271         return true;
18272       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
18273         if (RD->hasMutableFields())
18274           return true;
18275       if (!VD->isUsableInConstantExpressions(S.Context))
18276         return true;
18277       break;
18278 
18279     case NOUR_Discarded:
18280       if (VD->getType()->isReferenceType())
18281         return true;
18282       break;
18283     }
18284     return false;
18285   };
18286 
18287   // Mark that this expression does not constitute an odr-use.
18288   auto MarkNotOdrUsed = [&] {
18289     S.MaybeODRUseExprs.remove(E);
18290     if (LambdaScopeInfo *LSI = S.getCurLambda())
18291       LSI->markVariableExprAsNonODRUsed(E);
18292   };
18293 
18294   // C++2a [basic.def.odr]p2:
18295   //   The set of potential results of an expression e is defined as follows:
18296   switch (E->getStmtClass()) {
18297   //   -- If e is an id-expression, ...
18298   case Expr::DeclRefExprClass: {
18299     auto *DRE = cast<DeclRefExpr>(E);
18300     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
18301       break;
18302 
18303     // Rebuild as a non-odr-use DeclRefExpr.
18304     MarkNotOdrUsed();
18305     return DeclRefExpr::Create(
18306         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
18307         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
18308         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
18309         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
18310   }
18311 
18312   case Expr::FunctionParmPackExprClass: {
18313     auto *FPPE = cast<FunctionParmPackExpr>(E);
18314     // If any of the declarations in the pack is odr-used, then the expression
18315     // as a whole constitutes an odr-use.
18316     for (VarDecl *D : *FPPE)
18317       if (IsPotentialResultOdrUsed(D))
18318         return ExprEmpty();
18319 
18320     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
18321     // nothing cares about whether we marked this as an odr-use, but it might
18322     // be useful for non-compiler tools.
18323     MarkNotOdrUsed();
18324     break;
18325   }
18326 
18327   //   -- If e is a subscripting operation with an array operand...
18328   case Expr::ArraySubscriptExprClass: {
18329     auto *ASE = cast<ArraySubscriptExpr>(E);
18330     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
18331     if (!OldBase->getType()->isArrayType())
18332       break;
18333     ExprResult Base = Rebuild(OldBase);
18334     if (!Base.isUsable())
18335       return Base;
18336     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
18337     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
18338     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
18339     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
18340                                      ASE->getRBracketLoc());
18341   }
18342 
18343   case Expr::MemberExprClass: {
18344     auto *ME = cast<MemberExpr>(E);
18345     // -- If e is a class member access expression [...] naming a non-static
18346     //    data member...
18347     if (isa<FieldDecl>(ME->getMemberDecl())) {
18348       ExprResult Base = Rebuild(ME->getBase());
18349       if (!Base.isUsable())
18350         return Base;
18351       return MemberExpr::Create(
18352           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
18353           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
18354           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
18355           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
18356           ME->getObjectKind(), ME->isNonOdrUse());
18357     }
18358 
18359     if (ME->getMemberDecl()->isCXXInstanceMember())
18360       break;
18361 
18362     // -- If e is a class member access expression naming a static data member,
18363     //    ...
18364     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
18365       break;
18366 
18367     // Rebuild as a non-odr-use MemberExpr.
18368     MarkNotOdrUsed();
18369     return MemberExpr::Create(
18370         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
18371         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
18372         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
18373         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
18374   }
18375 
18376   case Expr::BinaryOperatorClass: {
18377     auto *BO = cast<BinaryOperator>(E);
18378     Expr *LHS = BO->getLHS();
18379     Expr *RHS = BO->getRHS();
18380     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
18381     if (BO->getOpcode() == BO_PtrMemD) {
18382       ExprResult Sub = Rebuild(LHS);
18383       if (!Sub.isUsable())
18384         return Sub;
18385       LHS = Sub.get();
18386     //   -- If e is a comma expression, ...
18387     } else if (BO->getOpcode() == BO_Comma) {
18388       ExprResult Sub = Rebuild(RHS);
18389       if (!Sub.isUsable())
18390         return Sub;
18391       RHS = Sub.get();
18392     } else {
18393       break;
18394     }
18395     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
18396                         LHS, RHS);
18397   }
18398 
18399   //   -- If e has the form (e1)...
18400   case Expr::ParenExprClass: {
18401     auto *PE = cast<ParenExpr>(E);
18402     ExprResult Sub = Rebuild(PE->getSubExpr());
18403     if (!Sub.isUsable())
18404       return Sub;
18405     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
18406   }
18407 
18408   //   -- If e is a glvalue conditional expression, ...
18409   // We don't apply this to a binary conditional operator. FIXME: Should we?
18410   case Expr::ConditionalOperatorClass: {
18411     auto *CO = cast<ConditionalOperator>(E);
18412     ExprResult LHS = Rebuild(CO->getLHS());
18413     if (LHS.isInvalid())
18414       return ExprError();
18415     ExprResult RHS = Rebuild(CO->getRHS());
18416     if (RHS.isInvalid())
18417       return ExprError();
18418     if (!LHS.isUsable() && !RHS.isUsable())
18419       return ExprEmpty();
18420     if (!LHS.isUsable())
18421       LHS = CO->getLHS();
18422     if (!RHS.isUsable())
18423       RHS = CO->getRHS();
18424     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
18425                                 CO->getCond(), LHS.get(), RHS.get());
18426   }
18427 
18428   // [Clang extension]
18429   //   -- If e has the form __extension__ e1...
18430   case Expr::UnaryOperatorClass: {
18431     auto *UO = cast<UnaryOperator>(E);
18432     if (UO->getOpcode() != UO_Extension)
18433       break;
18434     ExprResult Sub = Rebuild(UO->getSubExpr());
18435     if (!Sub.isUsable())
18436       return Sub;
18437     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
18438                           Sub.get());
18439   }
18440 
18441   // [Clang extension]
18442   //   -- If e has the form _Generic(...), the set of potential results is the
18443   //      union of the sets of potential results of the associated expressions.
18444   case Expr::GenericSelectionExprClass: {
18445     auto *GSE = cast<GenericSelectionExpr>(E);
18446 
18447     SmallVector<Expr *, 4> AssocExprs;
18448     bool AnyChanged = false;
18449     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
18450       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
18451       if (AssocExpr.isInvalid())
18452         return ExprError();
18453       if (AssocExpr.isUsable()) {
18454         AssocExprs.push_back(AssocExpr.get());
18455         AnyChanged = true;
18456       } else {
18457         AssocExprs.push_back(OrigAssocExpr);
18458       }
18459     }
18460 
18461     return AnyChanged ? S.CreateGenericSelectionExpr(
18462                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
18463                             GSE->getRParenLoc(), GSE->getControllingExpr(),
18464                             GSE->getAssocTypeSourceInfos(), AssocExprs)
18465                       : ExprEmpty();
18466   }
18467 
18468   // [Clang extension]
18469   //   -- If e has the form __builtin_choose_expr(...), the set of potential
18470   //      results is the union of the sets of potential results of the
18471   //      second and third subexpressions.
18472   case Expr::ChooseExprClass: {
18473     auto *CE = cast<ChooseExpr>(E);
18474 
18475     ExprResult LHS = Rebuild(CE->getLHS());
18476     if (LHS.isInvalid())
18477       return ExprError();
18478 
18479     ExprResult RHS = Rebuild(CE->getLHS());
18480     if (RHS.isInvalid())
18481       return ExprError();
18482 
18483     if (!LHS.get() && !RHS.get())
18484       return ExprEmpty();
18485     if (!LHS.isUsable())
18486       LHS = CE->getLHS();
18487     if (!RHS.isUsable())
18488       RHS = CE->getRHS();
18489 
18490     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
18491                              RHS.get(), CE->getRParenLoc());
18492   }
18493 
18494   // Step through non-syntactic nodes.
18495   case Expr::ConstantExprClass: {
18496     auto *CE = cast<ConstantExpr>(E);
18497     ExprResult Sub = Rebuild(CE->getSubExpr());
18498     if (!Sub.isUsable())
18499       return Sub;
18500     return ConstantExpr::Create(S.Context, Sub.get());
18501   }
18502 
18503   // We could mostly rely on the recursive rebuilding to rebuild implicit
18504   // casts, but not at the top level, so rebuild them here.
18505   case Expr::ImplicitCastExprClass: {
18506     auto *ICE = cast<ImplicitCastExpr>(E);
18507     // Only step through the narrow set of cast kinds we expect to encounter.
18508     // Anything else suggests we've left the region in which potential results
18509     // can be found.
18510     switch (ICE->getCastKind()) {
18511     case CK_NoOp:
18512     case CK_DerivedToBase:
18513     case CK_UncheckedDerivedToBase: {
18514       ExprResult Sub = Rebuild(ICE->getSubExpr());
18515       if (!Sub.isUsable())
18516         return Sub;
18517       CXXCastPath Path(ICE->path());
18518       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
18519                                  ICE->getValueKind(), &Path);
18520     }
18521 
18522     default:
18523       break;
18524     }
18525     break;
18526   }
18527 
18528   default:
18529     break;
18530   }
18531 
18532   // Can't traverse through this node. Nothing to do.
18533   return ExprEmpty();
18534 }
18535 
18536 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
18537   // Check whether the operand is or contains an object of non-trivial C union
18538   // type.
18539   if (E->getType().isVolatileQualified() &&
18540       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
18541        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
18542     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
18543                           Sema::NTCUC_LValueToRValueVolatile,
18544                           NTCUK_Destruct|NTCUK_Copy);
18545 
18546   // C++2a [basic.def.odr]p4:
18547   //   [...] an expression of non-volatile-qualified non-class type to which
18548   //   the lvalue-to-rvalue conversion is applied [...]
18549   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
18550     return E;
18551 
18552   ExprResult Result =
18553       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
18554   if (Result.isInvalid())
18555     return ExprError();
18556   return Result.get() ? Result : E;
18557 }
18558 
18559 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
18560   Res = CorrectDelayedTyposInExpr(Res);
18561 
18562   if (!Res.isUsable())
18563     return Res;
18564 
18565   // If a constant-expression is a reference to a variable where we delay
18566   // deciding whether it is an odr-use, just assume we will apply the
18567   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
18568   // (a non-type template argument), we have special handling anyway.
18569   return CheckLValueToRValueConversionOperand(Res.get());
18570 }
18571 
18572 void Sema::CleanupVarDeclMarking() {
18573   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
18574   // call.
18575   MaybeODRUseExprSet LocalMaybeODRUseExprs;
18576   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
18577 
18578   for (Expr *E : LocalMaybeODRUseExprs) {
18579     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
18580       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
18581                          DRE->getLocation(), *this);
18582     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
18583       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
18584                          *this);
18585     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
18586       for (VarDecl *VD : *FP)
18587         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
18588     } else {
18589       llvm_unreachable("Unexpected expression");
18590     }
18591   }
18592 
18593   assert(MaybeODRUseExprs.empty() &&
18594          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
18595 }
18596 
18597 static void DoMarkVarDeclReferenced(
18598     Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
18599     llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18600   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
18601           isa<FunctionParmPackExpr>(E)) &&
18602          "Invalid Expr argument to DoMarkVarDeclReferenced");
18603   Var->setReferenced();
18604 
18605   if (Var->isInvalidDecl())
18606     return;
18607 
18608   auto *MSI = Var->getMemberSpecializationInfo();
18609   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18610                                        : Var->getTemplateSpecializationKind();
18611 
18612   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18613   bool UsableInConstantExpr =
18614       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18615 
18616   if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
18617     RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
18618   }
18619 
18620   // C++20 [expr.const]p12:
18621   //   A variable [...] is needed for constant evaluation if it is [...] a
18622   //   variable whose name appears as a potentially constant evaluated
18623   //   expression that is either a contexpr variable or is of non-volatile
18624   //   const-qualified integral type or of reference type
18625   bool NeededForConstantEvaluation =
18626       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18627 
18628   bool NeedDefinition =
18629       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18630 
18631   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
18632          "Can't instantiate a partial template specialization.");
18633 
18634   // If this might be a member specialization of a static data member, check
18635   // the specialization is visible. We already did the checks for variable
18636   // template specializations when we created them.
18637   if (NeedDefinition && TSK != TSK_Undeclared &&
18638       !isa<VarTemplateSpecializationDecl>(Var))
18639     SemaRef.checkSpecializationVisibility(Loc, Var);
18640 
18641   // Perform implicit instantiation of static data members, static data member
18642   // templates of class templates, and variable template specializations. Delay
18643   // instantiations of variable templates, except for those that could be used
18644   // in a constant expression.
18645   if (NeedDefinition && isTemplateInstantiation(TSK)) {
18646     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18647     // instantiation declaration if a variable is usable in a constant
18648     // expression (among other cases).
18649     bool TryInstantiating =
18650         TSK == TSK_ImplicitInstantiation ||
18651         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18652 
18653     if (TryInstantiating) {
18654       SourceLocation PointOfInstantiation =
18655           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18656       bool FirstInstantiation = PointOfInstantiation.isInvalid();
18657       if (FirstInstantiation) {
18658         PointOfInstantiation = Loc;
18659         if (MSI)
18660           MSI->setPointOfInstantiation(PointOfInstantiation);
18661           // FIXME: Notify listener.
18662         else
18663           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18664       }
18665 
18666       if (UsableInConstantExpr) {
18667         // Do not defer instantiations of variables that could be used in a
18668         // constant expression.
18669         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18670           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18671         });
18672 
18673         // Re-set the member to trigger a recomputation of the dependence bits
18674         // for the expression.
18675         if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18676           DRE->setDecl(DRE->getDecl());
18677         else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
18678           ME->setMemberDecl(ME->getMemberDecl());
18679       } else if (FirstInstantiation ||
18680                  isa<VarTemplateSpecializationDecl>(Var)) {
18681         // FIXME: For a specialization of a variable template, we don't
18682         // distinguish between "declaration and type implicitly instantiated"
18683         // and "implicit instantiation of definition requested", so we have
18684         // no direct way to avoid enqueueing the pending instantiation
18685         // multiple times.
18686         SemaRef.PendingInstantiations
18687             .push_back(std::make_pair(Var, PointOfInstantiation));
18688       }
18689     }
18690   }
18691 
18692   // C++2a [basic.def.odr]p4:
18693   //   A variable x whose name appears as a potentially-evaluated expression e
18694   //   is odr-used by e unless
18695   //   -- x is a reference that is usable in constant expressions
18696   //   -- x is a variable of non-reference type that is usable in constant
18697   //      expressions and has no mutable subobjects [FIXME], and e is an
18698   //      element of the set of potential results of an expression of
18699   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18700   //      conversion is applied
18701   //   -- x is a variable of non-reference type, and e is an element of the set
18702   //      of potential results of a discarded-value expression to which the
18703   //      lvalue-to-rvalue conversion is not applied [FIXME]
18704   //
18705   // We check the first part of the second bullet here, and
18706   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18707   // FIXME: To get the third bullet right, we need to delay this even for
18708   // variables that are not usable in constant expressions.
18709 
18710   // If we already know this isn't an odr-use, there's nothing more to do.
18711   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18712     if (DRE->isNonOdrUse())
18713       return;
18714   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18715     if (ME->isNonOdrUse())
18716       return;
18717 
18718   switch (OdrUse) {
18719   case OdrUseContext::None:
18720     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18721            "missing non-odr-use marking for unevaluated decl ref");
18722     break;
18723 
18724   case OdrUseContext::FormallyOdrUsed:
18725     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18726     // behavior.
18727     break;
18728 
18729   case OdrUseContext::Used:
18730     // If we might later find that this expression isn't actually an odr-use,
18731     // delay the marking.
18732     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18733       SemaRef.MaybeODRUseExprs.insert(E);
18734     else
18735       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18736     break;
18737 
18738   case OdrUseContext::Dependent:
18739     // If this is a dependent context, we don't need to mark variables as
18740     // odr-used, but we may still need to track them for lambda capture.
18741     // FIXME: Do we also need to do this inside dependent typeid expressions
18742     // (which are modeled as unevaluated at this point)?
18743     const bool RefersToEnclosingScope =
18744         (SemaRef.CurContext != Var->getDeclContext() &&
18745          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18746     if (RefersToEnclosingScope) {
18747       LambdaScopeInfo *const LSI =
18748           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18749       if (LSI && (!LSI->CallOperator ||
18750                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18751         // If a variable could potentially be odr-used, defer marking it so
18752         // until we finish analyzing the full expression for any
18753         // lvalue-to-rvalue
18754         // or discarded value conversions that would obviate odr-use.
18755         // Add it to the list of potential captures that will be analyzed
18756         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18757         // unless the variable is a reference that was initialized by a constant
18758         // expression (this will never need to be captured or odr-used).
18759         //
18760         // FIXME: We can simplify this a lot after implementing P0588R1.
18761         assert(E && "Capture variable should be used in an expression.");
18762         if (!Var->getType()->isReferenceType() ||
18763             !Var->isUsableInConstantExpressions(SemaRef.Context))
18764           LSI->addPotentialCapture(E->IgnoreParens());
18765       }
18766     }
18767     break;
18768   }
18769 }
18770 
18771 /// Mark a variable referenced, and check whether it is odr-used
18772 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18773 /// used directly for normal expressions referring to VarDecl.
18774 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18775   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
18776 }
18777 
18778 static void
18779 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
18780                    bool MightBeOdrUse,
18781                    llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18782   if (SemaRef.isInOpenMPDeclareTargetContext())
18783     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18784 
18785   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18786     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
18787     return;
18788   }
18789 
18790   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18791 
18792   // If this is a call to a method via a cast, also mark the method in the
18793   // derived class used in case codegen can devirtualize the call.
18794   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18795   if (!ME)
18796     return;
18797   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18798   if (!MD)
18799     return;
18800   // Only attempt to devirtualize if this is truly a virtual call.
18801   bool IsVirtualCall = MD->isVirtual() &&
18802                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18803   if (!IsVirtualCall)
18804     return;
18805 
18806   // If it's possible to devirtualize the call, mark the called function
18807   // referenced.
18808   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18809       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18810   if (DM)
18811     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18812 }
18813 
18814 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18815 ///
18816 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
18817 /// handled with care if the DeclRefExpr is not newly-created.
18818 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18819   // TODO: update this with DR# once a defect report is filed.
18820   // C++11 defect. The address of a pure member should not be an ODR use, even
18821   // if it's a qualified reference.
18822   bool OdrUse = true;
18823   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18824     if (Method->isVirtual() &&
18825         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18826       OdrUse = false;
18827 
18828   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18829     if (!isUnevaluatedContext() && !isConstantEvaluated() &&
18830         FD->isConsteval() && !RebuildingImmediateInvocation)
18831       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18832   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
18833                      RefsMinusAssignments);
18834 }
18835 
18836 /// Perform reference-marking and odr-use handling for a MemberExpr.
18837 void Sema::MarkMemberReferenced(MemberExpr *E) {
18838   // C++11 [basic.def.odr]p2:
18839   //   A non-overloaded function whose name appears as a potentially-evaluated
18840   //   expression or a member of a set of candidate functions, if selected by
18841   //   overload resolution when referred to from a potentially-evaluated
18842   //   expression, is odr-used, unless it is a pure virtual function and its
18843   //   name is not explicitly qualified.
18844   bool MightBeOdrUse = true;
18845   if (E->performsVirtualDispatch(getLangOpts())) {
18846     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18847       if (Method->isPure())
18848         MightBeOdrUse = false;
18849   }
18850   SourceLocation Loc =
18851       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18852   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
18853                      RefsMinusAssignments);
18854 }
18855 
18856 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18857 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18858   for (VarDecl *VD : *E)
18859     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
18860                        RefsMinusAssignments);
18861 }
18862 
18863 /// Perform marking for a reference to an arbitrary declaration.  It
18864 /// marks the declaration referenced, and performs odr-use checking for
18865 /// functions and variables. This method should not be used when building a
18866 /// normal expression which refers to a variable.
18867 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18868                                  bool MightBeOdrUse) {
18869   if (MightBeOdrUse) {
18870     if (auto *VD = dyn_cast<VarDecl>(D)) {
18871       MarkVariableReferenced(Loc, VD);
18872       return;
18873     }
18874   }
18875   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18876     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18877     return;
18878   }
18879   D->setReferenced();
18880 }
18881 
18882 namespace {
18883   // Mark all of the declarations used by a type as referenced.
18884   // FIXME: Not fully implemented yet! We need to have a better understanding
18885   // of when we're entering a context we should not recurse into.
18886   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18887   // TreeTransforms rebuilding the type in a new context. Rather than
18888   // duplicating the TreeTransform logic, we should consider reusing it here.
18889   // Currently that causes problems when rebuilding LambdaExprs.
18890   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18891     Sema &S;
18892     SourceLocation Loc;
18893 
18894   public:
18895     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18896 
18897     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18898 
18899     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18900   };
18901 }
18902 
18903 bool MarkReferencedDecls::TraverseTemplateArgument(
18904     const TemplateArgument &Arg) {
18905   {
18906     // A non-type template argument is a constant-evaluated context.
18907     EnterExpressionEvaluationContext Evaluated(
18908         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18909     if (Arg.getKind() == TemplateArgument::Declaration) {
18910       if (Decl *D = Arg.getAsDecl())
18911         S.MarkAnyDeclReferenced(Loc, D, true);
18912     } else if (Arg.getKind() == TemplateArgument::Expression) {
18913       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18914     }
18915   }
18916 
18917   return Inherited::TraverseTemplateArgument(Arg);
18918 }
18919 
18920 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18921   MarkReferencedDecls Marker(*this, Loc);
18922   Marker.TraverseType(T);
18923 }
18924 
18925 namespace {
18926 /// Helper class that marks all of the declarations referenced by
18927 /// potentially-evaluated subexpressions as "referenced".
18928 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18929 public:
18930   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18931   bool SkipLocalVariables;
18932   ArrayRef<const Expr *> StopAt;
18933 
18934   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
18935                       ArrayRef<const Expr *> StopAt)
18936       : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
18937 
18938   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18939     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18940   }
18941 
18942   void Visit(Expr *E) {
18943     if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end())
18944       return;
18945     Inherited::Visit(E);
18946   }
18947 
18948   void VisitDeclRefExpr(DeclRefExpr *E) {
18949     // If we were asked not to visit local variables, don't.
18950     if (SkipLocalVariables) {
18951       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18952         if (VD->hasLocalStorage())
18953           return;
18954     }
18955 
18956     // FIXME: This can trigger the instantiation of the initializer of a
18957     // variable, which can cause the expression to become value-dependent
18958     // or error-dependent. Do we need to propagate the new dependence bits?
18959     S.MarkDeclRefReferenced(E);
18960   }
18961 
18962   void VisitMemberExpr(MemberExpr *E) {
18963     S.MarkMemberReferenced(E);
18964     Visit(E->getBase());
18965   }
18966 };
18967 } // namespace
18968 
18969 /// Mark any declarations that appear within this expression or any
18970 /// potentially-evaluated subexpressions as "referenced".
18971 ///
18972 /// \param SkipLocalVariables If true, don't mark local variables as
18973 /// 'referenced'.
18974 /// \param StopAt Subexpressions that we shouldn't recurse into.
18975 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18976                                             bool SkipLocalVariables,
18977                                             ArrayRef<const Expr*> StopAt) {
18978   EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
18979 }
18980 
18981 /// Emit a diagnostic when statements are reachable.
18982 /// FIXME: check for reachability even in expressions for which we don't build a
18983 ///        CFG (eg, in the initializer of a global or in a constant expression).
18984 ///        For example,
18985 ///        namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
18986 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
18987                            const PartialDiagnostic &PD) {
18988   if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18989     if (!FunctionScopes.empty())
18990       FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
18991           sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18992     return true;
18993   }
18994 
18995   // The initializer of a constexpr variable or of the first declaration of a
18996   // static data member is not syntactically a constant evaluated constant,
18997   // but nonetheless is always required to be a constant expression, so we
18998   // can skip diagnosing.
18999   // FIXME: Using the mangling context here is a hack.
19000   if (auto *VD = dyn_cast_or_null<VarDecl>(
19001           ExprEvalContexts.back().ManglingContextDecl)) {
19002     if (VD->isConstexpr() ||
19003         (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
19004       return false;
19005     // FIXME: For any other kind of variable, we should build a CFG for its
19006     // initializer and check whether the context in question is reachable.
19007   }
19008 
19009   Diag(Loc, PD);
19010   return true;
19011 }
19012 
19013 /// Emit a diagnostic that describes an effect on the run-time behavior
19014 /// of the program being compiled.
19015 ///
19016 /// This routine emits the given diagnostic when the code currently being
19017 /// type-checked is "potentially evaluated", meaning that there is a
19018 /// possibility that the code will actually be executable. Code in sizeof()
19019 /// expressions, code used only during overload resolution, etc., are not
19020 /// potentially evaluated. This routine will suppress such diagnostics or,
19021 /// in the absolutely nutty case of potentially potentially evaluated
19022 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
19023 /// later.
19024 ///
19025 /// This routine should be used for all diagnostics that describe the run-time
19026 /// behavior of a program, such as passing a non-POD value through an ellipsis.
19027 /// Failure to do so will likely result in spurious diagnostics or failures
19028 /// during overload resolution or within sizeof/alignof/typeof/typeid.
19029 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
19030                                const PartialDiagnostic &PD) {
19031 
19032   if (ExprEvalContexts.back().isDiscardedStatementContext())
19033     return false;
19034 
19035   switch (ExprEvalContexts.back().Context) {
19036   case ExpressionEvaluationContext::Unevaluated:
19037   case ExpressionEvaluationContext::UnevaluatedList:
19038   case ExpressionEvaluationContext::UnevaluatedAbstract:
19039   case ExpressionEvaluationContext::DiscardedStatement:
19040     // The argument will never be evaluated, so don't complain.
19041     break;
19042 
19043   case ExpressionEvaluationContext::ConstantEvaluated:
19044   case ExpressionEvaluationContext::ImmediateFunctionContext:
19045     // Relevant diagnostics should be produced by constant evaluation.
19046     break;
19047 
19048   case ExpressionEvaluationContext::PotentiallyEvaluated:
19049   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19050     return DiagIfReachable(Loc, Stmts, PD);
19051   }
19052 
19053   return false;
19054 }
19055 
19056 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
19057                                const PartialDiagnostic &PD) {
19058   return DiagRuntimeBehavior(
19059       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
19060 }
19061 
19062 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
19063                                CallExpr *CE, FunctionDecl *FD) {
19064   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
19065     return false;
19066 
19067   // If we're inside a decltype's expression, don't check for a valid return
19068   // type or construct temporaries until we know whether this is the last call.
19069   if (ExprEvalContexts.back().ExprContext ==
19070       ExpressionEvaluationContextRecord::EK_Decltype) {
19071     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
19072     return false;
19073   }
19074 
19075   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
19076     FunctionDecl *FD;
19077     CallExpr *CE;
19078 
19079   public:
19080     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
19081       : FD(FD), CE(CE) { }
19082 
19083     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19084       if (!FD) {
19085         S.Diag(Loc, diag::err_call_incomplete_return)
19086           << T << CE->getSourceRange();
19087         return;
19088       }
19089 
19090       S.Diag(Loc, diag::err_call_function_incomplete_return)
19091           << CE->getSourceRange() << FD << T;
19092       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
19093           << FD->getDeclName();
19094     }
19095   } Diagnoser(FD, CE);
19096 
19097   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
19098     return true;
19099 
19100   return false;
19101 }
19102 
19103 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
19104 // will prevent this condition from triggering, which is what we want.
19105 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
19106   SourceLocation Loc;
19107 
19108   unsigned diagnostic = diag::warn_condition_is_assignment;
19109   bool IsOrAssign = false;
19110 
19111   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
19112     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
19113       return;
19114 
19115     IsOrAssign = Op->getOpcode() == BO_OrAssign;
19116 
19117     // Greylist some idioms by putting them into a warning subcategory.
19118     if (ObjCMessageExpr *ME
19119           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
19120       Selector Sel = ME->getSelector();
19121 
19122       // self = [<foo> init...]
19123       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
19124         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19125 
19126       // <foo> = [<bar> nextObject]
19127       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
19128         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19129     }
19130 
19131     Loc = Op->getOperatorLoc();
19132   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
19133     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
19134       return;
19135 
19136     IsOrAssign = Op->getOperator() == OO_PipeEqual;
19137     Loc = Op->getOperatorLoc();
19138   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
19139     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
19140   else {
19141     // Not an assignment.
19142     return;
19143   }
19144 
19145   Diag(Loc, diagnostic) << E->getSourceRange();
19146 
19147   SourceLocation Open = E->getBeginLoc();
19148   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
19149   Diag(Loc, diag::note_condition_assign_silence)
19150         << FixItHint::CreateInsertion(Open, "(")
19151         << FixItHint::CreateInsertion(Close, ")");
19152 
19153   if (IsOrAssign)
19154     Diag(Loc, diag::note_condition_or_assign_to_comparison)
19155       << FixItHint::CreateReplacement(Loc, "!=");
19156   else
19157     Diag(Loc, diag::note_condition_assign_to_comparison)
19158       << FixItHint::CreateReplacement(Loc, "==");
19159 }
19160 
19161 /// Redundant parentheses over an equality comparison can indicate
19162 /// that the user intended an assignment used as condition.
19163 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
19164   // Don't warn if the parens came from a macro.
19165   SourceLocation parenLoc = ParenE->getBeginLoc();
19166   if (parenLoc.isInvalid() || parenLoc.isMacroID())
19167     return;
19168   // Don't warn for dependent expressions.
19169   if (ParenE->isTypeDependent())
19170     return;
19171 
19172   Expr *E = ParenE->IgnoreParens();
19173 
19174   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
19175     if (opE->getOpcode() == BO_EQ &&
19176         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
19177                                                            == Expr::MLV_Valid) {
19178       SourceLocation Loc = opE->getOperatorLoc();
19179 
19180       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
19181       SourceRange ParenERange = ParenE->getSourceRange();
19182       Diag(Loc, diag::note_equality_comparison_silence)
19183         << FixItHint::CreateRemoval(ParenERange.getBegin())
19184         << FixItHint::CreateRemoval(ParenERange.getEnd());
19185       Diag(Loc, diag::note_equality_comparison_to_assign)
19186         << FixItHint::CreateReplacement(Loc, "=");
19187     }
19188 }
19189 
19190 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
19191                                        bool IsConstexpr) {
19192   DiagnoseAssignmentAsCondition(E);
19193   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
19194     DiagnoseEqualityWithExtraParens(parenE);
19195 
19196   ExprResult result = CheckPlaceholderExpr(E);
19197   if (result.isInvalid()) return ExprError();
19198   E = result.get();
19199 
19200   if (!E->isTypeDependent()) {
19201     if (getLangOpts().CPlusPlus)
19202       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
19203 
19204     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
19205     if (ERes.isInvalid())
19206       return ExprError();
19207     E = ERes.get();
19208 
19209     QualType T = E->getType();
19210     if (!T->isScalarType()) { // C99 6.8.4.1p1
19211       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
19212         << T << E->getSourceRange();
19213       return ExprError();
19214     }
19215     CheckBoolLikeConversion(E, Loc);
19216   }
19217 
19218   return E;
19219 }
19220 
19221 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
19222                                            Expr *SubExpr, ConditionKind CK,
19223                                            bool MissingOK) {
19224   // MissingOK indicates whether having no condition expression is valid
19225   // (for loop) or invalid (e.g. while loop).
19226   if (!SubExpr)
19227     return MissingOK ? ConditionResult() : ConditionError();
19228 
19229   ExprResult Cond;
19230   switch (CK) {
19231   case ConditionKind::Boolean:
19232     Cond = CheckBooleanCondition(Loc, SubExpr);
19233     break;
19234 
19235   case ConditionKind::ConstexprIf:
19236     Cond = CheckBooleanCondition(Loc, SubExpr, true);
19237     break;
19238 
19239   case ConditionKind::Switch:
19240     Cond = CheckSwitchCondition(Loc, SubExpr);
19241     break;
19242   }
19243   if (Cond.isInvalid()) {
19244     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
19245                               {SubExpr}, PreferredConditionType(CK));
19246     if (!Cond.get())
19247       return ConditionError();
19248   }
19249   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
19250   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
19251   if (!FullExpr.get())
19252     return ConditionError();
19253 
19254   return ConditionResult(*this, nullptr, FullExpr,
19255                          CK == ConditionKind::ConstexprIf);
19256 }
19257 
19258 namespace {
19259   /// A visitor for rebuilding a call to an __unknown_any expression
19260   /// to have an appropriate type.
19261   struct RebuildUnknownAnyFunction
19262     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
19263 
19264     Sema &S;
19265 
19266     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
19267 
19268     ExprResult VisitStmt(Stmt *S) {
19269       llvm_unreachable("unexpected statement!");
19270     }
19271 
19272     ExprResult VisitExpr(Expr *E) {
19273       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
19274         << E->getSourceRange();
19275       return ExprError();
19276     }
19277 
19278     /// Rebuild an expression which simply semantically wraps another
19279     /// expression which it shares the type and value kind of.
19280     template <class T> ExprResult rebuildSugarExpr(T *E) {
19281       ExprResult SubResult = Visit(E->getSubExpr());
19282       if (SubResult.isInvalid()) return ExprError();
19283 
19284       Expr *SubExpr = SubResult.get();
19285       E->setSubExpr(SubExpr);
19286       E->setType(SubExpr->getType());
19287       E->setValueKind(SubExpr->getValueKind());
19288       assert(E->getObjectKind() == OK_Ordinary);
19289       return E;
19290     }
19291 
19292     ExprResult VisitParenExpr(ParenExpr *E) {
19293       return rebuildSugarExpr(E);
19294     }
19295 
19296     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19297       return rebuildSugarExpr(E);
19298     }
19299 
19300     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19301       ExprResult SubResult = Visit(E->getSubExpr());
19302       if (SubResult.isInvalid()) return ExprError();
19303 
19304       Expr *SubExpr = SubResult.get();
19305       E->setSubExpr(SubExpr);
19306       E->setType(S.Context.getPointerType(SubExpr->getType()));
19307       assert(E->isPRValue());
19308       assert(E->getObjectKind() == OK_Ordinary);
19309       return E;
19310     }
19311 
19312     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
19313       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
19314 
19315       E->setType(VD->getType());
19316 
19317       assert(E->isPRValue());
19318       if (S.getLangOpts().CPlusPlus &&
19319           !(isa<CXXMethodDecl>(VD) &&
19320             cast<CXXMethodDecl>(VD)->isInstance()))
19321         E->setValueKind(VK_LValue);
19322 
19323       return E;
19324     }
19325 
19326     ExprResult VisitMemberExpr(MemberExpr *E) {
19327       return resolveDecl(E, E->getMemberDecl());
19328     }
19329 
19330     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19331       return resolveDecl(E, E->getDecl());
19332     }
19333   };
19334 }
19335 
19336 /// Given a function expression of unknown-any type, try to rebuild it
19337 /// to have a function type.
19338 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
19339   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
19340   if (Result.isInvalid()) return ExprError();
19341   return S.DefaultFunctionArrayConversion(Result.get());
19342 }
19343 
19344 namespace {
19345   /// A visitor for rebuilding an expression of type __unknown_anytype
19346   /// into one which resolves the type directly on the referring
19347   /// expression.  Strict preservation of the original source
19348   /// structure is not a goal.
19349   struct RebuildUnknownAnyExpr
19350     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
19351 
19352     Sema &S;
19353 
19354     /// The current destination type.
19355     QualType DestType;
19356 
19357     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
19358       : S(S), DestType(CastType) {}
19359 
19360     ExprResult VisitStmt(Stmt *S) {
19361       llvm_unreachable("unexpected statement!");
19362     }
19363 
19364     ExprResult VisitExpr(Expr *E) {
19365       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19366         << E->getSourceRange();
19367       return ExprError();
19368     }
19369 
19370     ExprResult VisitCallExpr(CallExpr *E);
19371     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
19372 
19373     /// Rebuild an expression which simply semantically wraps another
19374     /// expression which it shares the type and value kind of.
19375     template <class T> ExprResult rebuildSugarExpr(T *E) {
19376       ExprResult SubResult = Visit(E->getSubExpr());
19377       if (SubResult.isInvalid()) return ExprError();
19378       Expr *SubExpr = SubResult.get();
19379       E->setSubExpr(SubExpr);
19380       E->setType(SubExpr->getType());
19381       E->setValueKind(SubExpr->getValueKind());
19382       assert(E->getObjectKind() == OK_Ordinary);
19383       return E;
19384     }
19385 
19386     ExprResult VisitParenExpr(ParenExpr *E) {
19387       return rebuildSugarExpr(E);
19388     }
19389 
19390     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19391       return rebuildSugarExpr(E);
19392     }
19393 
19394     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19395       const PointerType *Ptr = DestType->getAs<PointerType>();
19396       if (!Ptr) {
19397         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
19398           << E->getSourceRange();
19399         return ExprError();
19400       }
19401 
19402       if (isa<CallExpr>(E->getSubExpr())) {
19403         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
19404           << E->getSourceRange();
19405         return ExprError();
19406       }
19407 
19408       assert(E->isPRValue());
19409       assert(E->getObjectKind() == OK_Ordinary);
19410       E->setType(DestType);
19411 
19412       // Build the sub-expression as if it were an object of the pointee type.
19413       DestType = Ptr->getPointeeType();
19414       ExprResult SubResult = Visit(E->getSubExpr());
19415       if (SubResult.isInvalid()) return ExprError();
19416       E->setSubExpr(SubResult.get());
19417       return E;
19418     }
19419 
19420     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
19421 
19422     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
19423 
19424     ExprResult VisitMemberExpr(MemberExpr *E) {
19425       return resolveDecl(E, E->getMemberDecl());
19426     }
19427 
19428     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19429       return resolveDecl(E, E->getDecl());
19430     }
19431   };
19432 }
19433 
19434 /// Rebuilds a call expression which yielded __unknown_anytype.
19435 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
19436   Expr *CalleeExpr = E->getCallee();
19437 
19438   enum FnKind {
19439     FK_MemberFunction,
19440     FK_FunctionPointer,
19441     FK_BlockPointer
19442   };
19443 
19444   FnKind Kind;
19445   QualType CalleeType = CalleeExpr->getType();
19446   if (CalleeType == S.Context.BoundMemberTy) {
19447     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
19448     Kind = FK_MemberFunction;
19449     CalleeType = Expr::findBoundMemberType(CalleeExpr);
19450   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
19451     CalleeType = Ptr->getPointeeType();
19452     Kind = FK_FunctionPointer;
19453   } else {
19454     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
19455     Kind = FK_BlockPointer;
19456   }
19457   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
19458 
19459   // Verify that this is a legal result type of a function.
19460   if (DestType->isArrayType() || DestType->isFunctionType()) {
19461     unsigned diagID = diag::err_func_returning_array_function;
19462     if (Kind == FK_BlockPointer)
19463       diagID = diag::err_block_returning_array_function;
19464 
19465     S.Diag(E->getExprLoc(), diagID)
19466       << DestType->isFunctionType() << DestType;
19467     return ExprError();
19468   }
19469 
19470   // Otherwise, go ahead and set DestType as the call's result.
19471   E->setType(DestType.getNonLValueExprType(S.Context));
19472   E->setValueKind(Expr::getValueKindForType(DestType));
19473   assert(E->getObjectKind() == OK_Ordinary);
19474 
19475   // Rebuild the function type, replacing the result type with DestType.
19476   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
19477   if (Proto) {
19478     // __unknown_anytype(...) is a special case used by the debugger when
19479     // it has no idea what a function's signature is.
19480     //
19481     // We want to build this call essentially under the K&R
19482     // unprototyped rules, but making a FunctionNoProtoType in C++
19483     // would foul up all sorts of assumptions.  However, we cannot
19484     // simply pass all arguments as variadic arguments, nor can we
19485     // portably just call the function under a non-variadic type; see
19486     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
19487     // However, it turns out that in practice it is generally safe to
19488     // call a function declared as "A foo(B,C,D);" under the prototype
19489     // "A foo(B,C,D,...);".  The only known exception is with the
19490     // Windows ABI, where any variadic function is implicitly cdecl
19491     // regardless of its normal CC.  Therefore we change the parameter
19492     // types to match the types of the arguments.
19493     //
19494     // This is a hack, but it is far superior to moving the
19495     // corresponding target-specific code from IR-gen to Sema/AST.
19496 
19497     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
19498     SmallVector<QualType, 8> ArgTypes;
19499     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
19500       ArgTypes.reserve(E->getNumArgs());
19501       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
19502         ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
19503       }
19504       ParamTypes = ArgTypes;
19505     }
19506     DestType = S.Context.getFunctionType(DestType, ParamTypes,
19507                                          Proto->getExtProtoInfo());
19508   } else {
19509     DestType = S.Context.getFunctionNoProtoType(DestType,
19510                                                 FnType->getExtInfo());
19511   }
19512 
19513   // Rebuild the appropriate pointer-to-function type.
19514   switch (Kind) {
19515   case FK_MemberFunction:
19516     // Nothing to do.
19517     break;
19518 
19519   case FK_FunctionPointer:
19520     DestType = S.Context.getPointerType(DestType);
19521     break;
19522 
19523   case FK_BlockPointer:
19524     DestType = S.Context.getBlockPointerType(DestType);
19525     break;
19526   }
19527 
19528   // Finally, we can recurse.
19529   ExprResult CalleeResult = Visit(CalleeExpr);
19530   if (!CalleeResult.isUsable()) return ExprError();
19531   E->setCallee(CalleeResult.get());
19532 
19533   // Bind a temporary if necessary.
19534   return S.MaybeBindToTemporary(E);
19535 }
19536 
19537 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
19538   // Verify that this is a legal result type of a call.
19539   if (DestType->isArrayType() || DestType->isFunctionType()) {
19540     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
19541       << DestType->isFunctionType() << DestType;
19542     return ExprError();
19543   }
19544 
19545   // Rewrite the method result type if available.
19546   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
19547     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
19548     Method->setReturnType(DestType);
19549   }
19550 
19551   // Change the type of the message.
19552   E->setType(DestType.getNonReferenceType());
19553   E->setValueKind(Expr::getValueKindForType(DestType));
19554 
19555   return S.MaybeBindToTemporary(E);
19556 }
19557 
19558 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
19559   // The only case we should ever see here is a function-to-pointer decay.
19560   if (E->getCastKind() == CK_FunctionToPointerDecay) {
19561     assert(E->isPRValue());
19562     assert(E->getObjectKind() == OK_Ordinary);
19563 
19564     E->setType(DestType);
19565 
19566     // Rebuild the sub-expression as the pointee (function) type.
19567     DestType = DestType->castAs<PointerType>()->getPointeeType();
19568 
19569     ExprResult Result = Visit(E->getSubExpr());
19570     if (!Result.isUsable()) return ExprError();
19571 
19572     E->setSubExpr(Result.get());
19573     return E;
19574   } else if (E->getCastKind() == CK_LValueToRValue) {
19575     assert(E->isPRValue());
19576     assert(E->getObjectKind() == OK_Ordinary);
19577 
19578     assert(isa<BlockPointerType>(E->getType()));
19579 
19580     E->setType(DestType);
19581 
19582     // The sub-expression has to be a lvalue reference, so rebuild it as such.
19583     DestType = S.Context.getLValueReferenceType(DestType);
19584 
19585     ExprResult Result = Visit(E->getSubExpr());
19586     if (!Result.isUsable()) return ExprError();
19587 
19588     E->setSubExpr(Result.get());
19589     return E;
19590   } else {
19591     llvm_unreachable("Unhandled cast type!");
19592   }
19593 }
19594 
19595 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
19596   ExprValueKind ValueKind = VK_LValue;
19597   QualType Type = DestType;
19598 
19599   // We know how to make this work for certain kinds of decls:
19600 
19601   //  - functions
19602   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
19603     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
19604       DestType = Ptr->getPointeeType();
19605       ExprResult Result = resolveDecl(E, VD);
19606       if (Result.isInvalid()) return ExprError();
19607       return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
19608                                  VK_PRValue);
19609     }
19610 
19611     if (!Type->isFunctionType()) {
19612       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
19613         << VD << E->getSourceRange();
19614       return ExprError();
19615     }
19616     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
19617       // We must match the FunctionDecl's type to the hack introduced in
19618       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
19619       // type. See the lengthy commentary in that routine.
19620       QualType FDT = FD->getType();
19621       const FunctionType *FnType = FDT->castAs<FunctionType>();
19622       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
19623       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19624       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19625         SourceLocation Loc = FD->getLocation();
19626         FunctionDecl *NewFD = FunctionDecl::Create(
19627             S.Context, FD->getDeclContext(), Loc, Loc,
19628             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19629             SC_None, S.getCurFPFeatures().isFPConstrained(),
19630             false /*isInlineSpecified*/, FD->hasPrototype(),
19631             /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
19632 
19633         if (FD->getQualifier())
19634           NewFD->setQualifierInfo(FD->getQualifierLoc());
19635 
19636         SmallVector<ParmVarDecl*, 16> Params;
19637         for (const auto &AI : FT->param_types()) {
19638           ParmVarDecl *Param =
19639             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19640           Param->setScopeInfo(0, Params.size());
19641           Params.push_back(Param);
19642         }
19643         NewFD->setParams(Params);
19644         DRE->setDecl(NewFD);
19645         VD = DRE->getDecl();
19646       }
19647     }
19648 
19649     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19650       if (MD->isInstance()) {
19651         ValueKind = VK_PRValue;
19652         Type = S.Context.BoundMemberTy;
19653       }
19654 
19655     // Function references aren't l-values in C.
19656     if (!S.getLangOpts().CPlusPlus)
19657       ValueKind = VK_PRValue;
19658 
19659   //  - variables
19660   } else if (isa<VarDecl>(VD)) {
19661     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19662       Type = RefTy->getPointeeType();
19663     } else if (Type->isFunctionType()) {
19664       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19665         << VD << E->getSourceRange();
19666       return ExprError();
19667     }
19668 
19669   //  - nothing else
19670   } else {
19671     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19672       << VD << E->getSourceRange();
19673     return ExprError();
19674   }
19675 
19676   // Modifying the declaration like this is friendly to IR-gen but
19677   // also really dangerous.
19678   VD->setType(DestType);
19679   E->setType(Type);
19680   E->setValueKind(ValueKind);
19681   return E;
19682 }
19683 
19684 /// Check a cast of an unknown-any type.  We intentionally only
19685 /// trigger this for C-style casts.
19686 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19687                                      Expr *CastExpr, CastKind &CastKind,
19688                                      ExprValueKind &VK, CXXCastPath &Path) {
19689   // The type we're casting to must be either void or complete.
19690   if (!CastType->isVoidType() &&
19691       RequireCompleteType(TypeRange.getBegin(), CastType,
19692                           diag::err_typecheck_cast_to_incomplete))
19693     return ExprError();
19694 
19695   // Rewrite the casted expression from scratch.
19696   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19697   if (!result.isUsable()) return ExprError();
19698 
19699   CastExpr = result.get();
19700   VK = CastExpr->getValueKind();
19701   CastKind = CK_NoOp;
19702 
19703   return CastExpr;
19704 }
19705 
19706 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19707   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19708 }
19709 
19710 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19711                                     Expr *arg, QualType &paramType) {
19712   // If the syntactic form of the argument is not an explicit cast of
19713   // any sort, just do default argument promotion.
19714   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19715   if (!castArg) {
19716     ExprResult result = DefaultArgumentPromotion(arg);
19717     if (result.isInvalid()) return ExprError();
19718     paramType = result.get()->getType();
19719     return result;
19720   }
19721 
19722   // Otherwise, use the type that was written in the explicit cast.
19723   assert(!arg->hasPlaceholderType());
19724   paramType = castArg->getTypeAsWritten();
19725 
19726   // Copy-initialize a parameter of that type.
19727   InitializedEntity entity =
19728     InitializedEntity::InitializeParameter(Context, paramType,
19729                                            /*consumed*/ false);
19730   return PerformCopyInitialization(entity, callLoc, arg);
19731 }
19732 
19733 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19734   Expr *orig = E;
19735   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19736   while (true) {
19737     E = E->IgnoreParenImpCasts();
19738     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19739       E = call->getCallee();
19740       diagID = diag::err_uncasted_call_of_unknown_any;
19741     } else {
19742       break;
19743     }
19744   }
19745 
19746   SourceLocation loc;
19747   NamedDecl *d;
19748   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19749     loc = ref->getLocation();
19750     d = ref->getDecl();
19751   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19752     loc = mem->getMemberLoc();
19753     d = mem->getMemberDecl();
19754   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19755     diagID = diag::err_uncasted_call_of_unknown_any;
19756     loc = msg->getSelectorStartLoc();
19757     d = msg->getMethodDecl();
19758     if (!d) {
19759       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19760         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19761         << orig->getSourceRange();
19762       return ExprError();
19763     }
19764   } else {
19765     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19766       << E->getSourceRange();
19767     return ExprError();
19768   }
19769 
19770   S.Diag(loc, diagID) << d << orig->getSourceRange();
19771 
19772   // Never recoverable.
19773   return ExprError();
19774 }
19775 
19776 /// Check for operands with placeholder types and complain if found.
19777 /// Returns ExprError() if there was an error and no recovery was possible.
19778 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19779   if (!Context.isDependenceAllowed()) {
19780     // C cannot handle TypoExpr nodes on either side of a binop because it
19781     // doesn't handle dependent types properly, so make sure any TypoExprs have
19782     // been dealt with before checking the operands.
19783     ExprResult Result = CorrectDelayedTyposInExpr(E);
19784     if (!Result.isUsable()) return ExprError();
19785     E = Result.get();
19786   }
19787 
19788   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19789   if (!placeholderType) return E;
19790 
19791   switch (placeholderType->getKind()) {
19792 
19793   // Overloaded expressions.
19794   case BuiltinType::Overload: {
19795     // Try to resolve a single function template specialization.
19796     // This is obligatory.
19797     ExprResult Result = E;
19798     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19799       return Result;
19800 
19801     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19802     // leaves Result unchanged on failure.
19803     Result = E;
19804     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19805       return Result;
19806 
19807     // If that failed, try to recover with a call.
19808     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19809                          /*complain*/ true);
19810     return Result;
19811   }
19812 
19813   // Bound member functions.
19814   case BuiltinType::BoundMember: {
19815     ExprResult result = E;
19816     const Expr *BME = E->IgnoreParens();
19817     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19818     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19819     if (isa<CXXPseudoDestructorExpr>(BME)) {
19820       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19821     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19822       if (ME->getMemberNameInfo().getName().getNameKind() ==
19823           DeclarationName::CXXDestructorName)
19824         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19825     }
19826     tryToRecoverWithCall(result, PD,
19827                          /*complain*/ true);
19828     return result;
19829   }
19830 
19831   // ARC unbridged casts.
19832   case BuiltinType::ARCUnbridgedCast: {
19833     Expr *realCast = stripARCUnbridgedCast(E);
19834     diagnoseARCUnbridgedCast(realCast);
19835     return realCast;
19836   }
19837 
19838   // Expressions of unknown type.
19839   case BuiltinType::UnknownAny:
19840     return diagnoseUnknownAnyExpr(*this, E);
19841 
19842   // Pseudo-objects.
19843   case BuiltinType::PseudoObject:
19844     return checkPseudoObjectRValue(E);
19845 
19846   case BuiltinType::BuiltinFn: {
19847     // Accept __noop without parens by implicitly converting it to a call expr.
19848     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19849     if (DRE) {
19850       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19851       if (FD->getBuiltinID() == Builtin::BI__noop) {
19852         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19853                               CK_BuiltinFnToFnPtr)
19854                 .get();
19855         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19856                                 VK_PRValue, SourceLocation(),
19857                                 FPOptionsOverride());
19858       }
19859     }
19860 
19861     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19862     return ExprError();
19863   }
19864 
19865   case BuiltinType::IncompleteMatrixIdx:
19866     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19867              ->getRowIdx()
19868              ->getBeginLoc(),
19869          diag::err_matrix_incomplete_index);
19870     return ExprError();
19871 
19872   // Expressions of unknown type.
19873   case BuiltinType::OMPArraySection:
19874     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19875     return ExprError();
19876 
19877   // Expressions of unknown type.
19878   case BuiltinType::OMPArrayShaping:
19879     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19880 
19881   case BuiltinType::OMPIterator:
19882     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19883 
19884   // Everything else should be impossible.
19885 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19886   case BuiltinType::Id:
19887 #include "clang/Basic/OpenCLImageTypes.def"
19888 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19889   case BuiltinType::Id:
19890 #include "clang/Basic/OpenCLExtensionTypes.def"
19891 #define SVE_TYPE(Name, Id, SingletonId) \
19892   case BuiltinType::Id:
19893 #include "clang/Basic/AArch64SVEACLETypes.def"
19894 #define PPC_VECTOR_TYPE(Name, Id, Size) \
19895   case BuiltinType::Id:
19896 #include "clang/Basic/PPCTypes.def"
19897 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
19898 #include "clang/Basic/RISCVVTypes.def"
19899 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19900 #define PLACEHOLDER_TYPE(Id, SingletonId)
19901 #include "clang/AST/BuiltinTypes.def"
19902     break;
19903   }
19904 
19905   llvm_unreachable("invalid placeholder type!");
19906 }
19907 
19908 bool Sema::CheckCaseExpression(Expr *E) {
19909   if (E->isTypeDependent())
19910     return true;
19911   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19912     return E->getType()->isIntegralOrEnumerationType();
19913   return false;
19914 }
19915 
19916 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19917 ExprResult
19918 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19919   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19920          "Unknown Objective-C Boolean value!");
19921   QualType BoolT = Context.ObjCBuiltinBoolTy;
19922   if (!Context.getBOOLDecl()) {
19923     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19924                         Sema::LookupOrdinaryName);
19925     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19926       NamedDecl *ND = Result.getFoundDecl();
19927       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19928         Context.setBOOLDecl(TD);
19929     }
19930   }
19931   if (Context.getBOOLDecl())
19932     BoolT = Context.getBOOLType();
19933   return new (Context)
19934       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19935 }
19936 
19937 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19938     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19939     SourceLocation RParen) {
19940   auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
19941     auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19942       return Spec.getPlatform() == Platform;
19943     });
19944     // Transcribe the "ios" availability check to "maccatalyst" when compiling
19945     // for "maccatalyst" if "maccatalyst" is not specified.
19946     if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
19947       Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19948         return Spec.getPlatform() == "ios";
19949       });
19950     }
19951     if (Spec == AvailSpecs.end())
19952       return None;
19953     return Spec->getVersion();
19954   };
19955 
19956   VersionTuple Version;
19957   if (auto MaybeVersion =
19958           FindSpecVersion(Context.getTargetInfo().getPlatformName()))
19959     Version = *MaybeVersion;
19960 
19961   // The use of `@available` in the enclosing context should be analyzed to
19962   // warn when it's used inappropriately (i.e. not if(@available)).
19963   if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
19964     Context->HasPotentialAvailabilityViolations = true;
19965 
19966   return new (Context)
19967       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19968 }
19969 
19970 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19971                                     ArrayRef<Expr *> SubExprs, QualType T) {
19972   if (!Context.getLangOpts().RecoveryAST)
19973     return ExprError();
19974 
19975   if (isSFINAEContext())
19976     return ExprError();
19977 
19978   if (T.isNull() || T->isUndeducedType() ||
19979       !Context.getLangOpts().RecoveryASTType)
19980     // We don't know the concrete type, fallback to dependent type.
19981     T = Context.DependentTy;
19982 
19983   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19984 }
19985