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 using llvm::RoundingMode;
59 
60 /// Determine whether the use of this declaration is valid, without
61 /// emitting diagnostics.
62 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
63   // See if this is an auto-typed variable whose initializer we are parsing.
64   if (ParsingInitForAutoVars.count(D))
65     return false;
66 
67   // See if this is a deleted function.
68   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
69     if (FD->isDeleted())
70       return false;
71 
72     // If the function has a deduced return type, and we can't deduce it,
73     // then we can't use it either.
74     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
75         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
76       return false;
77 
78     // See if this is an aligned allocation/deallocation function that is
79     // unavailable.
80     if (TreatUnavailableAsInvalid &&
81         isUnavailableAlignedAllocationFunction(*FD))
82       return false;
83   }
84 
85   // See if this function is unavailable.
86   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
87       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
88     return false;
89 
90   if (isa<UnresolvedUsingIfExistsDecl>(D))
91     return false;
92 
93   return true;
94 }
95 
96 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
97   // Warn if this is used but marked unused.
98   if (const auto *A = D->getAttr<UnusedAttr>()) {
99     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
100     // should diagnose them.
101     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
102         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
103       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
104       if (DC && !DC->hasAttr<UnusedAttr>())
105         S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
106     }
107   }
108 }
109 
110 /// Emit a note explaining that this function is deleted.
111 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
112   assert(Decl && Decl->isDeleted());
113 
114   if (Decl->isDefaulted()) {
115     // If the method was explicitly defaulted, point at that declaration.
116     if (!Decl->isImplicit())
117       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
118 
119     // Try to diagnose why this special member function was implicitly
120     // deleted. This might fail, if that reason no longer applies.
121     DiagnoseDeletedDefaultedFunction(Decl);
122     return;
123   }
124 
125   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
126   if (Ctor && Ctor->isInheritingConstructor())
127     return NoteDeletedInheritingConstructor(Ctor);
128 
129   Diag(Decl->getLocation(), diag::note_availability_specified_here)
130     << Decl << 1;
131 }
132 
133 /// Determine whether a FunctionDecl was ever declared with an
134 /// explicit storage class.
135 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
136   for (auto I : D->redecls()) {
137     if (I->getStorageClass() != SC_None)
138       return true;
139   }
140   return false;
141 }
142 
143 /// Check whether we're in an extern inline function and referring to a
144 /// variable or function with internal linkage (C11 6.7.4p3).
145 ///
146 /// This is only a warning because we used to silently accept this code, but
147 /// in many cases it will not behave correctly. This is not enabled in C++ mode
148 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
149 /// and so while there may still be user mistakes, most of the time we can't
150 /// prove that there are errors.
151 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
152                                                       const NamedDecl *D,
153                                                       SourceLocation Loc) {
154   // This is disabled under C++; there are too many ways for this to fire in
155   // contexts where the warning is a false positive, or where it is technically
156   // correct but benign.
157   if (S.getLangOpts().CPlusPlus)
158     return;
159 
160   // Check if this is an inlined function or method.
161   FunctionDecl *Current = S.getCurFunctionDecl();
162   if (!Current)
163     return;
164   if (!Current->isInlined())
165     return;
166   if (!Current->isExternallyVisible())
167     return;
168 
169   // Check if the decl has internal linkage.
170   if (D->getFormalLinkage() != InternalLinkage)
171     return;
172 
173   // Downgrade from ExtWarn to Extension if
174   //  (1) the supposedly external inline function is in the main file,
175   //      and probably won't be included anywhere else.
176   //  (2) the thing we're referencing is a pure function.
177   //  (3) the thing we're referencing is another inline function.
178   // This last can give us false negatives, but it's better than warning on
179   // wrappers for simple C library functions.
180   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
181   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
182   if (!DowngradeWarning && UsedFn)
183     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
184 
185   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
186                                : diag::ext_internal_in_extern_inline)
187     << /*IsVar=*/!UsedFn << D;
188 
189   S.MaybeSuggestAddingStaticToDecl(Current);
190 
191   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
192       << D;
193 }
194 
195 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
196   const FunctionDecl *First = Cur->getFirstDecl();
197 
198   // Suggest "static" on the function, if possible.
199   if (!hasAnyExplicitStorageClass(First)) {
200     SourceLocation DeclBegin = First->getSourceRange().getBegin();
201     Diag(DeclBegin, diag::note_convert_inline_to_static)
202       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
203   }
204 }
205 
206 /// Determine whether the use of this declaration is valid, and
207 /// emit any corresponding diagnostics.
208 ///
209 /// This routine diagnoses various problems with referencing
210 /// declarations that can occur when using a declaration. For example,
211 /// it might warn if a deprecated or unavailable declaration is being
212 /// used, or produce an error (and return true) if a C++0x deleted
213 /// function is being used.
214 ///
215 /// \returns true if there was an error (this declaration cannot be
216 /// referenced), false otherwise.
217 ///
218 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
219                              const ObjCInterfaceDecl *UnknownObjCClass,
220                              bool ObjCPropertyAccess,
221                              bool AvoidPartialAvailabilityChecks,
222                              ObjCInterfaceDecl *ClassReceiver) {
223   SourceLocation Loc = Locs.front();
224   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
225     // If there were any diagnostics suppressed by template argument deduction,
226     // emit them now.
227     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
228     if (Pos != SuppressedDiagnostics.end()) {
229       for (const PartialDiagnosticAt &Suppressed : Pos->second)
230         Diag(Suppressed.first, Suppressed.second);
231 
232       // Clear out the list of suppressed diagnostics, so that we don't emit
233       // them again for this specialization. However, we don't obsolete this
234       // entry from the table, because we want to avoid ever emitting these
235       // diagnostics again.
236       Pos->second.clear();
237     }
238 
239     // C++ [basic.start.main]p3:
240     //   The function 'main' shall not be used within a program.
241     if (cast<FunctionDecl>(D)->isMain())
242       Diag(Loc, diag::ext_main_used);
243 
244     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
245   }
246 
247   // See if this is an auto-typed variable whose initializer we are parsing.
248   if (ParsingInitForAutoVars.count(D)) {
249     if (isa<BindingDecl>(D)) {
250       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
251         << D->getDeclName();
252     } else {
253       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
254         << D->getDeclName() << cast<VarDecl>(D)->getType();
255     }
256     return true;
257   }
258 
259   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
260     // See if this is a deleted function.
261     if (FD->isDeleted()) {
262       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
263       if (Ctor && Ctor->isInheritingConstructor())
264         Diag(Loc, diag::err_deleted_inherited_ctor_use)
265             << Ctor->getParent()
266             << Ctor->getInheritedConstructor().getConstructor()->getParent();
267       else
268         Diag(Loc, diag::err_deleted_function_use);
269       NoteDeletedFunction(FD);
270       return true;
271     }
272 
273     // [expr.prim.id]p4
274     //   A program that refers explicitly or implicitly to a function with a
275     //   trailing requires-clause whose constraint-expression is not satisfied,
276     //   other than to declare it, is ill-formed. [...]
277     //
278     // See if this is a function with constraints that need to be satisfied.
279     // Check this before deducing the return type, as it might instantiate the
280     // definition.
281     if (FD->getTrailingRequiresClause()) {
282       ConstraintSatisfaction Satisfaction;
283       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
284         // A diagnostic will have already been generated (non-constant
285         // constraint expression, for example)
286         return true;
287       if (!Satisfaction.IsSatisfied) {
288         Diag(Loc,
289              diag::err_reference_to_function_with_unsatisfied_constraints)
290             << D;
291         DiagnoseUnsatisfiedConstraint(Satisfaction);
292         return true;
293       }
294     }
295 
296     // If the function has a deduced return type, and we can't deduce it,
297     // then we can't use it either.
298     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
299         DeduceReturnType(FD, Loc))
300       return true;
301 
302     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
303       return true;
304 
305     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
306       return true;
307   }
308 
309   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
310     // Lambdas are only default-constructible or assignable in C++2a onwards.
311     if (MD->getParent()->isLambda() &&
312         ((isa<CXXConstructorDecl>(MD) &&
313           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
314          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
315       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
316         << !isa<CXXConstructorDecl>(MD);
317     }
318   }
319 
320   auto getReferencedObjCProp = [](const NamedDecl *D) ->
321                                       const ObjCPropertyDecl * {
322     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
323       return MD->findPropertyDecl();
324     return nullptr;
325   };
326   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
327     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
328       return true;
329   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
330       return true;
331   }
332 
333   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
334   // Only the variables omp_in and omp_out are allowed in the combiner.
335   // Only the variables omp_priv and omp_orig are allowed in the
336   // initializer-clause.
337   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
338   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
339       isa<VarDecl>(D)) {
340     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
341         << getCurFunction()->HasOMPDeclareReductionCombiner;
342     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
343     return true;
344   }
345 
346   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
347   //  List-items in map clauses on this construct may only refer to the declared
348   //  variable var and entities that could be referenced by a procedure defined
349   //  at the same location
350   if (LangOpts.OpenMP && isa<VarDecl>(D) &&
351       !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
352     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
353         << getOpenMPDeclareMapperVarName();
354     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
355     return true;
356   }
357 
358   if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
359     Diag(Loc, diag::err_use_of_empty_using_if_exists);
360     Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
361     return true;
362   }
363 
364   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
365                              AvoidPartialAvailabilityChecks, ClassReceiver);
366 
367   DiagnoseUnusedOfDecl(*this, D, Loc);
368 
369   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
370 
371   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
372     if (auto *VD = dyn_cast<ValueDecl>(D))
373       checkDeviceDecl(VD, Loc);
374 
375     if (!Context.getTargetInfo().isTLSSupported())
376       if (const auto *VD = dyn_cast<VarDecl>(D))
377         if (VD->getTLSKind() != VarDecl::TLS_None)
378           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
379   }
380 
381   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
382       !isUnevaluatedContext()) {
383     // C++ [expr.prim.req.nested] p3
384     //   A local parameter shall only appear as an unevaluated operand
385     //   (Clause 8) within the constraint-expression.
386     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
387         << D;
388     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
389     return true;
390   }
391 
392   return false;
393 }
394 
395 /// DiagnoseSentinelCalls - This routine checks whether a call or
396 /// message-send is to a declaration with the sentinel attribute, and
397 /// if so, it checks that the requirements of the sentinel are
398 /// satisfied.
399 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
400                                  ArrayRef<Expr *> Args) {
401   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
402   if (!attr)
403     return;
404 
405   // The number of formal parameters of the declaration.
406   unsigned numFormalParams;
407 
408   // The kind of declaration.  This is also an index into a %select in
409   // the diagnostic.
410   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
411 
412   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
413     numFormalParams = MD->param_size();
414     calleeType = CT_Method;
415   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
416     numFormalParams = FD->param_size();
417     calleeType = CT_Function;
418   } else if (isa<VarDecl>(D)) {
419     QualType type = cast<ValueDecl>(D)->getType();
420     const FunctionType *fn = nullptr;
421     if (const PointerType *ptr = type->getAs<PointerType>()) {
422       fn = ptr->getPointeeType()->getAs<FunctionType>();
423       if (!fn) return;
424       calleeType = CT_Function;
425     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
426       fn = ptr->getPointeeType()->castAs<FunctionType>();
427       calleeType = CT_Block;
428     } else {
429       return;
430     }
431 
432     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
433       numFormalParams = proto->getNumParams();
434     } else {
435       numFormalParams = 0;
436     }
437   } else {
438     return;
439   }
440 
441   // "nullPos" is the number of formal parameters at the end which
442   // effectively count as part of the variadic arguments.  This is
443   // useful if you would prefer to not have *any* formal parameters,
444   // but the language forces you to have at least one.
445   unsigned nullPos = attr->getNullPos();
446   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
447   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
448 
449   // The number of arguments which should follow the sentinel.
450   unsigned numArgsAfterSentinel = attr->getSentinel();
451 
452   // If there aren't enough arguments for all the formal parameters,
453   // the sentinel, and the args after the sentinel, complain.
454   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
455     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
456     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
457     return;
458   }
459 
460   // Otherwise, find the sentinel expression.
461   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
462   if (!sentinelExpr) return;
463   if (sentinelExpr->isValueDependent()) return;
464   if (Context.isSentinelNullExpr(sentinelExpr)) return;
465 
466   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
467   // or 'NULL' if those are actually defined in the context.  Only use
468   // 'nil' for ObjC methods, where it's much more likely that the
469   // variadic arguments form a list of object pointers.
470   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
471   std::string NullValue;
472   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
473     NullValue = "nil";
474   else if (getLangOpts().CPlusPlus11)
475     NullValue = "nullptr";
476   else if (PP.isMacroDefined("NULL"))
477     NullValue = "NULL";
478   else
479     NullValue = "(void*) 0";
480 
481   if (MissingNilLoc.isInvalid())
482     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
483   else
484     Diag(MissingNilLoc, diag::warn_missing_sentinel)
485       << int(calleeType)
486       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
487   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
488 }
489 
490 SourceRange Sema::getExprRange(Expr *E) const {
491   return E ? E->getSourceRange() : SourceRange();
492 }
493 
494 //===----------------------------------------------------------------------===//
495 //  Standard Promotions and Conversions
496 //===----------------------------------------------------------------------===//
497 
498 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
499 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
500   // Handle any placeholder expressions which made it here.
501   if (E->getType()->isPlaceholderType()) {
502     ExprResult result = CheckPlaceholderExpr(E);
503     if (result.isInvalid()) return ExprError();
504     E = result.get();
505   }
506 
507   QualType Ty = E->getType();
508   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
509 
510   if (Ty->isFunctionType()) {
511     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
512       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
513         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
514           return ExprError();
515 
516     E = ImpCastExprToType(E, Context.getPointerType(Ty),
517                           CK_FunctionToPointerDecay).get();
518   } else if (Ty->isArrayType()) {
519     // In C90 mode, arrays only promote to pointers if the array expression is
520     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
521     // type 'array of type' is converted to an expression that has type 'pointer
522     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
523     // that has type 'array of type' ...".  The relevant change is "an lvalue"
524     // (C90) to "an expression" (C99).
525     //
526     // C++ 4.2p1:
527     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
528     // T" can be converted to an rvalue of type "pointer to T".
529     //
530     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
531       ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
532                                          CK_ArrayToPointerDecay);
533       if (Res.isInvalid())
534         return ExprError();
535       E = Res.get();
536     }
537   }
538   return E;
539 }
540 
541 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
542   // Check to see if we are dereferencing a null pointer.  If so,
543   // and if not volatile-qualified, this is undefined behavior that the
544   // optimizer will delete, so warn about it.  People sometimes try to use this
545   // to get a deterministic trap and are surprised by clang's behavior.  This
546   // only handles the pattern "*null", which is a very syntactic check.
547   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
548   if (UO && UO->getOpcode() == UO_Deref &&
549       UO->getSubExpr()->getType()->isPointerType()) {
550     const LangAS AS =
551         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
552     if ((!isTargetAddressSpace(AS) ||
553          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
554         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
555             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
556         !UO->getType().isVolatileQualified()) {
557       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
558                             S.PDiag(diag::warn_indirection_through_null)
559                                 << UO->getSubExpr()->getSourceRange());
560       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
561                             S.PDiag(diag::note_indirection_through_null));
562     }
563   }
564 }
565 
566 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
567                                     SourceLocation AssignLoc,
568                                     const Expr* RHS) {
569   const ObjCIvarDecl *IV = OIRE->getDecl();
570   if (!IV)
571     return;
572 
573   DeclarationName MemberName = IV->getDeclName();
574   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
575   if (!Member || !Member->isStr("isa"))
576     return;
577 
578   const Expr *Base = OIRE->getBase();
579   QualType BaseType = Base->getType();
580   if (OIRE->isArrow())
581     BaseType = BaseType->getPointeeType();
582   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
583     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
584       ObjCInterfaceDecl *ClassDeclared = nullptr;
585       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
586       if (!ClassDeclared->getSuperClass()
587           && (*ClassDeclared->ivar_begin()) == IV) {
588         if (RHS) {
589           NamedDecl *ObjectSetClass =
590             S.LookupSingleName(S.TUScope,
591                                &S.Context.Idents.get("object_setClass"),
592                                SourceLocation(), S.LookupOrdinaryName);
593           if (ObjectSetClass) {
594             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
595             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
596                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
597                                               "object_setClass(")
598                 << FixItHint::CreateReplacement(
599                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
600                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
601           }
602           else
603             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
604         } else {
605           NamedDecl *ObjectGetClass =
606             S.LookupSingleName(S.TUScope,
607                                &S.Context.Idents.get("object_getClass"),
608                                SourceLocation(), S.LookupOrdinaryName);
609           if (ObjectGetClass)
610             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
611                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
612                                               "object_getClass(")
613                 << FixItHint::CreateReplacement(
614                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
615           else
616             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
617         }
618         S.Diag(IV->getLocation(), diag::note_ivar_decl);
619       }
620     }
621 }
622 
623 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
624   // Handle any placeholder expressions which made it here.
625   if (E->getType()->isPlaceholderType()) {
626     ExprResult result = CheckPlaceholderExpr(E);
627     if (result.isInvalid()) return ExprError();
628     E = result.get();
629   }
630 
631   // C++ [conv.lval]p1:
632   //   A glvalue of a non-function, non-array type T can be
633   //   converted to a prvalue.
634   if (!E->isGLValue()) return E;
635 
636   QualType T = E->getType();
637   assert(!T.isNull() && "r-value conversion on typeless expression?");
638 
639   // lvalue-to-rvalue conversion cannot be applied to function or array types.
640   if (T->isFunctionType() || T->isArrayType())
641     return E;
642 
643   // We don't want to throw lvalue-to-rvalue casts on top of
644   // expressions of certain types in C++.
645   if (getLangOpts().CPlusPlus &&
646       (E->getType() == Context.OverloadTy ||
647        T->isDependentType() ||
648        T->isRecordType()))
649     return E;
650 
651   // The C standard is actually really unclear on this point, and
652   // DR106 tells us what the result should be but not why.  It's
653   // generally best to say that void types just doesn't undergo
654   // lvalue-to-rvalue at all.  Note that expressions of unqualified
655   // 'void' type are never l-values, but qualified void can be.
656   if (T->isVoidType())
657     return E;
658 
659   // OpenCL usually rejects direct accesses to values of 'half' type.
660   if (getLangOpts().OpenCL &&
661       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
662       T->isHalfType()) {
663     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
664       << 0 << T;
665     return ExprError();
666   }
667 
668   CheckForNullPointerDereference(*this, E);
669   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
670     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
671                                      &Context.Idents.get("object_getClass"),
672                                      SourceLocation(), LookupOrdinaryName);
673     if (ObjectGetClass)
674       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
675           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
676           << FixItHint::CreateReplacement(
677                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
678     else
679       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
680   }
681   else if (const ObjCIvarRefExpr *OIRE =
682             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
683     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
684 
685   // C++ [conv.lval]p1:
686   //   [...] If T is a non-class type, the type of the prvalue is the
687   //   cv-unqualified version of T. Otherwise, the type of the
688   //   rvalue is T.
689   //
690   // C99 6.3.2.1p2:
691   //   If the lvalue has qualified type, the value has the unqualified
692   //   version of the type of the lvalue; otherwise, the value has the
693   //   type of the lvalue.
694   if (T.hasQualifiers())
695     T = T.getUnqualifiedType();
696 
697   // Under the MS ABI, lock down the inheritance model now.
698   if (T->isMemberPointerType() &&
699       Context.getTargetInfo().getCXXABI().isMicrosoft())
700     (void)isCompleteType(E->getExprLoc(), T);
701 
702   ExprResult Res = CheckLValueToRValueConversionOperand(E);
703   if (Res.isInvalid())
704     return Res;
705   E = Res.get();
706 
707   // Loading a __weak object implicitly retains the value, so we need a cleanup to
708   // balance that.
709   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
710     Cleanup.setExprNeedsCleanups(true);
711 
712   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
713     Cleanup.setExprNeedsCleanups(true);
714 
715   // C++ [conv.lval]p3:
716   //   If T is cv std::nullptr_t, the result is a null pointer constant.
717   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
718   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
719                                  CurFPFeatureOverrides());
720 
721   // C11 6.3.2.1p2:
722   //   ... if the lvalue has atomic type, the value has the non-atomic version
723   //   of the type of the lvalue ...
724   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
725     T = Atomic->getValueType().getUnqualifiedType();
726     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
727                                    nullptr, VK_PRValue, FPOptionsOverride());
728   }
729 
730   return Res;
731 }
732 
733 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
734   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
735   if (Res.isInvalid())
736     return ExprError();
737   Res = DefaultLvalueConversion(Res.get());
738   if (Res.isInvalid())
739     return ExprError();
740   return Res;
741 }
742 
743 /// CallExprUnaryConversions - a special case of an unary conversion
744 /// performed on a function designator of a call expression.
745 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
746   QualType Ty = E->getType();
747   ExprResult Res = E;
748   // Only do implicit cast for a function type, but not for a pointer
749   // to function type.
750   if (Ty->isFunctionType()) {
751     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
752                             CK_FunctionToPointerDecay);
753     if (Res.isInvalid())
754       return ExprError();
755   }
756   Res = DefaultLvalueConversion(Res.get());
757   if (Res.isInvalid())
758     return ExprError();
759   return Res.get();
760 }
761 
762 /// UsualUnaryConversions - Performs various conversions that are common to most
763 /// operators (C99 6.3). The conversions of array and function types are
764 /// sometimes suppressed. For example, the array->pointer conversion doesn't
765 /// apply if the array is an argument to the sizeof or address (&) operators.
766 /// In these instances, this routine should *not* be called.
767 ExprResult Sema::UsualUnaryConversions(Expr *E) {
768   // First, convert to an r-value.
769   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
770   if (Res.isInvalid())
771     return ExprError();
772   E = Res.get();
773 
774   QualType Ty = E->getType();
775   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
776 
777   // Half FP have to be promoted to float unless it is natively supported
778   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
779     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
780 
781   // Try to perform integral promotions if the object has a theoretically
782   // promotable type.
783   if (Ty->isIntegralOrUnscopedEnumerationType()) {
784     // C99 6.3.1.1p2:
785     //
786     //   The following may be used in an expression wherever an int or
787     //   unsigned int may be used:
788     //     - an object or expression with an integer type whose integer
789     //       conversion rank is less than or equal to the rank of int
790     //       and unsigned int.
791     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
792     //
793     //   If an int can represent all values of the original type, the
794     //   value is converted to an int; otherwise, it is converted to an
795     //   unsigned int. These are called the integer promotions. All
796     //   other types are unchanged by the integer promotions.
797 
798     QualType PTy = Context.isPromotableBitField(E);
799     if (!PTy.isNull()) {
800       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
801       return E;
802     }
803     if (Ty->isPromotableIntegerType()) {
804       QualType PT = Context.getPromotedIntegerType(Ty);
805       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
806       return E;
807     }
808   }
809   return E;
810 }
811 
812 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
813 /// do not have a prototype. Arguments that have type float or __fp16
814 /// are promoted to double. All other argument types are converted by
815 /// UsualUnaryConversions().
816 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
817   QualType Ty = E->getType();
818   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
819 
820   ExprResult Res = UsualUnaryConversions(E);
821   if (Res.isInvalid())
822     return ExprError();
823   E = Res.get();
824 
825   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
826   // promote to double.
827   // Note that default argument promotion applies only to float (and
828   // half/fp16); it does not apply to _Float16.
829   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
830   if (BTy && (BTy->getKind() == BuiltinType::Half ||
831               BTy->getKind() == BuiltinType::Float)) {
832     if (getLangOpts().OpenCL &&
833         !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
834       if (BTy->getKind() == BuiltinType::Half) {
835         E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
836       }
837     } else {
838       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
839     }
840   }
841   if (BTy &&
842       getLangOpts().getExtendIntArgs() ==
843           LangOptions::ExtendArgsKind::ExtendTo64 &&
844       Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
845       Context.getTypeSizeInChars(BTy) <
846           Context.getTypeSizeInChars(Context.LongLongTy)) {
847     E = (Ty->isUnsignedIntegerType())
848             ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
849                   .get()
850             : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
851     assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
852            "Unexpected typesize for LongLongTy");
853   }
854 
855   // C++ performs lvalue-to-rvalue conversion as a default argument
856   // promotion, even on class types, but note:
857   //   C++11 [conv.lval]p2:
858   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
859   //     operand or a subexpression thereof the value contained in the
860   //     referenced object is not accessed. Otherwise, if the glvalue
861   //     has a class type, the conversion copy-initializes a temporary
862   //     of type T from the glvalue and the result of the conversion
863   //     is a prvalue for the temporary.
864   // FIXME: add some way to gate this entire thing for correctness in
865   // potentially potentially evaluated contexts.
866   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
867     ExprResult Temp = PerformCopyInitialization(
868                        InitializedEntity::InitializeTemporary(E->getType()),
869                                                 E->getExprLoc(), E);
870     if (Temp.isInvalid())
871       return ExprError();
872     E = Temp.get();
873   }
874 
875   return E;
876 }
877 
878 /// Determine the degree of POD-ness for an expression.
879 /// Incomplete types are considered POD, since this check can be performed
880 /// when we're in an unevaluated context.
881 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
882   if (Ty->isIncompleteType()) {
883     // C++11 [expr.call]p7:
884     //   After these conversions, if the argument does not have arithmetic,
885     //   enumeration, pointer, pointer to member, or class type, the program
886     //   is ill-formed.
887     //
888     // Since we've already performed array-to-pointer and function-to-pointer
889     // decay, the only such type in C++ is cv void. This also handles
890     // initializer lists as variadic arguments.
891     if (Ty->isVoidType())
892       return VAK_Invalid;
893 
894     if (Ty->isObjCObjectType())
895       return VAK_Invalid;
896     return VAK_Valid;
897   }
898 
899   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
900     return VAK_Invalid;
901 
902   if (Ty.isCXX98PODType(Context))
903     return VAK_Valid;
904 
905   // C++11 [expr.call]p7:
906   //   Passing a potentially-evaluated argument of class type (Clause 9)
907   //   having a non-trivial copy constructor, a non-trivial move constructor,
908   //   or a non-trivial destructor, with no corresponding parameter,
909   //   is conditionally-supported with implementation-defined semantics.
910   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
911     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
912       if (!Record->hasNonTrivialCopyConstructor() &&
913           !Record->hasNonTrivialMoveConstructor() &&
914           !Record->hasNonTrivialDestructor())
915         return VAK_ValidInCXX11;
916 
917   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
918     return VAK_Valid;
919 
920   if (Ty->isObjCObjectType())
921     return VAK_Invalid;
922 
923   if (getLangOpts().MSVCCompat)
924     return VAK_MSVCUndefined;
925 
926   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
927   // permitted to reject them. We should consider doing so.
928   return VAK_Undefined;
929 }
930 
931 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
932   // Don't allow one to pass an Objective-C interface to a vararg.
933   const QualType &Ty = E->getType();
934   VarArgKind VAK = isValidVarArgType(Ty);
935 
936   // Complain about passing non-POD types through varargs.
937   switch (VAK) {
938   case VAK_ValidInCXX11:
939     DiagRuntimeBehavior(
940         E->getBeginLoc(), nullptr,
941         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
942     LLVM_FALLTHROUGH;
943   case VAK_Valid:
944     if (Ty->isRecordType()) {
945       // This is unlikely to be what the user intended. If the class has a
946       // 'c_str' member function, the user probably meant to call that.
947       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
948                           PDiag(diag::warn_pass_class_arg_to_vararg)
949                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
950     }
951     break;
952 
953   case VAK_Undefined:
954   case VAK_MSVCUndefined:
955     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
956                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
957                             << getLangOpts().CPlusPlus11 << Ty << CT);
958     break;
959 
960   case VAK_Invalid:
961     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
962       Diag(E->getBeginLoc(),
963            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
964           << Ty << CT;
965     else if (Ty->isObjCObjectType())
966       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
967                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
968                               << Ty << CT);
969     else
970       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
971           << isa<InitListExpr>(E) << Ty << CT;
972     break;
973   }
974 }
975 
976 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
977 /// will create a trap if the resulting type is not a POD type.
978 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
979                                                   FunctionDecl *FDecl) {
980   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
981     // Strip the unbridged-cast placeholder expression off, if applicable.
982     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
983         (CT == VariadicMethod ||
984          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
985       E = stripARCUnbridgedCast(E);
986 
987     // Otherwise, do normal placeholder checking.
988     } else {
989       ExprResult ExprRes = CheckPlaceholderExpr(E);
990       if (ExprRes.isInvalid())
991         return ExprError();
992       E = ExprRes.get();
993     }
994   }
995 
996   ExprResult ExprRes = DefaultArgumentPromotion(E);
997   if (ExprRes.isInvalid())
998     return ExprError();
999 
1000   // Copy blocks to the heap.
1001   if (ExprRes.get()->getType()->isBlockPointerType())
1002     maybeExtendBlockObject(ExprRes);
1003 
1004   E = ExprRes.get();
1005 
1006   // Diagnostics regarding non-POD argument types are
1007   // emitted along with format string checking in Sema::CheckFunctionCall().
1008   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1009     // Turn this into a trap.
1010     CXXScopeSpec SS;
1011     SourceLocation TemplateKWLoc;
1012     UnqualifiedId Name;
1013     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1014                        E->getBeginLoc());
1015     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1016                                           /*HasTrailingLParen=*/true,
1017                                           /*IsAddressOfOperand=*/false);
1018     if (TrapFn.isInvalid())
1019       return ExprError();
1020 
1021     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1022                                     None, E->getEndLoc());
1023     if (Call.isInvalid())
1024       return ExprError();
1025 
1026     ExprResult Comma =
1027         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1028     if (Comma.isInvalid())
1029       return ExprError();
1030     return Comma.get();
1031   }
1032 
1033   if (!getLangOpts().CPlusPlus &&
1034       RequireCompleteType(E->getExprLoc(), E->getType(),
1035                           diag::err_call_incomplete_argument))
1036     return ExprError();
1037 
1038   return E;
1039 }
1040 
1041 /// Converts an integer to complex float type.  Helper function of
1042 /// UsualArithmeticConversions()
1043 ///
1044 /// \return false if the integer expression is an integer type and is
1045 /// successfully converted to the complex type.
1046 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1047                                                   ExprResult &ComplexExpr,
1048                                                   QualType IntTy,
1049                                                   QualType ComplexTy,
1050                                                   bool SkipCast) {
1051   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1052   if (SkipCast) return false;
1053   if (IntTy->isIntegerType()) {
1054     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1055     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1056     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1057                                   CK_FloatingRealToComplex);
1058   } else {
1059     assert(IntTy->isComplexIntegerType());
1060     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1061                                   CK_IntegralComplexToFloatingComplex);
1062   }
1063   return false;
1064 }
1065 
1066 /// Handle arithmetic conversion with complex types.  Helper function of
1067 /// UsualArithmeticConversions()
1068 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1069                                              ExprResult &RHS, QualType LHSType,
1070                                              QualType RHSType,
1071                                              bool IsCompAssign) {
1072   // if we have an integer operand, the result is the complex type.
1073   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1074                                              /*skipCast*/false))
1075     return LHSType;
1076   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1077                                              /*skipCast*/IsCompAssign))
1078     return RHSType;
1079 
1080   // This handles complex/complex, complex/float, or float/complex.
1081   // When both operands are complex, the shorter operand is converted to the
1082   // type of the longer, and that is the type of the result. This corresponds
1083   // to what is done when combining two real floating-point operands.
1084   // The fun begins when size promotion occur across type domains.
1085   // From H&S 6.3.4: When one operand is complex and the other is a real
1086   // floating-point type, the less precise type is converted, within it's
1087   // real or complex domain, to the precision of the other type. For example,
1088   // when combining a "long double" with a "double _Complex", the
1089   // "double _Complex" is promoted to "long double _Complex".
1090 
1091   // Compute the rank of the two types, regardless of whether they are complex.
1092   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1093 
1094   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1095   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1096   QualType LHSElementType =
1097       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1098   QualType RHSElementType =
1099       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1100 
1101   QualType ResultType = S.Context.getComplexType(LHSElementType);
1102   if (Order < 0) {
1103     // Promote the precision of the LHS if not an assignment.
1104     ResultType = S.Context.getComplexType(RHSElementType);
1105     if (!IsCompAssign) {
1106       if (LHSComplexType)
1107         LHS =
1108             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1109       else
1110         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1111     }
1112   } else if (Order > 0) {
1113     // Promote the precision of the RHS.
1114     if (RHSComplexType)
1115       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1116     else
1117       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1118   }
1119   return ResultType;
1120 }
1121 
1122 /// Handle arithmetic conversion from integer to float.  Helper function
1123 /// of UsualArithmeticConversions()
1124 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1125                                            ExprResult &IntExpr,
1126                                            QualType FloatTy, QualType IntTy,
1127                                            bool ConvertFloat, bool ConvertInt) {
1128   if (IntTy->isIntegerType()) {
1129     if (ConvertInt)
1130       // Convert intExpr to the lhs floating point type.
1131       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1132                                     CK_IntegralToFloating);
1133     return FloatTy;
1134   }
1135 
1136   // Convert both sides to the appropriate complex float.
1137   assert(IntTy->isComplexIntegerType());
1138   QualType result = S.Context.getComplexType(FloatTy);
1139 
1140   // _Complex int -> _Complex float
1141   if (ConvertInt)
1142     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1143                                   CK_IntegralComplexToFloatingComplex);
1144 
1145   // float -> _Complex float
1146   if (ConvertFloat)
1147     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1148                                     CK_FloatingRealToComplex);
1149 
1150   return result;
1151 }
1152 
1153 /// Handle arithmethic conversion with floating point types.  Helper
1154 /// function of UsualArithmeticConversions()
1155 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1156                                       ExprResult &RHS, QualType LHSType,
1157                                       QualType RHSType, bool IsCompAssign) {
1158   bool LHSFloat = LHSType->isRealFloatingType();
1159   bool RHSFloat = RHSType->isRealFloatingType();
1160 
1161   // N1169 4.1.4: If one of the operands has a floating type and the other
1162   //              operand has a fixed-point type, the fixed-point operand
1163   //              is converted to the floating type [...]
1164   if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1165     if (LHSFloat)
1166       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1167     else if (!IsCompAssign)
1168       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1169     return LHSFloat ? LHSType : RHSType;
1170   }
1171 
1172   // If we have two real floating types, convert the smaller operand
1173   // to the bigger result.
1174   if (LHSFloat && RHSFloat) {
1175     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1176     if (order > 0) {
1177       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1178       return LHSType;
1179     }
1180 
1181     assert(order < 0 && "illegal float comparison");
1182     if (!IsCompAssign)
1183       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1184     return RHSType;
1185   }
1186 
1187   if (LHSFloat) {
1188     // Half FP has to be promoted to float unless it is natively supported
1189     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1190       LHSType = S.Context.FloatTy;
1191 
1192     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1193                                       /*ConvertFloat=*/!IsCompAssign,
1194                                       /*ConvertInt=*/ true);
1195   }
1196   assert(RHSFloat);
1197   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1198                                     /*ConvertFloat=*/ true,
1199                                     /*ConvertInt=*/!IsCompAssign);
1200 }
1201 
1202 /// Diagnose attempts to convert between __float128, __ibm128 and
1203 /// long double if there is no support for such conversion.
1204 /// Helper function of UsualArithmeticConversions().
1205 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1206                                       QualType RHSType) {
1207   // No issue if either is not a floating point type.
1208   if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1209     return false;
1210 
1211   // No issue if both have the same 128-bit float semantics.
1212   auto *LHSComplex = LHSType->getAs<ComplexType>();
1213   auto *RHSComplex = RHSType->getAs<ComplexType>();
1214 
1215   QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1216   QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1217 
1218   const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1219   const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1220 
1221   if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1222        &RHSSem != &llvm::APFloat::IEEEquad()) &&
1223       (&LHSSem != &llvm::APFloat::IEEEquad() ||
1224        &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1225     return false;
1226 
1227   return true;
1228 }
1229 
1230 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1231 
1232 namespace {
1233 /// These helper callbacks are placed in an anonymous namespace to
1234 /// permit their use as function template parameters.
1235 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1236   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1237 }
1238 
1239 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1240   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1241                              CK_IntegralComplexCast);
1242 }
1243 }
1244 
1245 /// Handle integer arithmetic conversions.  Helper function of
1246 /// UsualArithmeticConversions()
1247 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1248 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1249                                         ExprResult &RHS, QualType LHSType,
1250                                         QualType RHSType, bool IsCompAssign) {
1251   // The rules for this case are in C99 6.3.1.8
1252   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1253   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1254   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1255   if (LHSSigned == RHSSigned) {
1256     // Same signedness; use the higher-ranked type
1257     if (order >= 0) {
1258       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1259       return LHSType;
1260     } else if (!IsCompAssign)
1261       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1262     return RHSType;
1263   } else if (order != (LHSSigned ? 1 : -1)) {
1264     // The unsigned type has greater than or equal rank to the
1265     // signed type, so use the unsigned type
1266     if (RHSSigned) {
1267       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1268       return LHSType;
1269     } else if (!IsCompAssign)
1270       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1271     return RHSType;
1272   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1273     // The two types are different widths; if we are here, that
1274     // means the signed type is larger than the unsigned type, so
1275     // use the signed type.
1276     if (LHSSigned) {
1277       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1278       return LHSType;
1279     } else if (!IsCompAssign)
1280       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1281     return RHSType;
1282   } else {
1283     // The signed type is higher-ranked than the unsigned type,
1284     // but isn't actually any bigger (like unsigned int and long
1285     // on most 32-bit systems).  Use the unsigned type corresponding
1286     // to the signed type.
1287     QualType result =
1288       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1289     RHS = (*doRHSCast)(S, RHS.get(), result);
1290     if (!IsCompAssign)
1291       LHS = (*doLHSCast)(S, LHS.get(), result);
1292     return result;
1293   }
1294 }
1295 
1296 /// Handle conversions with GCC complex int extension.  Helper function
1297 /// of UsualArithmeticConversions()
1298 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1299                                            ExprResult &RHS, QualType LHSType,
1300                                            QualType RHSType,
1301                                            bool IsCompAssign) {
1302   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1303   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1304 
1305   if (LHSComplexInt && RHSComplexInt) {
1306     QualType LHSEltType = LHSComplexInt->getElementType();
1307     QualType RHSEltType = RHSComplexInt->getElementType();
1308     QualType ScalarType =
1309       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1310         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1311 
1312     return S.Context.getComplexType(ScalarType);
1313   }
1314 
1315   if (LHSComplexInt) {
1316     QualType LHSEltType = LHSComplexInt->getElementType();
1317     QualType ScalarType =
1318       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1319         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1320     QualType ComplexType = S.Context.getComplexType(ScalarType);
1321     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1322                               CK_IntegralRealToComplex);
1323 
1324     return ComplexType;
1325   }
1326 
1327   assert(RHSComplexInt);
1328 
1329   QualType RHSEltType = RHSComplexInt->getElementType();
1330   QualType ScalarType =
1331     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1332       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1333   QualType ComplexType = S.Context.getComplexType(ScalarType);
1334 
1335   if (!IsCompAssign)
1336     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1337                               CK_IntegralRealToComplex);
1338   return ComplexType;
1339 }
1340 
1341 /// Return the rank of a given fixed point or integer type. The value itself
1342 /// doesn't matter, but the values must be increasing with proper increasing
1343 /// rank as described in N1169 4.1.1.
1344 static unsigned GetFixedPointRank(QualType Ty) {
1345   const auto *BTy = Ty->getAs<BuiltinType>();
1346   assert(BTy && "Expected a builtin type.");
1347 
1348   switch (BTy->getKind()) {
1349   case BuiltinType::ShortFract:
1350   case BuiltinType::UShortFract:
1351   case BuiltinType::SatShortFract:
1352   case BuiltinType::SatUShortFract:
1353     return 1;
1354   case BuiltinType::Fract:
1355   case BuiltinType::UFract:
1356   case BuiltinType::SatFract:
1357   case BuiltinType::SatUFract:
1358     return 2;
1359   case BuiltinType::LongFract:
1360   case BuiltinType::ULongFract:
1361   case BuiltinType::SatLongFract:
1362   case BuiltinType::SatULongFract:
1363     return 3;
1364   case BuiltinType::ShortAccum:
1365   case BuiltinType::UShortAccum:
1366   case BuiltinType::SatShortAccum:
1367   case BuiltinType::SatUShortAccum:
1368     return 4;
1369   case BuiltinType::Accum:
1370   case BuiltinType::UAccum:
1371   case BuiltinType::SatAccum:
1372   case BuiltinType::SatUAccum:
1373     return 5;
1374   case BuiltinType::LongAccum:
1375   case BuiltinType::ULongAccum:
1376   case BuiltinType::SatLongAccum:
1377   case BuiltinType::SatULongAccum:
1378     return 6;
1379   default:
1380     if (BTy->isInteger())
1381       return 0;
1382     llvm_unreachable("Unexpected fixed point or integer type");
1383   }
1384 }
1385 
1386 /// handleFixedPointConversion - Fixed point operations between fixed
1387 /// point types and integers or other fixed point types do not fall under
1388 /// usual arithmetic conversion since these conversions could result in loss
1389 /// of precsision (N1169 4.1.4). These operations should be calculated with
1390 /// the full precision of their result type (N1169 4.1.6.2.1).
1391 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1392                                            QualType RHSTy) {
1393   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1394          "Expected at least one of the operands to be a fixed point type");
1395   assert((LHSTy->isFixedPointOrIntegerType() ||
1396           RHSTy->isFixedPointOrIntegerType()) &&
1397          "Special fixed point arithmetic operation conversions are only "
1398          "applied to ints or other fixed point types");
1399 
1400   // If one operand has signed fixed-point type and the other operand has
1401   // unsigned fixed-point type, then the unsigned fixed-point operand is
1402   // converted to its corresponding signed fixed-point type and the resulting
1403   // type is the type of the converted operand.
1404   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1405     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1406   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1407     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1408 
1409   // The result type is the type with the highest rank, whereby a fixed-point
1410   // conversion rank is always greater than an integer conversion rank; if the
1411   // type of either of the operands is a saturating fixedpoint type, the result
1412   // type shall be the saturating fixed-point type corresponding to the type
1413   // with the highest rank; the resulting value is converted (taking into
1414   // account rounding and overflow) to the precision of the resulting type.
1415   // Same ranks between signed and unsigned types are resolved earlier, so both
1416   // types are either signed or both unsigned at this point.
1417   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1418   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1419 
1420   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1421 
1422   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1423     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1424 
1425   return ResultTy;
1426 }
1427 
1428 /// Check that the usual arithmetic conversions can be performed on this pair of
1429 /// expressions that might be of enumeration type.
1430 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1431                                            SourceLocation Loc,
1432                                            Sema::ArithConvKind ACK) {
1433   // C++2a [expr.arith.conv]p1:
1434   //   If one operand is of enumeration type and the other operand is of a
1435   //   different enumeration type or a floating-point type, this behavior is
1436   //   deprecated ([depr.arith.conv.enum]).
1437   //
1438   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1439   // Eventually we will presumably reject these cases (in C++23 onwards?).
1440   QualType L = LHS->getType(), R = RHS->getType();
1441   bool LEnum = L->isUnscopedEnumerationType(),
1442        REnum = R->isUnscopedEnumerationType();
1443   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1444   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1445       (REnum && L->isFloatingType())) {
1446     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1447                     ? diag::warn_arith_conv_enum_float_cxx20
1448                     : diag::warn_arith_conv_enum_float)
1449         << LHS->getSourceRange() << RHS->getSourceRange()
1450         << (int)ACK << LEnum << L << R;
1451   } else if (!IsCompAssign && LEnum && REnum &&
1452              !S.Context.hasSameUnqualifiedType(L, R)) {
1453     unsigned DiagID;
1454     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1455         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1456       // If either enumeration type is unnamed, it's less likely that the
1457       // user cares about this, but this situation is still deprecated in
1458       // C++2a. Use a different warning group.
1459       DiagID = S.getLangOpts().CPlusPlus20
1460                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1461                     : diag::warn_arith_conv_mixed_anon_enum_types;
1462     } else if (ACK == Sema::ACK_Conditional) {
1463       // Conditional expressions are separated out because they have
1464       // historically had a different warning flag.
1465       DiagID = S.getLangOpts().CPlusPlus20
1466                    ? diag::warn_conditional_mixed_enum_types_cxx20
1467                    : diag::warn_conditional_mixed_enum_types;
1468     } else if (ACK == Sema::ACK_Comparison) {
1469       // Comparison expressions are separated out because they have
1470       // historically had a different warning flag.
1471       DiagID = S.getLangOpts().CPlusPlus20
1472                    ? diag::warn_comparison_mixed_enum_types_cxx20
1473                    : diag::warn_comparison_mixed_enum_types;
1474     } else {
1475       DiagID = S.getLangOpts().CPlusPlus20
1476                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1477                    : diag::warn_arith_conv_mixed_enum_types;
1478     }
1479     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1480                         << (int)ACK << L << R;
1481   }
1482 }
1483 
1484 /// UsualArithmeticConversions - Performs various conversions that are common to
1485 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1486 /// routine returns the first non-arithmetic type found. The client is
1487 /// responsible for emitting appropriate error diagnostics.
1488 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1489                                           SourceLocation Loc,
1490                                           ArithConvKind ACK) {
1491   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1492 
1493   if (ACK != ACK_CompAssign) {
1494     LHS = UsualUnaryConversions(LHS.get());
1495     if (LHS.isInvalid())
1496       return QualType();
1497   }
1498 
1499   RHS = UsualUnaryConversions(RHS.get());
1500   if (RHS.isInvalid())
1501     return QualType();
1502 
1503   // For conversion purposes, we ignore any qualifiers.
1504   // For example, "const float" and "float" are equivalent.
1505   QualType LHSType =
1506     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1507   QualType RHSType =
1508     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1509 
1510   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1511   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1512     LHSType = AtomicLHS->getValueType();
1513 
1514   // If both types are identical, no conversion is needed.
1515   if (LHSType == RHSType)
1516     return LHSType;
1517 
1518   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1519   // The caller can deal with this (e.g. pointer + int).
1520   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1521     return QualType();
1522 
1523   // Apply unary and bitfield promotions to the LHS's type.
1524   QualType LHSUnpromotedType = LHSType;
1525   if (LHSType->isPromotableIntegerType())
1526     LHSType = Context.getPromotedIntegerType(LHSType);
1527   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1528   if (!LHSBitfieldPromoteTy.isNull())
1529     LHSType = LHSBitfieldPromoteTy;
1530   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1531     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1532 
1533   // If both types are identical, no conversion is needed.
1534   if (LHSType == RHSType)
1535     return LHSType;
1536 
1537   // At this point, we have two different arithmetic types.
1538 
1539   // Diagnose attempts to convert between __ibm128, __float128 and long double
1540   // where such conversions currently can't be handled.
1541   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1542     return QualType();
1543 
1544   // Handle complex types first (C99 6.3.1.8p1).
1545   if (LHSType->isComplexType() || RHSType->isComplexType())
1546     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1547                                         ACK == ACK_CompAssign);
1548 
1549   // Now handle "real" floating types (i.e. float, double, long double).
1550   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1551     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1552                                  ACK == ACK_CompAssign);
1553 
1554   // Handle GCC complex int extension.
1555   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1556     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1557                                       ACK == ACK_CompAssign);
1558 
1559   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1560     return handleFixedPointConversion(*this, LHSType, RHSType);
1561 
1562   // Finally, we have two differing integer types.
1563   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1564            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1565 }
1566 
1567 //===----------------------------------------------------------------------===//
1568 //  Semantic Analysis for various Expression Types
1569 //===----------------------------------------------------------------------===//
1570 
1571 
1572 ExprResult
1573 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1574                                 SourceLocation DefaultLoc,
1575                                 SourceLocation RParenLoc,
1576                                 Expr *ControllingExpr,
1577                                 ArrayRef<ParsedType> ArgTypes,
1578                                 ArrayRef<Expr *> ArgExprs) {
1579   unsigned NumAssocs = ArgTypes.size();
1580   assert(NumAssocs == ArgExprs.size());
1581 
1582   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1583   for (unsigned i = 0; i < NumAssocs; ++i) {
1584     if (ArgTypes[i])
1585       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1586     else
1587       Types[i] = nullptr;
1588   }
1589 
1590   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1591                                              ControllingExpr,
1592                                              llvm::makeArrayRef(Types, NumAssocs),
1593                                              ArgExprs);
1594   delete [] Types;
1595   return ER;
1596 }
1597 
1598 ExprResult
1599 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1600                                  SourceLocation DefaultLoc,
1601                                  SourceLocation RParenLoc,
1602                                  Expr *ControllingExpr,
1603                                  ArrayRef<TypeSourceInfo *> Types,
1604                                  ArrayRef<Expr *> Exprs) {
1605   unsigned NumAssocs = Types.size();
1606   assert(NumAssocs == Exprs.size());
1607 
1608   // Decay and strip qualifiers for the controlling expression type, and handle
1609   // placeholder type replacement. See committee discussion from WG14 DR423.
1610   {
1611     EnterExpressionEvaluationContext Unevaluated(
1612         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1613     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1614     if (R.isInvalid())
1615       return ExprError();
1616     ControllingExpr = R.get();
1617   }
1618 
1619   // The controlling expression is an unevaluated operand, so side effects are
1620   // likely unintended.
1621   if (!inTemplateInstantiation() &&
1622       ControllingExpr->HasSideEffects(Context, false))
1623     Diag(ControllingExpr->getExprLoc(),
1624          diag::warn_side_effects_unevaluated_context);
1625 
1626   bool TypeErrorFound = false,
1627        IsResultDependent = ControllingExpr->isTypeDependent(),
1628        ContainsUnexpandedParameterPack
1629          = ControllingExpr->containsUnexpandedParameterPack();
1630 
1631   for (unsigned i = 0; i < NumAssocs; ++i) {
1632     if (Exprs[i]->containsUnexpandedParameterPack())
1633       ContainsUnexpandedParameterPack = true;
1634 
1635     if (Types[i]) {
1636       if (Types[i]->getType()->containsUnexpandedParameterPack())
1637         ContainsUnexpandedParameterPack = true;
1638 
1639       if (Types[i]->getType()->isDependentType()) {
1640         IsResultDependent = true;
1641       } else {
1642         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1643         // complete object type other than a variably modified type."
1644         unsigned D = 0;
1645         if (Types[i]->getType()->isIncompleteType())
1646           D = diag::err_assoc_type_incomplete;
1647         else if (!Types[i]->getType()->isObjectType())
1648           D = diag::err_assoc_type_nonobject;
1649         else if (Types[i]->getType()->isVariablyModifiedType())
1650           D = diag::err_assoc_type_variably_modified;
1651 
1652         if (D != 0) {
1653           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1654             << Types[i]->getTypeLoc().getSourceRange()
1655             << Types[i]->getType();
1656           TypeErrorFound = true;
1657         }
1658 
1659         // C11 6.5.1.1p2 "No two generic associations in the same generic
1660         // selection shall specify compatible types."
1661         for (unsigned j = i+1; j < NumAssocs; ++j)
1662           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1663               Context.typesAreCompatible(Types[i]->getType(),
1664                                          Types[j]->getType())) {
1665             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1666                  diag::err_assoc_compatible_types)
1667               << Types[j]->getTypeLoc().getSourceRange()
1668               << Types[j]->getType()
1669               << Types[i]->getType();
1670             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1671                  diag::note_compat_assoc)
1672               << Types[i]->getTypeLoc().getSourceRange()
1673               << Types[i]->getType();
1674             TypeErrorFound = true;
1675           }
1676       }
1677     }
1678   }
1679   if (TypeErrorFound)
1680     return ExprError();
1681 
1682   // If we determined that the generic selection is result-dependent, don't
1683   // try to compute the result expression.
1684   if (IsResultDependent)
1685     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1686                                         Exprs, DefaultLoc, RParenLoc,
1687                                         ContainsUnexpandedParameterPack);
1688 
1689   SmallVector<unsigned, 1> CompatIndices;
1690   unsigned DefaultIndex = -1U;
1691   for (unsigned i = 0; i < NumAssocs; ++i) {
1692     if (!Types[i])
1693       DefaultIndex = i;
1694     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1695                                         Types[i]->getType()))
1696       CompatIndices.push_back(i);
1697   }
1698 
1699   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1700   // type compatible with at most one of the types named in its generic
1701   // association list."
1702   if (CompatIndices.size() > 1) {
1703     // We strip parens here because the controlling expression is typically
1704     // parenthesized in macro definitions.
1705     ControllingExpr = ControllingExpr->IgnoreParens();
1706     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1707         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1708         << (unsigned)CompatIndices.size();
1709     for (unsigned I : CompatIndices) {
1710       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1711            diag::note_compat_assoc)
1712         << Types[I]->getTypeLoc().getSourceRange()
1713         << Types[I]->getType();
1714     }
1715     return ExprError();
1716   }
1717 
1718   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1719   // its controlling expression shall have type compatible with exactly one of
1720   // the types named in its generic association list."
1721   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1722     // We strip parens here because the controlling expression is typically
1723     // parenthesized in macro definitions.
1724     ControllingExpr = ControllingExpr->IgnoreParens();
1725     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1726         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1727     return ExprError();
1728   }
1729 
1730   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1731   // type name that is compatible with the type of the controlling expression,
1732   // then the result expression of the generic selection is the expression
1733   // in that generic association. Otherwise, the result expression of the
1734   // generic selection is the expression in the default generic association."
1735   unsigned ResultIndex =
1736     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1737 
1738   return GenericSelectionExpr::Create(
1739       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1740       ContainsUnexpandedParameterPack, ResultIndex);
1741 }
1742 
1743 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1744 /// location of the token and the offset of the ud-suffix within it.
1745 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1746                                      unsigned Offset) {
1747   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1748                                         S.getLangOpts());
1749 }
1750 
1751 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1752 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1753 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1754                                                  IdentifierInfo *UDSuffix,
1755                                                  SourceLocation UDSuffixLoc,
1756                                                  ArrayRef<Expr*> Args,
1757                                                  SourceLocation LitEndLoc) {
1758   assert(Args.size() <= 2 && "too many arguments for literal operator");
1759 
1760   QualType ArgTy[2];
1761   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1762     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1763     if (ArgTy[ArgIdx]->isArrayType())
1764       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1765   }
1766 
1767   DeclarationName OpName =
1768     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1769   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1770   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1771 
1772   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1773   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1774                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1775                               /*AllowStringTemplatePack*/ false,
1776                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1777     return ExprError();
1778 
1779   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1780 }
1781 
1782 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1783 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1784 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1785 /// multiple tokens.  However, the common case is that StringToks points to one
1786 /// string.
1787 ///
1788 ExprResult
1789 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1790   assert(!StringToks.empty() && "Must have at least one string!");
1791 
1792   StringLiteralParser Literal(StringToks, PP);
1793   if (Literal.hadError)
1794     return ExprError();
1795 
1796   SmallVector<SourceLocation, 4> StringTokLocs;
1797   for (const Token &Tok : StringToks)
1798     StringTokLocs.push_back(Tok.getLocation());
1799 
1800   QualType CharTy = Context.CharTy;
1801   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1802   if (Literal.isWide()) {
1803     CharTy = Context.getWideCharType();
1804     Kind = StringLiteral::Wide;
1805   } else if (Literal.isUTF8()) {
1806     if (getLangOpts().Char8)
1807       CharTy = Context.Char8Ty;
1808     Kind = StringLiteral::UTF8;
1809   } else if (Literal.isUTF16()) {
1810     CharTy = Context.Char16Ty;
1811     Kind = StringLiteral::UTF16;
1812   } else if (Literal.isUTF32()) {
1813     CharTy = Context.Char32Ty;
1814     Kind = StringLiteral::UTF32;
1815   } else if (Literal.isPascal()) {
1816     CharTy = Context.UnsignedCharTy;
1817   }
1818 
1819   // Warn on initializing an array of char from a u8 string literal; this
1820   // becomes ill-formed in C++2a.
1821   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1822       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1823     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1824 
1825     // Create removals for all 'u8' prefixes in the string literal(s). This
1826     // ensures C++2a compatibility (but may change the program behavior when
1827     // built by non-Clang compilers for which the execution character set is
1828     // not always UTF-8).
1829     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1830     SourceLocation RemovalDiagLoc;
1831     for (const Token &Tok : StringToks) {
1832       if (Tok.getKind() == tok::utf8_string_literal) {
1833         if (RemovalDiagLoc.isInvalid())
1834           RemovalDiagLoc = Tok.getLocation();
1835         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1836             Tok.getLocation(),
1837             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1838                                            getSourceManager(), getLangOpts())));
1839       }
1840     }
1841     Diag(RemovalDiagLoc, RemovalDiag);
1842   }
1843 
1844   QualType StrTy =
1845       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1846 
1847   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1848   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1849                                              Kind, Literal.Pascal, StrTy,
1850                                              &StringTokLocs[0],
1851                                              StringTokLocs.size());
1852   if (Literal.getUDSuffix().empty())
1853     return Lit;
1854 
1855   // We're building a user-defined literal.
1856   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1857   SourceLocation UDSuffixLoc =
1858     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1859                    Literal.getUDSuffixOffset());
1860 
1861   // Make sure we're allowed user-defined literals here.
1862   if (!UDLScope)
1863     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1864 
1865   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1866   //   operator "" X (str, len)
1867   QualType SizeType = Context.getSizeType();
1868 
1869   DeclarationName OpName =
1870     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1871   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1872   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1873 
1874   QualType ArgTy[] = {
1875     Context.getArrayDecayedType(StrTy), SizeType
1876   };
1877 
1878   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1879   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1880                                 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1881                                 /*AllowStringTemplatePack*/ true,
1882                                 /*DiagnoseMissing*/ true, Lit)) {
1883 
1884   case LOLR_Cooked: {
1885     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1886     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1887                                                     StringTokLocs[0]);
1888     Expr *Args[] = { Lit, LenArg };
1889 
1890     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1891   }
1892 
1893   case LOLR_Template: {
1894     TemplateArgumentListInfo ExplicitArgs;
1895     TemplateArgument Arg(Lit);
1896     TemplateArgumentLocInfo ArgInfo(Lit);
1897     ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1898     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1899                                     &ExplicitArgs);
1900   }
1901 
1902   case LOLR_StringTemplatePack: {
1903     TemplateArgumentListInfo ExplicitArgs;
1904 
1905     unsigned CharBits = Context.getIntWidth(CharTy);
1906     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1907     llvm::APSInt Value(CharBits, CharIsUnsigned);
1908 
1909     TemplateArgument TypeArg(CharTy);
1910     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1911     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1912 
1913     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1914       Value = Lit->getCodeUnit(I);
1915       TemplateArgument Arg(Context, Value, CharTy);
1916       TemplateArgumentLocInfo ArgInfo;
1917       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1918     }
1919     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1920                                     &ExplicitArgs);
1921   }
1922   case LOLR_Raw:
1923   case LOLR_ErrorNoDiagnostic:
1924     llvm_unreachable("unexpected literal operator lookup result");
1925   case LOLR_Error:
1926     return ExprError();
1927   }
1928   llvm_unreachable("unexpected literal operator lookup result");
1929 }
1930 
1931 DeclRefExpr *
1932 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1933                        SourceLocation Loc,
1934                        const CXXScopeSpec *SS) {
1935   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1936   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1937 }
1938 
1939 DeclRefExpr *
1940 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1941                        const DeclarationNameInfo &NameInfo,
1942                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1943                        SourceLocation TemplateKWLoc,
1944                        const TemplateArgumentListInfo *TemplateArgs) {
1945   NestedNameSpecifierLoc NNS =
1946       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1947   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1948                           TemplateArgs);
1949 }
1950 
1951 // CUDA/HIP: Check whether a captured reference variable is referencing a
1952 // host variable in a device or host device lambda.
1953 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1954                                                             VarDecl *VD) {
1955   if (!S.getLangOpts().CUDA || !VD->hasInit())
1956     return false;
1957   assert(VD->getType()->isReferenceType());
1958 
1959   // Check whether the reference variable is referencing a host variable.
1960   auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1961   if (!DRE)
1962     return false;
1963   auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
1964   if (!Referee || !Referee->hasGlobalStorage() ||
1965       Referee->hasAttr<CUDADeviceAttr>())
1966     return false;
1967 
1968   // Check whether the current function is a device or host device lambda.
1969   // Check whether the reference variable is a capture by getDeclContext()
1970   // since refersToEnclosingVariableOrCapture() is not ready at this point.
1971   auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
1972   if (MD && MD->getParent()->isLambda() &&
1973       MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
1974       VD->getDeclContext() != MD)
1975     return true;
1976 
1977   return false;
1978 }
1979 
1980 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1981   // A declaration named in an unevaluated operand never constitutes an odr-use.
1982   if (isUnevaluatedContext())
1983     return NOUR_Unevaluated;
1984 
1985   // C++2a [basic.def.odr]p4:
1986   //   A variable x whose name appears as a potentially-evaluated expression e
1987   //   is odr-used by e unless [...] x is a reference that is usable in
1988   //   constant expressions.
1989   // CUDA/HIP:
1990   //   If a reference variable referencing a host variable is captured in a
1991   //   device or host device lambda, the value of the referee must be copied
1992   //   to the capture and the reference variable must be treated as odr-use
1993   //   since the value of the referee is not known at compile time and must
1994   //   be loaded from the captured.
1995   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1996     if (VD->getType()->isReferenceType() &&
1997         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1998         !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
1999         VD->isUsableInConstantExpressions(Context))
2000       return NOUR_Constant;
2001   }
2002 
2003   // All remaining non-variable cases constitute an odr-use. For variables, we
2004   // need to wait and see how the expression is used.
2005   return NOUR_None;
2006 }
2007 
2008 /// BuildDeclRefExpr - Build an expression that references a
2009 /// declaration that does not require a closure capture.
2010 DeclRefExpr *
2011 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2012                        const DeclarationNameInfo &NameInfo,
2013                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2014                        SourceLocation TemplateKWLoc,
2015                        const TemplateArgumentListInfo *TemplateArgs) {
2016   bool RefersToCapturedVariable =
2017       isa<VarDecl>(D) &&
2018       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2019 
2020   DeclRefExpr *E = DeclRefExpr::Create(
2021       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2022       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2023   MarkDeclRefReferenced(E);
2024 
2025   // C++ [except.spec]p17:
2026   //   An exception-specification is considered to be needed when:
2027   //   - in an expression, the function is the unique lookup result or
2028   //     the selected member of a set of overloaded functions.
2029   //
2030   // We delay doing this until after we've built the function reference and
2031   // marked it as used so that:
2032   //  a) if the function is defaulted, we get errors from defining it before /
2033   //     instead of errors from computing its exception specification, and
2034   //  b) if the function is a defaulted comparison, we can use the body we
2035   //     build when defining it as input to the exception specification
2036   //     computation rather than computing a new body.
2037   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2038     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2039       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2040         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2041     }
2042   }
2043 
2044   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2045       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2046       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2047     getCurFunction()->recordUseOfWeak(E);
2048 
2049   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2050   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2051     FD = IFD->getAnonField();
2052   if (FD) {
2053     UnusedPrivateFields.remove(FD);
2054     // Just in case we're building an illegal pointer-to-member.
2055     if (FD->isBitField())
2056       E->setObjectKind(OK_BitField);
2057   }
2058 
2059   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2060   // designates a bit-field.
2061   if (auto *BD = dyn_cast<BindingDecl>(D))
2062     if (auto *BE = BD->getBinding())
2063       E->setObjectKind(BE->getObjectKind());
2064 
2065   return E;
2066 }
2067 
2068 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2069 /// possibly a list of template arguments.
2070 ///
2071 /// If this produces template arguments, it is permitted to call
2072 /// DecomposeTemplateName.
2073 ///
2074 /// This actually loses a lot of source location information for
2075 /// non-standard name kinds; we should consider preserving that in
2076 /// some way.
2077 void
2078 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2079                              TemplateArgumentListInfo &Buffer,
2080                              DeclarationNameInfo &NameInfo,
2081                              const TemplateArgumentListInfo *&TemplateArgs) {
2082   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2083     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2084     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2085 
2086     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2087                                        Id.TemplateId->NumArgs);
2088     translateTemplateArguments(TemplateArgsPtr, Buffer);
2089 
2090     TemplateName TName = Id.TemplateId->Template.get();
2091     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2092     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2093     TemplateArgs = &Buffer;
2094   } else {
2095     NameInfo = GetNameFromUnqualifiedId(Id);
2096     TemplateArgs = nullptr;
2097   }
2098 }
2099 
2100 static void emitEmptyLookupTypoDiagnostic(
2101     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2102     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2103     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2104   DeclContext *Ctx =
2105       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2106   if (!TC) {
2107     // Emit a special diagnostic for failed member lookups.
2108     // FIXME: computing the declaration context might fail here (?)
2109     if (Ctx)
2110       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2111                                                  << SS.getRange();
2112     else
2113       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2114     return;
2115   }
2116 
2117   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2118   bool DroppedSpecifier =
2119       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2120   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2121                         ? diag::note_implicit_param_decl
2122                         : diag::note_previous_decl;
2123   if (!Ctx)
2124     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2125                          SemaRef.PDiag(NoteID));
2126   else
2127     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2128                                  << Typo << Ctx << DroppedSpecifier
2129                                  << SS.getRange(),
2130                          SemaRef.PDiag(NoteID));
2131 }
2132 
2133 /// Diagnose a lookup that found results in an enclosing class during error
2134 /// recovery. This usually indicates that the results were found in a dependent
2135 /// base class that could not be searched as part of a template definition.
2136 /// Always issues a diagnostic (though this may be only a warning in MS
2137 /// compatibility mode).
2138 ///
2139 /// Return \c true if the error is unrecoverable, or \c false if the caller
2140 /// should attempt to recover using these lookup results.
2141 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2142   // During a default argument instantiation the CurContext points
2143   // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2144   // function parameter list, hence add an explicit check.
2145   bool isDefaultArgument =
2146       !CodeSynthesisContexts.empty() &&
2147       CodeSynthesisContexts.back().Kind ==
2148           CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2149   CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2150   bool isInstance = CurMethod && CurMethod->isInstance() &&
2151                     R.getNamingClass() == CurMethod->getParent() &&
2152                     !isDefaultArgument;
2153 
2154   // There are two ways we can find a class-scope declaration during template
2155   // instantiation that we did not find in the template definition: if it is a
2156   // member of a dependent base class, or if it is declared after the point of
2157   // use in the same class. Distinguish these by comparing the class in which
2158   // the member was found to the naming class of the lookup.
2159   unsigned DiagID = diag::err_found_in_dependent_base;
2160   unsigned NoteID = diag::note_member_declared_at;
2161   if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2162     DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2163                                       : diag::err_found_later_in_class;
2164   } else if (getLangOpts().MSVCCompat) {
2165     DiagID = diag::ext_found_in_dependent_base;
2166     NoteID = diag::note_dependent_member_use;
2167   }
2168 
2169   if (isInstance) {
2170     // Give a code modification hint to insert 'this->'.
2171     Diag(R.getNameLoc(), DiagID)
2172         << R.getLookupName()
2173         << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2174     CheckCXXThisCapture(R.getNameLoc());
2175   } else {
2176     // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2177     // they're not shadowed).
2178     Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2179   }
2180 
2181   for (NamedDecl *D : R)
2182     Diag(D->getLocation(), NoteID);
2183 
2184   // Return true if we are inside a default argument instantiation
2185   // and the found name refers to an instance member function, otherwise
2186   // the caller will try to create an implicit member call and this is wrong
2187   // for default arguments.
2188   //
2189   // FIXME: Is this special case necessary? We could allow the caller to
2190   // diagnose this.
2191   if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2192     Diag(R.getNameLoc(), diag::err_member_call_without_object);
2193     return true;
2194   }
2195 
2196   // Tell the callee to try to recover.
2197   return false;
2198 }
2199 
2200 /// Diagnose an empty lookup.
2201 ///
2202 /// \return false if new lookup candidates were found
2203 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2204                                CorrectionCandidateCallback &CCC,
2205                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2206                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2207   DeclarationName Name = R.getLookupName();
2208 
2209   unsigned diagnostic = diag::err_undeclared_var_use;
2210   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2211   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2212       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2213       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2214     diagnostic = diag::err_undeclared_use;
2215     diagnostic_suggest = diag::err_undeclared_use_suggest;
2216   }
2217 
2218   // If the original lookup was an unqualified lookup, fake an
2219   // unqualified lookup.  This is useful when (for example) the
2220   // original lookup would not have found something because it was a
2221   // dependent name.
2222   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2223   while (DC) {
2224     if (isa<CXXRecordDecl>(DC)) {
2225       LookupQualifiedName(R, DC);
2226 
2227       if (!R.empty()) {
2228         // Don't give errors about ambiguities in this lookup.
2229         R.suppressDiagnostics();
2230 
2231         // If there's a best viable function among the results, only mention
2232         // that one in the notes.
2233         OverloadCandidateSet Candidates(R.getNameLoc(),
2234                                         OverloadCandidateSet::CSK_Normal);
2235         AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2236         OverloadCandidateSet::iterator Best;
2237         if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2238             OR_Success) {
2239           R.clear();
2240           R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2241           R.resolveKind();
2242         }
2243 
2244         return DiagnoseDependentMemberLookup(R);
2245       }
2246 
2247       R.clear();
2248     }
2249 
2250     DC = DC->getLookupParent();
2251   }
2252 
2253   // We didn't find anything, so try to correct for a typo.
2254   TypoCorrection Corrected;
2255   if (S && Out) {
2256     SourceLocation TypoLoc = R.getNameLoc();
2257     assert(!ExplicitTemplateArgs &&
2258            "Diagnosing an empty lookup with explicit template args!");
2259     *Out = CorrectTypoDelayed(
2260         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2261         [=](const TypoCorrection &TC) {
2262           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2263                                         diagnostic, diagnostic_suggest);
2264         },
2265         nullptr, CTK_ErrorRecovery);
2266     if (*Out)
2267       return true;
2268   } else if (S &&
2269              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2270                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2271     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2272     bool DroppedSpecifier =
2273         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2274     R.setLookupName(Corrected.getCorrection());
2275 
2276     bool AcceptableWithRecovery = false;
2277     bool AcceptableWithoutRecovery = false;
2278     NamedDecl *ND = Corrected.getFoundDecl();
2279     if (ND) {
2280       if (Corrected.isOverloaded()) {
2281         OverloadCandidateSet OCS(R.getNameLoc(),
2282                                  OverloadCandidateSet::CSK_Normal);
2283         OverloadCandidateSet::iterator Best;
2284         for (NamedDecl *CD : Corrected) {
2285           if (FunctionTemplateDecl *FTD =
2286                    dyn_cast<FunctionTemplateDecl>(CD))
2287             AddTemplateOverloadCandidate(
2288                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2289                 Args, OCS);
2290           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2291             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2292               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2293                                    Args, OCS);
2294         }
2295         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2296         case OR_Success:
2297           ND = Best->FoundDecl;
2298           Corrected.setCorrectionDecl(ND);
2299           break;
2300         default:
2301           // FIXME: Arbitrarily pick the first declaration for the note.
2302           Corrected.setCorrectionDecl(ND);
2303           break;
2304         }
2305       }
2306       R.addDecl(ND);
2307       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2308         CXXRecordDecl *Record = nullptr;
2309         if (Corrected.getCorrectionSpecifier()) {
2310           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2311           Record = Ty->getAsCXXRecordDecl();
2312         }
2313         if (!Record)
2314           Record = cast<CXXRecordDecl>(
2315               ND->getDeclContext()->getRedeclContext());
2316         R.setNamingClass(Record);
2317       }
2318 
2319       auto *UnderlyingND = ND->getUnderlyingDecl();
2320       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2321                                isa<FunctionTemplateDecl>(UnderlyingND);
2322       // FIXME: If we ended up with a typo for a type name or
2323       // Objective-C class name, we're in trouble because the parser
2324       // is in the wrong place to recover. Suggest the typo
2325       // correction, but don't make it a fix-it since we're not going
2326       // to recover well anyway.
2327       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2328                                   getAsTypeTemplateDecl(UnderlyingND) ||
2329                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2330     } else {
2331       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2332       // because we aren't able to recover.
2333       AcceptableWithoutRecovery = true;
2334     }
2335 
2336     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2337       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2338                             ? diag::note_implicit_param_decl
2339                             : diag::note_previous_decl;
2340       if (SS.isEmpty())
2341         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2342                      PDiag(NoteID), AcceptableWithRecovery);
2343       else
2344         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2345                                   << Name << computeDeclContext(SS, false)
2346                                   << DroppedSpecifier << SS.getRange(),
2347                      PDiag(NoteID), AcceptableWithRecovery);
2348 
2349       // Tell the callee whether to try to recover.
2350       return !AcceptableWithRecovery;
2351     }
2352   }
2353   R.clear();
2354 
2355   // Emit a special diagnostic for failed member lookups.
2356   // FIXME: computing the declaration context might fail here (?)
2357   if (!SS.isEmpty()) {
2358     Diag(R.getNameLoc(), diag::err_no_member)
2359       << Name << computeDeclContext(SS, false)
2360       << SS.getRange();
2361     return true;
2362   }
2363 
2364   // Give up, we can't recover.
2365   Diag(R.getNameLoc(), diagnostic) << Name;
2366   return true;
2367 }
2368 
2369 /// In Microsoft mode, if we are inside a template class whose parent class has
2370 /// dependent base classes, and we can't resolve an unqualified identifier, then
2371 /// assume the identifier is a member of a dependent base class.  We can only
2372 /// recover successfully in static methods, instance methods, and other contexts
2373 /// where 'this' is available.  This doesn't precisely match MSVC's
2374 /// instantiation model, but it's close enough.
2375 static Expr *
2376 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2377                                DeclarationNameInfo &NameInfo,
2378                                SourceLocation TemplateKWLoc,
2379                                const TemplateArgumentListInfo *TemplateArgs) {
2380   // Only try to recover from lookup into dependent bases in static methods or
2381   // contexts where 'this' is available.
2382   QualType ThisType = S.getCurrentThisType();
2383   const CXXRecordDecl *RD = nullptr;
2384   if (!ThisType.isNull())
2385     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2386   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2387     RD = MD->getParent();
2388   if (!RD || !RD->hasAnyDependentBases())
2389     return nullptr;
2390 
2391   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2392   // is available, suggest inserting 'this->' as a fixit.
2393   SourceLocation Loc = NameInfo.getLoc();
2394   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2395   DB << NameInfo.getName() << RD;
2396 
2397   if (!ThisType.isNull()) {
2398     DB << FixItHint::CreateInsertion(Loc, "this->");
2399     return CXXDependentScopeMemberExpr::Create(
2400         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2401         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2402         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2403   }
2404 
2405   // Synthesize a fake NNS that points to the derived class.  This will
2406   // perform name lookup during template instantiation.
2407   CXXScopeSpec SS;
2408   auto *NNS =
2409       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2410   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2411   return DependentScopeDeclRefExpr::Create(
2412       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2413       TemplateArgs);
2414 }
2415 
2416 ExprResult
2417 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2418                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2419                         bool HasTrailingLParen, bool IsAddressOfOperand,
2420                         CorrectionCandidateCallback *CCC,
2421                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2422   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2423          "cannot be direct & operand and have a trailing lparen");
2424   if (SS.isInvalid())
2425     return ExprError();
2426 
2427   TemplateArgumentListInfo TemplateArgsBuffer;
2428 
2429   // Decompose the UnqualifiedId into the following data.
2430   DeclarationNameInfo NameInfo;
2431   const TemplateArgumentListInfo *TemplateArgs;
2432   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2433 
2434   DeclarationName Name = NameInfo.getName();
2435   IdentifierInfo *II = Name.getAsIdentifierInfo();
2436   SourceLocation NameLoc = NameInfo.getLoc();
2437 
2438   if (II && II->isEditorPlaceholder()) {
2439     // FIXME: When typed placeholders are supported we can create a typed
2440     // placeholder expression node.
2441     return ExprError();
2442   }
2443 
2444   // C++ [temp.dep.expr]p3:
2445   //   An id-expression is type-dependent if it contains:
2446   //     -- an identifier that was declared with a dependent type,
2447   //        (note: handled after lookup)
2448   //     -- a template-id that is dependent,
2449   //        (note: handled in BuildTemplateIdExpr)
2450   //     -- a conversion-function-id that specifies a dependent type,
2451   //     -- a nested-name-specifier that contains a class-name that
2452   //        names a dependent type.
2453   // Determine whether this is a member of an unknown specialization;
2454   // we need to handle these differently.
2455   bool DependentID = false;
2456   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2457       Name.getCXXNameType()->isDependentType()) {
2458     DependentID = true;
2459   } else if (SS.isSet()) {
2460     if (DeclContext *DC = computeDeclContext(SS, false)) {
2461       if (RequireCompleteDeclContext(SS, DC))
2462         return ExprError();
2463     } else {
2464       DependentID = true;
2465     }
2466   }
2467 
2468   if (DependentID)
2469     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2470                                       IsAddressOfOperand, TemplateArgs);
2471 
2472   // Perform the required lookup.
2473   LookupResult R(*this, NameInfo,
2474                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2475                      ? LookupObjCImplicitSelfParam
2476                      : LookupOrdinaryName);
2477   if (TemplateKWLoc.isValid() || TemplateArgs) {
2478     // Lookup the template name again to correctly establish the context in
2479     // which it was found. This is really unfortunate as we already did the
2480     // lookup to determine that it was a template name in the first place. If
2481     // this becomes a performance hit, we can work harder to preserve those
2482     // results until we get here but it's likely not worth it.
2483     bool MemberOfUnknownSpecialization;
2484     AssumedTemplateKind AssumedTemplate;
2485     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2486                            MemberOfUnknownSpecialization, TemplateKWLoc,
2487                            &AssumedTemplate))
2488       return ExprError();
2489 
2490     if (MemberOfUnknownSpecialization ||
2491         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2492       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2493                                         IsAddressOfOperand, TemplateArgs);
2494   } else {
2495     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2496     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2497 
2498     // If the result might be in a dependent base class, this is a dependent
2499     // id-expression.
2500     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2501       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2502                                         IsAddressOfOperand, TemplateArgs);
2503 
2504     // If this reference is in an Objective-C method, then we need to do
2505     // some special Objective-C lookup, too.
2506     if (IvarLookupFollowUp) {
2507       ExprResult E(LookupInObjCMethod(R, S, II, true));
2508       if (E.isInvalid())
2509         return ExprError();
2510 
2511       if (Expr *Ex = E.getAs<Expr>())
2512         return Ex;
2513     }
2514   }
2515 
2516   if (R.isAmbiguous())
2517     return ExprError();
2518 
2519   // This could be an implicitly declared function reference (legal in C90,
2520   // extension in C99, forbidden in C++).
2521   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2522     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2523     if (D) R.addDecl(D);
2524   }
2525 
2526   // Determine whether this name might be a candidate for
2527   // argument-dependent lookup.
2528   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2529 
2530   if (R.empty() && !ADL) {
2531     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2532       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2533                                                    TemplateKWLoc, TemplateArgs))
2534         return E;
2535     }
2536 
2537     // Don't diagnose an empty lookup for inline assembly.
2538     if (IsInlineAsmIdentifier)
2539       return ExprError();
2540 
2541     // If this name wasn't predeclared and if this is not a function
2542     // call, diagnose the problem.
2543     TypoExpr *TE = nullptr;
2544     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2545                                                        : nullptr);
2546     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2547     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2548            "Typo correction callback misconfigured");
2549     if (CCC) {
2550       // Make sure the callback knows what the typo being diagnosed is.
2551       CCC->setTypoName(II);
2552       if (SS.isValid())
2553         CCC->setTypoNNS(SS.getScopeRep());
2554     }
2555     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2556     // a template name, but we happen to have always already looked up the name
2557     // before we get here if it must be a template name.
2558     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2559                             None, &TE)) {
2560       if (TE && KeywordReplacement) {
2561         auto &State = getTypoExprState(TE);
2562         auto BestTC = State.Consumer->getNextCorrection();
2563         if (BestTC.isKeyword()) {
2564           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2565           if (State.DiagHandler)
2566             State.DiagHandler(BestTC);
2567           KeywordReplacement->startToken();
2568           KeywordReplacement->setKind(II->getTokenID());
2569           KeywordReplacement->setIdentifierInfo(II);
2570           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2571           // Clean up the state associated with the TypoExpr, since it has
2572           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2573           clearDelayedTypo(TE);
2574           // Signal that a correction to a keyword was performed by returning a
2575           // valid-but-null ExprResult.
2576           return (Expr*)nullptr;
2577         }
2578         State.Consumer->resetCorrectionStream();
2579       }
2580       return TE ? TE : ExprError();
2581     }
2582 
2583     assert(!R.empty() &&
2584            "DiagnoseEmptyLookup returned false but added no results");
2585 
2586     // If we found an Objective-C instance variable, let
2587     // LookupInObjCMethod build the appropriate expression to
2588     // reference the ivar.
2589     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2590       R.clear();
2591       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2592       // In a hopelessly buggy code, Objective-C instance variable
2593       // lookup fails and no expression will be built to reference it.
2594       if (!E.isInvalid() && !E.get())
2595         return ExprError();
2596       return E;
2597     }
2598   }
2599 
2600   // This is guaranteed from this point on.
2601   assert(!R.empty() || ADL);
2602 
2603   // Check whether this might be a C++ implicit instance member access.
2604   // C++ [class.mfct.non-static]p3:
2605   //   When an id-expression that is not part of a class member access
2606   //   syntax and not used to form a pointer to member is used in the
2607   //   body of a non-static member function of class X, if name lookup
2608   //   resolves the name in the id-expression to a non-static non-type
2609   //   member of some class C, the id-expression is transformed into a
2610   //   class member access expression using (*this) as the
2611   //   postfix-expression to the left of the . operator.
2612   //
2613   // But we don't actually need to do this for '&' operands if R
2614   // resolved to a function or overloaded function set, because the
2615   // expression is ill-formed if it actually works out to be a
2616   // non-static member function:
2617   //
2618   // C++ [expr.ref]p4:
2619   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2620   //   [t]he expression can be used only as the left-hand operand of a
2621   //   member function call.
2622   //
2623   // There are other safeguards against such uses, but it's important
2624   // to get this right here so that we don't end up making a
2625   // spuriously dependent expression if we're inside a dependent
2626   // instance method.
2627   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2628     bool MightBeImplicitMember;
2629     if (!IsAddressOfOperand)
2630       MightBeImplicitMember = true;
2631     else if (!SS.isEmpty())
2632       MightBeImplicitMember = false;
2633     else if (R.isOverloadedResult())
2634       MightBeImplicitMember = false;
2635     else if (R.isUnresolvableResult())
2636       MightBeImplicitMember = true;
2637     else
2638       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2639                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2640                               isa<MSPropertyDecl>(R.getFoundDecl());
2641 
2642     if (MightBeImplicitMember)
2643       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2644                                              R, TemplateArgs, S);
2645   }
2646 
2647   if (TemplateArgs || TemplateKWLoc.isValid()) {
2648 
2649     // In C++1y, if this is a variable template id, then check it
2650     // in BuildTemplateIdExpr().
2651     // The single lookup result must be a variable template declaration.
2652     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2653         Id.TemplateId->Kind == TNK_Var_template) {
2654       assert(R.getAsSingle<VarTemplateDecl>() &&
2655              "There should only be one declaration found.");
2656     }
2657 
2658     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2659   }
2660 
2661   return BuildDeclarationNameExpr(SS, R, ADL);
2662 }
2663 
2664 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2665 /// declaration name, generally during template instantiation.
2666 /// There's a large number of things which don't need to be done along
2667 /// this path.
2668 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2669     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2670     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2671   DeclContext *DC = computeDeclContext(SS, false);
2672   if (!DC)
2673     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2674                                      NameInfo, /*TemplateArgs=*/nullptr);
2675 
2676   if (RequireCompleteDeclContext(SS, DC))
2677     return ExprError();
2678 
2679   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2680   LookupQualifiedName(R, DC);
2681 
2682   if (R.isAmbiguous())
2683     return ExprError();
2684 
2685   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2686     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2687                                      NameInfo, /*TemplateArgs=*/nullptr);
2688 
2689   if (R.empty()) {
2690     // Don't diagnose problems with invalid record decl, the secondary no_member
2691     // diagnostic during template instantiation is likely bogus, e.g. if a class
2692     // is invalid because it's derived from an invalid base class, then missing
2693     // members were likely supposed to be inherited.
2694     if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2695       if (CD->isInvalidDecl())
2696         return ExprError();
2697     Diag(NameInfo.getLoc(), diag::err_no_member)
2698       << NameInfo.getName() << DC << SS.getRange();
2699     return ExprError();
2700   }
2701 
2702   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2703     // Diagnose a missing typename if this resolved unambiguously to a type in
2704     // a dependent context.  If we can recover with a type, downgrade this to
2705     // a warning in Microsoft compatibility mode.
2706     unsigned DiagID = diag::err_typename_missing;
2707     if (RecoveryTSI && getLangOpts().MSVCCompat)
2708       DiagID = diag::ext_typename_missing;
2709     SourceLocation Loc = SS.getBeginLoc();
2710     auto D = Diag(Loc, DiagID);
2711     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2712       << SourceRange(Loc, NameInfo.getEndLoc());
2713 
2714     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2715     // context.
2716     if (!RecoveryTSI)
2717       return ExprError();
2718 
2719     // Only issue the fixit if we're prepared to recover.
2720     D << FixItHint::CreateInsertion(Loc, "typename ");
2721 
2722     // Recover by pretending this was an elaborated type.
2723     QualType Ty = Context.getTypeDeclType(TD);
2724     TypeLocBuilder TLB;
2725     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2726 
2727     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2728     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2729     QTL.setElaboratedKeywordLoc(SourceLocation());
2730     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2731 
2732     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2733 
2734     return ExprEmpty();
2735   }
2736 
2737   // Defend against this resolving to an implicit member access. We usually
2738   // won't get here if this might be a legitimate a class member (we end up in
2739   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2740   // a pointer-to-member or in an unevaluated context in C++11.
2741   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2742     return BuildPossibleImplicitMemberExpr(SS,
2743                                            /*TemplateKWLoc=*/SourceLocation(),
2744                                            R, /*TemplateArgs=*/nullptr, S);
2745 
2746   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2747 }
2748 
2749 /// The parser has read a name in, and Sema has detected that we're currently
2750 /// inside an ObjC method. Perform some additional checks and determine if we
2751 /// should form a reference to an ivar.
2752 ///
2753 /// Ideally, most of this would be done by lookup, but there's
2754 /// actually quite a lot of extra work involved.
2755 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2756                                         IdentifierInfo *II) {
2757   SourceLocation Loc = Lookup.getNameLoc();
2758   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2759 
2760   // Check for error condition which is already reported.
2761   if (!CurMethod)
2762     return DeclResult(true);
2763 
2764   // There are two cases to handle here.  1) scoped lookup could have failed,
2765   // in which case we should look for an ivar.  2) scoped lookup could have
2766   // found a decl, but that decl is outside the current instance method (i.e.
2767   // a global variable).  In these two cases, we do a lookup for an ivar with
2768   // this name, if the lookup sucedes, we replace it our current decl.
2769 
2770   // If we're in a class method, we don't normally want to look for
2771   // ivars.  But if we don't find anything else, and there's an
2772   // ivar, that's an error.
2773   bool IsClassMethod = CurMethod->isClassMethod();
2774 
2775   bool LookForIvars;
2776   if (Lookup.empty())
2777     LookForIvars = true;
2778   else if (IsClassMethod)
2779     LookForIvars = false;
2780   else
2781     LookForIvars = (Lookup.isSingleResult() &&
2782                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2783   ObjCInterfaceDecl *IFace = nullptr;
2784   if (LookForIvars) {
2785     IFace = CurMethod->getClassInterface();
2786     ObjCInterfaceDecl *ClassDeclared;
2787     ObjCIvarDecl *IV = nullptr;
2788     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2789       // Diagnose using an ivar in a class method.
2790       if (IsClassMethod) {
2791         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2792         return DeclResult(true);
2793       }
2794 
2795       // Diagnose the use of an ivar outside of the declaring class.
2796       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2797           !declaresSameEntity(ClassDeclared, IFace) &&
2798           !getLangOpts().DebuggerSupport)
2799         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2800 
2801       // Success.
2802       return IV;
2803     }
2804   } else if (CurMethod->isInstanceMethod()) {
2805     // We should warn if a local variable hides an ivar.
2806     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2807       ObjCInterfaceDecl *ClassDeclared;
2808       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2809         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2810             declaresSameEntity(IFace, ClassDeclared))
2811           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2812       }
2813     }
2814   } else if (Lookup.isSingleResult() &&
2815              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2816     // If accessing a stand-alone ivar in a class method, this is an error.
2817     if (const ObjCIvarDecl *IV =
2818             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2819       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2820       return DeclResult(true);
2821     }
2822   }
2823 
2824   // Didn't encounter an error, didn't find an ivar.
2825   return DeclResult(false);
2826 }
2827 
2828 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2829                                   ObjCIvarDecl *IV) {
2830   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2831   assert(CurMethod && CurMethod->isInstanceMethod() &&
2832          "should not reference ivar from this context");
2833 
2834   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2835   assert(IFace && "should not reference ivar from this context");
2836 
2837   // If we're referencing an invalid decl, just return this as a silent
2838   // error node.  The error diagnostic was already emitted on the decl.
2839   if (IV->isInvalidDecl())
2840     return ExprError();
2841 
2842   // Check if referencing a field with __attribute__((deprecated)).
2843   if (DiagnoseUseOfDecl(IV, Loc))
2844     return ExprError();
2845 
2846   // FIXME: This should use a new expr for a direct reference, don't
2847   // turn this into Self->ivar, just return a BareIVarExpr or something.
2848   IdentifierInfo &II = Context.Idents.get("self");
2849   UnqualifiedId SelfName;
2850   SelfName.setImplicitSelfParam(&II);
2851   CXXScopeSpec SelfScopeSpec;
2852   SourceLocation TemplateKWLoc;
2853   ExprResult SelfExpr =
2854       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2855                         /*HasTrailingLParen=*/false,
2856                         /*IsAddressOfOperand=*/false);
2857   if (SelfExpr.isInvalid())
2858     return ExprError();
2859 
2860   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2861   if (SelfExpr.isInvalid())
2862     return ExprError();
2863 
2864   MarkAnyDeclReferenced(Loc, IV, true);
2865 
2866   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2867   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2868       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2869     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2870 
2871   ObjCIvarRefExpr *Result = new (Context)
2872       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2873                       IV->getLocation(), SelfExpr.get(), true, true);
2874 
2875   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2876     if (!isUnevaluatedContext() &&
2877         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2878       getCurFunction()->recordUseOfWeak(Result);
2879   }
2880   if (getLangOpts().ObjCAutoRefCount)
2881     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2882       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2883 
2884   return Result;
2885 }
2886 
2887 /// The parser has read a name in, and Sema has detected that we're currently
2888 /// inside an ObjC method. Perform some additional checks and determine if we
2889 /// should form a reference to an ivar. If so, build an expression referencing
2890 /// that ivar.
2891 ExprResult
2892 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2893                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2894   // FIXME: Integrate this lookup step into LookupParsedName.
2895   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2896   if (Ivar.isInvalid())
2897     return ExprError();
2898   if (Ivar.isUsable())
2899     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2900                             cast<ObjCIvarDecl>(Ivar.get()));
2901 
2902   if (Lookup.empty() && II && AllowBuiltinCreation)
2903     LookupBuiltin(Lookup);
2904 
2905   // Sentinel value saying that we didn't do anything special.
2906   return ExprResult(false);
2907 }
2908 
2909 /// Cast a base object to a member's actual type.
2910 ///
2911 /// There are two relevant checks:
2912 ///
2913 /// C++ [class.access.base]p7:
2914 ///
2915 ///   If a class member access operator [...] is used to access a non-static
2916 ///   data member or non-static member function, the reference is ill-formed if
2917 ///   the left operand [...] cannot be implicitly converted to a pointer to the
2918 ///   naming class of the right operand.
2919 ///
2920 /// C++ [expr.ref]p7:
2921 ///
2922 ///   If E2 is a non-static data member or a non-static member function, the
2923 ///   program is ill-formed if the class of which E2 is directly a member is an
2924 ///   ambiguous base (11.8) of the naming class (11.9.3) of E2.
2925 ///
2926 /// Note that the latter check does not consider access; the access of the
2927 /// "real" base class is checked as appropriate when checking the access of the
2928 /// member name.
2929 ExprResult
2930 Sema::PerformObjectMemberConversion(Expr *From,
2931                                     NestedNameSpecifier *Qualifier,
2932                                     NamedDecl *FoundDecl,
2933                                     NamedDecl *Member) {
2934   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2935   if (!RD)
2936     return From;
2937 
2938   QualType DestRecordType;
2939   QualType DestType;
2940   QualType FromRecordType;
2941   QualType FromType = From->getType();
2942   bool PointerConversions = false;
2943   if (isa<FieldDecl>(Member)) {
2944     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2945     auto FromPtrType = FromType->getAs<PointerType>();
2946     DestRecordType = Context.getAddrSpaceQualType(
2947         DestRecordType, FromPtrType
2948                             ? FromType->getPointeeType().getAddressSpace()
2949                             : FromType.getAddressSpace());
2950 
2951     if (FromPtrType) {
2952       DestType = Context.getPointerType(DestRecordType);
2953       FromRecordType = FromPtrType->getPointeeType();
2954       PointerConversions = true;
2955     } else {
2956       DestType = DestRecordType;
2957       FromRecordType = FromType;
2958     }
2959   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2960     if (Method->isStatic())
2961       return From;
2962 
2963     DestType = Method->getThisType();
2964     DestRecordType = DestType->getPointeeType();
2965 
2966     if (FromType->getAs<PointerType>()) {
2967       FromRecordType = FromType->getPointeeType();
2968       PointerConversions = true;
2969     } else {
2970       FromRecordType = FromType;
2971       DestType = DestRecordType;
2972     }
2973 
2974     LangAS FromAS = FromRecordType.getAddressSpace();
2975     LangAS DestAS = DestRecordType.getAddressSpace();
2976     if (FromAS != DestAS) {
2977       QualType FromRecordTypeWithoutAS =
2978           Context.removeAddrSpaceQualType(FromRecordType);
2979       QualType FromTypeWithDestAS =
2980           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2981       if (PointerConversions)
2982         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2983       From = ImpCastExprToType(From, FromTypeWithDestAS,
2984                                CK_AddressSpaceConversion, From->getValueKind())
2985                  .get();
2986     }
2987   } else {
2988     // No conversion necessary.
2989     return From;
2990   }
2991 
2992   if (DestType->isDependentType() || FromType->isDependentType())
2993     return From;
2994 
2995   // If the unqualified types are the same, no conversion is necessary.
2996   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2997     return From;
2998 
2999   SourceRange FromRange = From->getSourceRange();
3000   SourceLocation FromLoc = FromRange.getBegin();
3001 
3002   ExprValueKind VK = From->getValueKind();
3003 
3004   // C++ [class.member.lookup]p8:
3005   //   [...] Ambiguities can often be resolved by qualifying a name with its
3006   //   class name.
3007   //
3008   // If the member was a qualified name and the qualified referred to a
3009   // specific base subobject type, we'll cast to that intermediate type
3010   // first and then to the object in which the member is declared. That allows
3011   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3012   //
3013   //   class Base { public: int x; };
3014   //   class Derived1 : public Base { };
3015   //   class Derived2 : public Base { };
3016   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
3017   //
3018   //   void VeryDerived::f() {
3019   //     x = 17; // error: ambiguous base subobjects
3020   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
3021   //   }
3022   if (Qualifier && Qualifier->getAsType()) {
3023     QualType QType = QualType(Qualifier->getAsType(), 0);
3024     assert(QType->isRecordType() && "lookup done with non-record type");
3025 
3026     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
3027 
3028     // In C++98, the qualifier type doesn't actually have to be a base
3029     // type of the object type, in which case we just ignore it.
3030     // Otherwise build the appropriate casts.
3031     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3032       CXXCastPath BasePath;
3033       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3034                                        FromLoc, FromRange, &BasePath))
3035         return ExprError();
3036 
3037       if (PointerConversions)
3038         QType = Context.getPointerType(QType);
3039       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3040                                VK, &BasePath).get();
3041 
3042       FromType = QType;
3043       FromRecordType = QRecordType;
3044 
3045       // If the qualifier type was the same as the destination type,
3046       // we're done.
3047       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3048         return From;
3049     }
3050   }
3051 
3052   CXXCastPath BasePath;
3053   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3054                                    FromLoc, FromRange, &BasePath,
3055                                    /*IgnoreAccess=*/true))
3056     return ExprError();
3057 
3058   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3059                            VK, &BasePath);
3060 }
3061 
3062 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3063                                       const LookupResult &R,
3064                                       bool HasTrailingLParen) {
3065   // Only when used directly as the postfix-expression of a call.
3066   if (!HasTrailingLParen)
3067     return false;
3068 
3069   // Never if a scope specifier was provided.
3070   if (SS.isSet())
3071     return false;
3072 
3073   // Only in C++ or ObjC++.
3074   if (!getLangOpts().CPlusPlus)
3075     return false;
3076 
3077   // Turn off ADL when we find certain kinds of declarations during
3078   // normal lookup:
3079   for (NamedDecl *D : R) {
3080     // C++0x [basic.lookup.argdep]p3:
3081     //     -- a declaration of a class member
3082     // Since using decls preserve this property, we check this on the
3083     // original decl.
3084     if (D->isCXXClassMember())
3085       return false;
3086 
3087     // C++0x [basic.lookup.argdep]p3:
3088     //     -- a block-scope function declaration that is not a
3089     //        using-declaration
3090     // NOTE: we also trigger this for function templates (in fact, we
3091     // don't check the decl type at all, since all other decl types
3092     // turn off ADL anyway).
3093     if (isa<UsingShadowDecl>(D))
3094       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3095     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3096       return false;
3097 
3098     // C++0x [basic.lookup.argdep]p3:
3099     //     -- a declaration that is neither a function or a function
3100     //        template
3101     // And also for builtin functions.
3102     if (isa<FunctionDecl>(D)) {
3103       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3104 
3105       // But also builtin functions.
3106       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3107         return false;
3108     } else if (!isa<FunctionTemplateDecl>(D))
3109       return false;
3110   }
3111 
3112   return true;
3113 }
3114 
3115 
3116 /// Diagnoses obvious problems with the use of the given declaration
3117 /// as an expression.  This is only actually called for lookups that
3118 /// were not overloaded, and it doesn't promise that the declaration
3119 /// will in fact be used.
3120 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3121   if (D->isInvalidDecl())
3122     return true;
3123 
3124   if (isa<TypedefNameDecl>(D)) {
3125     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3126     return true;
3127   }
3128 
3129   if (isa<ObjCInterfaceDecl>(D)) {
3130     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3131     return true;
3132   }
3133 
3134   if (isa<NamespaceDecl>(D)) {
3135     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3136     return true;
3137   }
3138 
3139   return false;
3140 }
3141 
3142 // Certain multiversion types should be treated as overloaded even when there is
3143 // only one result.
3144 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3145   assert(R.isSingleResult() && "Expected only a single result");
3146   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3147   return FD &&
3148          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3149 }
3150 
3151 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3152                                           LookupResult &R, bool NeedsADL,
3153                                           bool AcceptInvalidDecl) {
3154   // If this is a single, fully-resolved result and we don't need ADL,
3155   // just build an ordinary singleton decl ref.
3156   if (!NeedsADL && R.isSingleResult() &&
3157       !R.getAsSingle<FunctionTemplateDecl>() &&
3158       !ShouldLookupResultBeMultiVersionOverload(R))
3159     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3160                                     R.getRepresentativeDecl(), nullptr,
3161                                     AcceptInvalidDecl);
3162 
3163   // We only need to check the declaration if there's exactly one
3164   // result, because in the overloaded case the results can only be
3165   // functions and function templates.
3166   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3167       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3168     return ExprError();
3169 
3170   // Otherwise, just build an unresolved lookup expression.  Suppress
3171   // any lookup-related diagnostics; we'll hash these out later, when
3172   // we've picked a target.
3173   R.suppressDiagnostics();
3174 
3175   UnresolvedLookupExpr *ULE
3176     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3177                                    SS.getWithLocInContext(Context),
3178                                    R.getLookupNameInfo(),
3179                                    NeedsADL, R.isOverloadedResult(),
3180                                    R.begin(), R.end());
3181 
3182   return ULE;
3183 }
3184 
3185 static void
3186 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3187                                    ValueDecl *var, DeclContext *DC);
3188 
3189 /// Complete semantic analysis for a reference to the given declaration.
3190 ExprResult Sema::BuildDeclarationNameExpr(
3191     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3192     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3193     bool AcceptInvalidDecl) {
3194   assert(D && "Cannot refer to a NULL declaration");
3195   assert(!isa<FunctionTemplateDecl>(D) &&
3196          "Cannot refer unambiguously to a function template");
3197 
3198   SourceLocation Loc = NameInfo.getLoc();
3199   if (CheckDeclInExpr(*this, Loc, D))
3200     return ExprError();
3201 
3202   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3203     // Specifically diagnose references to class templates that are missing
3204     // a template argument list.
3205     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3206     return ExprError();
3207   }
3208 
3209   // Make sure that we're referring to a value.
3210   if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3211     Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3212     Diag(D->getLocation(), diag::note_declared_at);
3213     return ExprError();
3214   }
3215 
3216   // Check whether this declaration can be used. Note that we suppress
3217   // this check when we're going to perform argument-dependent lookup
3218   // on this function name, because this might not be the function
3219   // that overload resolution actually selects.
3220   if (DiagnoseUseOfDecl(D, Loc))
3221     return ExprError();
3222 
3223   auto *VD = cast<ValueDecl>(D);
3224 
3225   // Only create DeclRefExpr's for valid Decl's.
3226   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3227     return ExprError();
3228 
3229   // Handle members of anonymous structs and unions.  If we got here,
3230   // and the reference is to a class member indirect field, then this
3231   // must be the subject of a pointer-to-member expression.
3232   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3233     if (!indirectField->isCXXClassMember())
3234       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3235                                                       indirectField);
3236 
3237   QualType type = VD->getType();
3238   if (type.isNull())
3239     return ExprError();
3240   ExprValueKind valueKind = VK_PRValue;
3241 
3242   // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3243   // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3244   // is expanded by some outer '...' in the context of the use.
3245   type = type.getNonPackExpansionType();
3246 
3247   switch (D->getKind()) {
3248     // Ignore all the non-ValueDecl kinds.
3249 #define ABSTRACT_DECL(kind)
3250 #define VALUE(type, base)
3251 #define DECL(type, base) case Decl::type:
3252 #include "clang/AST/DeclNodes.inc"
3253     llvm_unreachable("invalid value decl kind");
3254 
3255   // These shouldn't make it here.
3256   case Decl::ObjCAtDefsField:
3257     llvm_unreachable("forming non-member reference to ivar?");
3258 
3259   // Enum constants are always r-values and never references.
3260   // Unresolved using declarations are dependent.
3261   case Decl::EnumConstant:
3262   case Decl::UnresolvedUsingValue:
3263   case Decl::OMPDeclareReduction:
3264   case Decl::OMPDeclareMapper:
3265     valueKind = VK_PRValue;
3266     break;
3267 
3268   // Fields and indirect fields that got here must be for
3269   // pointer-to-member expressions; we just call them l-values for
3270   // internal consistency, because this subexpression doesn't really
3271   // exist in the high-level semantics.
3272   case Decl::Field:
3273   case Decl::IndirectField:
3274   case Decl::ObjCIvar:
3275     assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3276 
3277     // These can't have reference type in well-formed programs, but
3278     // for internal consistency we do this anyway.
3279     type = type.getNonReferenceType();
3280     valueKind = VK_LValue;
3281     break;
3282 
3283   // Non-type template parameters are either l-values or r-values
3284   // depending on the type.
3285   case Decl::NonTypeTemplateParm: {
3286     if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3287       type = reftype->getPointeeType();
3288       valueKind = VK_LValue; // even if the parameter is an r-value reference
3289       break;
3290     }
3291 
3292     // [expr.prim.id.unqual]p2:
3293     //   If the entity is a template parameter object for a template
3294     //   parameter of type T, the type of the expression is const T.
3295     //   [...] The expression is an lvalue if the entity is a [...] template
3296     //   parameter object.
3297     if (type->isRecordType()) {
3298       type = type.getUnqualifiedType().withConst();
3299       valueKind = VK_LValue;
3300       break;
3301     }
3302 
3303     // For non-references, we need to strip qualifiers just in case
3304     // the template parameter was declared as 'const int' or whatever.
3305     valueKind = VK_PRValue;
3306     type = type.getUnqualifiedType();
3307     break;
3308   }
3309 
3310   case Decl::Var:
3311   case Decl::VarTemplateSpecialization:
3312   case Decl::VarTemplatePartialSpecialization:
3313   case Decl::Decomposition:
3314   case Decl::OMPCapturedExpr:
3315     // In C, "extern void blah;" is valid and is an r-value.
3316     if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3317         type->isVoidType()) {
3318       valueKind = VK_PRValue;
3319       break;
3320     }
3321     LLVM_FALLTHROUGH;
3322 
3323   case Decl::ImplicitParam:
3324   case Decl::ParmVar: {
3325     // These are always l-values.
3326     valueKind = VK_LValue;
3327     type = type.getNonReferenceType();
3328 
3329     // FIXME: Does the addition of const really only apply in
3330     // potentially-evaluated contexts? Since the variable isn't actually
3331     // captured in an unevaluated context, it seems that the answer is no.
3332     if (!isUnevaluatedContext()) {
3333       QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3334       if (!CapturedType.isNull())
3335         type = CapturedType;
3336     }
3337 
3338     break;
3339   }
3340 
3341   case Decl::Binding: {
3342     // These are always lvalues.
3343     valueKind = VK_LValue;
3344     type = type.getNonReferenceType();
3345     // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3346     // decides how that's supposed to work.
3347     auto *BD = cast<BindingDecl>(VD);
3348     if (BD->getDeclContext() != CurContext) {
3349       auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3350       if (DD && DD->hasLocalStorage())
3351         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3352     }
3353     break;
3354   }
3355 
3356   case Decl::Function: {
3357     if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3358       if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3359         type = Context.BuiltinFnTy;
3360         valueKind = VK_PRValue;
3361         break;
3362       }
3363     }
3364 
3365     const FunctionType *fty = type->castAs<FunctionType>();
3366 
3367     // If we're referring to a function with an __unknown_anytype
3368     // result type, make the entire expression __unknown_anytype.
3369     if (fty->getReturnType() == Context.UnknownAnyTy) {
3370       type = Context.UnknownAnyTy;
3371       valueKind = VK_PRValue;
3372       break;
3373     }
3374 
3375     // Functions are l-values in C++.
3376     if (getLangOpts().CPlusPlus) {
3377       valueKind = VK_LValue;
3378       break;
3379     }
3380 
3381     // C99 DR 316 says that, if a function type comes from a
3382     // function definition (without a prototype), that type is only
3383     // used for checking compatibility. Therefore, when referencing
3384     // the function, we pretend that we don't have the full function
3385     // type.
3386     if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3387       type = Context.getFunctionNoProtoType(fty->getReturnType(),
3388                                             fty->getExtInfo());
3389 
3390     // Functions are r-values in C.
3391     valueKind = VK_PRValue;
3392     break;
3393   }
3394 
3395   case Decl::CXXDeductionGuide:
3396     llvm_unreachable("building reference to deduction guide");
3397 
3398   case Decl::MSProperty:
3399   case Decl::MSGuid:
3400   case Decl::TemplateParamObject:
3401     // FIXME: Should MSGuidDecl and template parameter objects be subject to
3402     // capture in OpenMP, or duplicated between host and device?
3403     valueKind = VK_LValue;
3404     break;
3405 
3406   case Decl::CXXMethod:
3407     // If we're referring to a method with an __unknown_anytype
3408     // result type, make the entire expression __unknown_anytype.
3409     // This should only be possible with a type written directly.
3410     if (const FunctionProtoType *proto =
3411             dyn_cast<FunctionProtoType>(VD->getType()))
3412       if (proto->getReturnType() == Context.UnknownAnyTy) {
3413         type = Context.UnknownAnyTy;
3414         valueKind = VK_PRValue;
3415         break;
3416       }
3417 
3418     // C++ methods are l-values if static, r-values if non-static.
3419     if (cast<CXXMethodDecl>(VD)->isStatic()) {
3420       valueKind = VK_LValue;
3421       break;
3422     }
3423     LLVM_FALLTHROUGH;
3424 
3425   case Decl::CXXConversion:
3426   case Decl::CXXDestructor:
3427   case Decl::CXXConstructor:
3428     valueKind = VK_PRValue;
3429     break;
3430   }
3431 
3432   return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3433                           /*FIXME: TemplateKWLoc*/ SourceLocation(),
3434                           TemplateArgs);
3435 }
3436 
3437 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3438                                     SmallString<32> &Target) {
3439   Target.resize(CharByteWidth * (Source.size() + 1));
3440   char *ResultPtr = &Target[0];
3441   const llvm::UTF8 *ErrorPtr;
3442   bool success =
3443       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3444   (void)success;
3445   assert(success);
3446   Target.resize(ResultPtr - &Target[0]);
3447 }
3448 
3449 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3450                                      PredefinedExpr::IdentKind IK) {
3451   // Pick the current block, lambda, captured statement or function.
3452   Decl *currentDecl = nullptr;
3453   if (const BlockScopeInfo *BSI = getCurBlock())
3454     currentDecl = BSI->TheDecl;
3455   else if (const LambdaScopeInfo *LSI = getCurLambda())
3456     currentDecl = LSI->CallOperator;
3457   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3458     currentDecl = CSI->TheCapturedDecl;
3459   else
3460     currentDecl = getCurFunctionOrMethodDecl();
3461 
3462   if (!currentDecl) {
3463     Diag(Loc, diag::ext_predef_outside_function);
3464     currentDecl = Context.getTranslationUnitDecl();
3465   }
3466 
3467   QualType ResTy;
3468   StringLiteral *SL = nullptr;
3469   if (cast<DeclContext>(currentDecl)->isDependentContext())
3470     ResTy = Context.DependentTy;
3471   else {
3472     // Pre-defined identifiers are of type char[x], where x is the length of
3473     // the string.
3474     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3475     unsigned Length = Str.length();
3476 
3477     llvm::APInt LengthI(32, Length + 1);
3478     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3479       ResTy =
3480           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3481       SmallString<32> RawChars;
3482       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3483                               Str, RawChars);
3484       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3485                                            ArrayType::Normal,
3486                                            /*IndexTypeQuals*/ 0);
3487       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3488                                  /*Pascal*/ false, ResTy, Loc);
3489     } else {
3490       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3491       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3492                                            ArrayType::Normal,
3493                                            /*IndexTypeQuals*/ 0);
3494       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3495                                  /*Pascal*/ false, ResTy, Loc);
3496     }
3497   }
3498 
3499   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3500 }
3501 
3502 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3503                                                SourceLocation LParen,
3504                                                SourceLocation RParen,
3505                                                TypeSourceInfo *TSI) {
3506   return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3507 }
3508 
3509 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3510                                                SourceLocation LParen,
3511                                                SourceLocation RParen,
3512                                                ParsedType ParsedTy) {
3513   TypeSourceInfo *TSI = nullptr;
3514   QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3515 
3516   if (Ty.isNull())
3517     return ExprError();
3518   if (!TSI)
3519     TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3520 
3521   return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3522 }
3523 
3524 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3525   PredefinedExpr::IdentKind IK;
3526 
3527   switch (Kind) {
3528   default: llvm_unreachable("Unknown simple primary expr!");
3529   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3530   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3531   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3532   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3533   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3534   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3535   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3536   }
3537 
3538   return BuildPredefinedExpr(Loc, IK);
3539 }
3540 
3541 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3542   SmallString<16> CharBuffer;
3543   bool Invalid = false;
3544   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3545   if (Invalid)
3546     return ExprError();
3547 
3548   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3549                             PP, Tok.getKind());
3550   if (Literal.hadError())
3551     return ExprError();
3552 
3553   QualType Ty;
3554   if (Literal.isWide())
3555     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3556   else if (Literal.isUTF8() && getLangOpts().Char8)
3557     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3558   else if (Literal.isUTF16())
3559     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3560   else if (Literal.isUTF32())
3561     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3562   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3563     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3564   else
3565     Ty = Context.CharTy;  // 'x' -> char in C++
3566 
3567   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3568   if (Literal.isWide())
3569     Kind = CharacterLiteral::Wide;
3570   else if (Literal.isUTF16())
3571     Kind = CharacterLiteral::UTF16;
3572   else if (Literal.isUTF32())
3573     Kind = CharacterLiteral::UTF32;
3574   else if (Literal.isUTF8())
3575     Kind = CharacterLiteral::UTF8;
3576 
3577   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3578                                              Tok.getLocation());
3579 
3580   if (Literal.getUDSuffix().empty())
3581     return Lit;
3582 
3583   // We're building a user-defined literal.
3584   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3585   SourceLocation UDSuffixLoc =
3586     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3587 
3588   // Make sure we're allowed user-defined literals here.
3589   if (!UDLScope)
3590     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3591 
3592   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3593   //   operator "" X (ch)
3594   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3595                                         Lit, Tok.getLocation());
3596 }
3597 
3598 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3599   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3600   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3601                                 Context.IntTy, Loc);
3602 }
3603 
3604 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3605                                   QualType Ty, SourceLocation Loc) {
3606   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3607 
3608   using llvm::APFloat;
3609   APFloat Val(Format);
3610 
3611   APFloat::opStatus result = Literal.GetFloatValue(Val);
3612 
3613   // Overflow is always an error, but underflow is only an error if
3614   // we underflowed to zero (APFloat reports denormals as underflow).
3615   if ((result & APFloat::opOverflow) ||
3616       ((result & APFloat::opUnderflow) && Val.isZero())) {
3617     unsigned diagnostic;
3618     SmallString<20> buffer;
3619     if (result & APFloat::opOverflow) {
3620       diagnostic = diag::warn_float_overflow;
3621       APFloat::getLargest(Format).toString(buffer);
3622     } else {
3623       diagnostic = diag::warn_float_underflow;
3624       APFloat::getSmallest(Format).toString(buffer);
3625     }
3626 
3627     S.Diag(Loc, diagnostic)
3628       << Ty
3629       << StringRef(buffer.data(), buffer.size());
3630   }
3631 
3632   bool isExact = (result == APFloat::opOK);
3633   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3634 }
3635 
3636 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3637   assert(E && "Invalid expression");
3638 
3639   if (E->isValueDependent())
3640     return false;
3641 
3642   QualType QT = E->getType();
3643   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3644     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3645     return true;
3646   }
3647 
3648   llvm::APSInt ValueAPS;
3649   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3650 
3651   if (R.isInvalid())
3652     return true;
3653 
3654   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3655   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3656     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3657         << toString(ValueAPS, 10) << ValueIsPositive;
3658     return true;
3659   }
3660 
3661   return false;
3662 }
3663 
3664 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3665   // Fast path for a single digit (which is quite common).  A single digit
3666   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3667   if (Tok.getLength() == 1) {
3668     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3669     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3670   }
3671 
3672   SmallString<128> SpellingBuffer;
3673   // NumericLiteralParser wants to overread by one character.  Add padding to
3674   // the buffer in case the token is copied to the buffer.  If getSpelling()
3675   // returns a StringRef to the memory buffer, it should have a null char at
3676   // the EOF, so it is also safe.
3677   SpellingBuffer.resize(Tok.getLength() + 1);
3678 
3679   // Get the spelling of the token, which eliminates trigraphs, etc.
3680   bool Invalid = false;
3681   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3682   if (Invalid)
3683     return ExprError();
3684 
3685   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3686                                PP.getSourceManager(), PP.getLangOpts(),
3687                                PP.getTargetInfo(), PP.getDiagnostics());
3688   if (Literal.hadError)
3689     return ExprError();
3690 
3691   if (Literal.hasUDSuffix()) {
3692     // We're building a user-defined literal.
3693     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3694     SourceLocation UDSuffixLoc =
3695       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3696 
3697     // Make sure we're allowed user-defined literals here.
3698     if (!UDLScope)
3699       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3700 
3701     QualType CookedTy;
3702     if (Literal.isFloatingLiteral()) {
3703       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3704       // long double, the literal is treated as a call of the form
3705       //   operator "" X (f L)
3706       CookedTy = Context.LongDoubleTy;
3707     } else {
3708       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3709       // unsigned long long, the literal is treated as a call of the form
3710       //   operator "" X (n ULL)
3711       CookedTy = Context.UnsignedLongLongTy;
3712     }
3713 
3714     DeclarationName OpName =
3715       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3716     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3717     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3718 
3719     SourceLocation TokLoc = Tok.getLocation();
3720 
3721     // Perform literal operator lookup to determine if we're building a raw
3722     // literal or a cooked one.
3723     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3724     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3725                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3726                                   /*AllowStringTemplatePack*/ false,
3727                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3728     case LOLR_ErrorNoDiagnostic:
3729       // Lookup failure for imaginary constants isn't fatal, there's still the
3730       // GNU extension producing _Complex types.
3731       break;
3732     case LOLR_Error:
3733       return ExprError();
3734     case LOLR_Cooked: {
3735       Expr *Lit;
3736       if (Literal.isFloatingLiteral()) {
3737         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3738       } else {
3739         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3740         if (Literal.GetIntegerValue(ResultVal))
3741           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3742               << /* Unsigned */ 1;
3743         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3744                                      Tok.getLocation());
3745       }
3746       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3747     }
3748 
3749     case LOLR_Raw: {
3750       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3751       // literal is treated as a call of the form
3752       //   operator "" X ("n")
3753       unsigned Length = Literal.getUDSuffixOffset();
3754       QualType StrTy = Context.getConstantArrayType(
3755           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3756           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3757       Expr *Lit = StringLiteral::Create(
3758           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3759           /*Pascal*/false, StrTy, &TokLoc, 1);
3760       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3761     }
3762 
3763     case LOLR_Template: {
3764       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3765       // template), L is treated as a call fo the form
3766       //   operator "" X <'c1', 'c2', ... 'ck'>()
3767       // where n is the source character sequence c1 c2 ... ck.
3768       TemplateArgumentListInfo ExplicitArgs;
3769       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3770       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3771       llvm::APSInt Value(CharBits, CharIsUnsigned);
3772       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3773         Value = TokSpelling[I];
3774         TemplateArgument Arg(Context, Value, Context.CharTy);
3775         TemplateArgumentLocInfo ArgInfo;
3776         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3777       }
3778       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3779                                       &ExplicitArgs);
3780     }
3781     case LOLR_StringTemplatePack:
3782       llvm_unreachable("unexpected literal operator lookup result");
3783     }
3784   }
3785 
3786   Expr *Res;
3787 
3788   if (Literal.isFixedPointLiteral()) {
3789     QualType Ty;
3790 
3791     if (Literal.isAccum) {
3792       if (Literal.isHalf) {
3793         Ty = Context.ShortAccumTy;
3794       } else if (Literal.isLong) {
3795         Ty = Context.LongAccumTy;
3796       } else {
3797         Ty = Context.AccumTy;
3798       }
3799     } else if (Literal.isFract) {
3800       if (Literal.isHalf) {
3801         Ty = Context.ShortFractTy;
3802       } else if (Literal.isLong) {
3803         Ty = Context.LongFractTy;
3804       } else {
3805         Ty = Context.FractTy;
3806       }
3807     }
3808 
3809     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3810 
3811     bool isSigned = !Literal.isUnsigned;
3812     unsigned scale = Context.getFixedPointScale(Ty);
3813     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3814 
3815     llvm::APInt Val(bit_width, 0, isSigned);
3816     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3817     bool ValIsZero = Val.isZero() && !Overflowed;
3818 
3819     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3820     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3821       // Clause 6.4.4 - The value of a constant shall be in the range of
3822       // representable values for its type, with exception for constants of a
3823       // fract type with a value of exactly 1; such a constant shall denote
3824       // the maximal value for the type.
3825       --Val;
3826     else if (Val.ugt(MaxVal) || Overflowed)
3827       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3828 
3829     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3830                                               Tok.getLocation(), scale);
3831   } else if (Literal.isFloatingLiteral()) {
3832     QualType Ty;
3833     if (Literal.isHalf){
3834       if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3835         Ty = Context.HalfTy;
3836       else {
3837         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3838         return ExprError();
3839       }
3840     } else if (Literal.isFloat)
3841       Ty = Context.FloatTy;
3842     else if (Literal.isLong)
3843       Ty = Context.LongDoubleTy;
3844     else if (Literal.isFloat16)
3845       Ty = Context.Float16Ty;
3846     else if (Literal.isFloat128)
3847       Ty = Context.Float128Ty;
3848     else
3849       Ty = Context.DoubleTy;
3850 
3851     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3852 
3853     if (Ty == Context.DoubleTy) {
3854       if (getLangOpts().SinglePrecisionConstants) {
3855         if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3856           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3857         }
3858       } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3859                                              "cl_khr_fp64", getLangOpts())) {
3860         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3861         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3862             << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3863         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3864       }
3865     }
3866   } else if (!Literal.isIntegerLiteral()) {
3867     return ExprError();
3868   } else {
3869     QualType Ty;
3870 
3871     // 'long long' is a C99 or C++11 feature.
3872     if (!getLangOpts().C99 && Literal.isLongLong) {
3873       if (getLangOpts().CPlusPlus)
3874         Diag(Tok.getLocation(),
3875              getLangOpts().CPlusPlus11 ?
3876              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3877       else
3878         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3879     }
3880 
3881     // 'z/uz' literals are a C++2b feature.
3882     if (Literal.isSizeT)
3883       Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3884                                   ? getLangOpts().CPlusPlus2b
3885                                         ? diag::warn_cxx20_compat_size_t_suffix
3886                                         : diag::ext_cxx2b_size_t_suffix
3887                                   : diag::err_cxx2b_size_t_suffix);
3888 
3889     // Get the value in the widest-possible width.
3890     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3891     llvm::APInt ResultVal(MaxWidth, 0);
3892 
3893     if (Literal.GetIntegerValue(ResultVal)) {
3894       // If this value didn't fit into uintmax_t, error and force to ull.
3895       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3896           << /* Unsigned */ 1;
3897       Ty = Context.UnsignedLongLongTy;
3898       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3899              "long long is not intmax_t?");
3900     } else {
3901       // If this value fits into a ULL, try to figure out what else it fits into
3902       // according to the rules of C99 6.4.4.1p5.
3903 
3904       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3905       // be an unsigned int.
3906       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3907 
3908       // Check from smallest to largest, picking the smallest type we can.
3909       unsigned Width = 0;
3910 
3911       // Microsoft specific integer suffixes are explicitly sized.
3912       if (Literal.MicrosoftInteger) {
3913         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3914           Width = 8;
3915           Ty = Context.CharTy;
3916         } else {
3917           Width = Literal.MicrosoftInteger;
3918           Ty = Context.getIntTypeForBitwidth(Width,
3919                                              /*Signed=*/!Literal.isUnsigned);
3920         }
3921       }
3922 
3923       // Check C++2b size_t literals.
3924       if (Literal.isSizeT) {
3925         assert(!Literal.MicrosoftInteger &&
3926                "size_t literals can't be Microsoft literals");
3927         unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3928             Context.getTargetInfo().getSizeType());
3929 
3930         // Does it fit in size_t?
3931         if (ResultVal.isIntN(SizeTSize)) {
3932           // Does it fit in ssize_t?
3933           if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3934             Ty = Context.getSignedSizeType();
3935           else if (AllowUnsigned)
3936             Ty = Context.getSizeType();
3937           Width = SizeTSize;
3938         }
3939       }
3940 
3941       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3942           !Literal.isSizeT) {
3943         // Are int/unsigned possibilities?
3944         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3945 
3946         // Does it fit in a unsigned int?
3947         if (ResultVal.isIntN(IntSize)) {
3948           // Does it fit in a signed int?
3949           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3950             Ty = Context.IntTy;
3951           else if (AllowUnsigned)
3952             Ty = Context.UnsignedIntTy;
3953           Width = IntSize;
3954         }
3955       }
3956 
3957       // Are long/unsigned long possibilities?
3958       if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
3959         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3960 
3961         // Does it fit in a unsigned long?
3962         if (ResultVal.isIntN(LongSize)) {
3963           // Does it fit in a signed long?
3964           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3965             Ty = Context.LongTy;
3966           else if (AllowUnsigned)
3967             Ty = Context.UnsignedLongTy;
3968           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3969           // is compatible.
3970           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3971             const unsigned LongLongSize =
3972                 Context.getTargetInfo().getLongLongWidth();
3973             Diag(Tok.getLocation(),
3974                  getLangOpts().CPlusPlus
3975                      ? Literal.isLong
3976                            ? diag::warn_old_implicitly_unsigned_long_cxx
3977                            : /*C++98 UB*/ diag::
3978                                  ext_old_implicitly_unsigned_long_cxx
3979                      : diag::warn_old_implicitly_unsigned_long)
3980                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3981                                             : /*will be ill-formed*/ 1);
3982             Ty = Context.UnsignedLongTy;
3983           }
3984           Width = LongSize;
3985         }
3986       }
3987 
3988       // Check long long if needed.
3989       if (Ty.isNull() && !Literal.isSizeT) {
3990         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3991 
3992         // Does it fit in a unsigned long long?
3993         if (ResultVal.isIntN(LongLongSize)) {
3994           // Does it fit in a signed long long?
3995           // To be compatible with MSVC, hex integer literals ending with the
3996           // LL or i64 suffix are always signed in Microsoft mode.
3997           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3998               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3999             Ty = Context.LongLongTy;
4000           else if (AllowUnsigned)
4001             Ty = Context.UnsignedLongLongTy;
4002           Width = LongLongSize;
4003         }
4004       }
4005 
4006       // If we still couldn't decide a type, we either have 'size_t' literal
4007       // that is out of range, or a decimal literal that does not fit in a
4008       // signed long long and has no U suffix.
4009       if (Ty.isNull()) {
4010         if (Literal.isSizeT)
4011           Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4012               << Literal.isUnsigned;
4013         else
4014           Diag(Tok.getLocation(),
4015                diag::ext_integer_literal_too_large_for_signed);
4016         Ty = Context.UnsignedLongLongTy;
4017         Width = Context.getTargetInfo().getLongLongWidth();
4018       }
4019 
4020       if (ResultVal.getBitWidth() != Width)
4021         ResultVal = ResultVal.trunc(Width);
4022     }
4023     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4024   }
4025 
4026   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4027   if (Literal.isImaginary) {
4028     Res = new (Context) ImaginaryLiteral(Res,
4029                                         Context.getComplexType(Res->getType()));
4030 
4031     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4032   }
4033   return Res;
4034 }
4035 
4036 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4037   assert(E && "ActOnParenExpr() missing expr");
4038   QualType ExprTy = E->getType();
4039   if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4040       !E->isLValue() && ExprTy->hasFloatingRepresentation())
4041     return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4042   return new (Context) ParenExpr(L, R, E);
4043 }
4044 
4045 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4046                                          SourceLocation Loc,
4047                                          SourceRange ArgRange) {
4048   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4049   // scalar or vector data type argument..."
4050   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4051   // type (C99 6.2.5p18) or void.
4052   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4053     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4054       << T << ArgRange;
4055     return true;
4056   }
4057 
4058   assert((T->isVoidType() || !T->isIncompleteType()) &&
4059          "Scalar types should always be complete");
4060   return false;
4061 }
4062 
4063 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4064                                            SourceLocation Loc,
4065                                            SourceRange ArgRange,
4066                                            UnaryExprOrTypeTrait TraitKind) {
4067   // Invalid types must be hard errors for SFINAE in C++.
4068   if (S.LangOpts.CPlusPlus)
4069     return true;
4070 
4071   // C99 6.5.3.4p1:
4072   if (T->isFunctionType() &&
4073       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4074        TraitKind == UETT_PreferredAlignOf)) {
4075     // sizeof(function)/alignof(function) is allowed as an extension.
4076     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4077         << getTraitSpelling(TraitKind) << ArgRange;
4078     return false;
4079   }
4080 
4081   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4082   // this is an error (OpenCL v1.1 s6.3.k)
4083   if (T->isVoidType()) {
4084     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4085                                         : diag::ext_sizeof_alignof_void_type;
4086     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4087     return false;
4088   }
4089 
4090   return true;
4091 }
4092 
4093 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4094                                              SourceLocation Loc,
4095                                              SourceRange ArgRange,
4096                                              UnaryExprOrTypeTrait TraitKind) {
4097   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4098   // runtime doesn't allow it.
4099   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4100     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4101       << T << (TraitKind == UETT_SizeOf)
4102       << ArgRange;
4103     return true;
4104   }
4105 
4106   return false;
4107 }
4108 
4109 /// Check whether E is a pointer from a decayed array type (the decayed
4110 /// pointer type is equal to T) and emit a warning if it is.
4111 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4112                                      Expr *E) {
4113   // Don't warn if the operation changed the type.
4114   if (T != E->getType())
4115     return;
4116 
4117   // Now look for array decays.
4118   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4119   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4120     return;
4121 
4122   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4123                                              << ICE->getType()
4124                                              << ICE->getSubExpr()->getType();
4125 }
4126 
4127 /// Check the constraints on expression operands to unary type expression
4128 /// and type traits.
4129 ///
4130 /// Completes any types necessary and validates the constraints on the operand
4131 /// expression. The logic mostly mirrors the type-based overload, but may modify
4132 /// the expression as it completes the type for that expression through template
4133 /// instantiation, etc.
4134 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4135                                             UnaryExprOrTypeTrait ExprKind) {
4136   QualType ExprTy = E->getType();
4137   assert(!ExprTy->isReferenceType());
4138 
4139   bool IsUnevaluatedOperand =
4140       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4141        ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4142   if (IsUnevaluatedOperand) {
4143     ExprResult Result = CheckUnevaluatedOperand(E);
4144     if (Result.isInvalid())
4145       return true;
4146     E = Result.get();
4147   }
4148 
4149   // The operand for sizeof and alignof is in an unevaluated expression context,
4150   // so side effects could result in unintended consequences.
4151   // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4152   // used to build SFINAE gadgets.
4153   // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4154   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4155       !E->isInstantiationDependent() &&
4156       E->HasSideEffects(Context, false))
4157     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4158 
4159   if (ExprKind == UETT_VecStep)
4160     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4161                                         E->getSourceRange());
4162 
4163   // Explicitly list some types as extensions.
4164   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4165                                       E->getSourceRange(), ExprKind))
4166     return false;
4167 
4168   // 'alignof' applied to an expression only requires the base element type of
4169   // the expression to be complete. 'sizeof' requires the expression's type to
4170   // be complete (and will attempt to complete it if it's an array of unknown
4171   // bound).
4172   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4173     if (RequireCompleteSizedType(
4174             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4175             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4176             getTraitSpelling(ExprKind), E->getSourceRange()))
4177       return true;
4178   } else {
4179     if (RequireCompleteSizedExprType(
4180             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4181             getTraitSpelling(ExprKind), E->getSourceRange()))
4182       return true;
4183   }
4184 
4185   // Completing the expression's type may have changed it.
4186   ExprTy = E->getType();
4187   assert(!ExprTy->isReferenceType());
4188 
4189   if (ExprTy->isFunctionType()) {
4190     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4191         << getTraitSpelling(ExprKind) << E->getSourceRange();
4192     return true;
4193   }
4194 
4195   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4196                                        E->getSourceRange(), ExprKind))
4197     return true;
4198 
4199   if (ExprKind == UETT_SizeOf) {
4200     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4201       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4202         QualType OType = PVD->getOriginalType();
4203         QualType Type = PVD->getType();
4204         if (Type->isPointerType() && OType->isArrayType()) {
4205           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4206             << Type << OType;
4207           Diag(PVD->getLocation(), diag::note_declared_at);
4208         }
4209       }
4210     }
4211 
4212     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4213     // decays into a pointer and returns an unintended result. This is most
4214     // likely a typo for "sizeof(array) op x".
4215     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4216       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4217                                BO->getLHS());
4218       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4219                                BO->getRHS());
4220     }
4221   }
4222 
4223   return false;
4224 }
4225 
4226 /// Check the constraints on operands to unary expression and type
4227 /// traits.
4228 ///
4229 /// This will complete any types necessary, and validate the various constraints
4230 /// on those operands.
4231 ///
4232 /// The UsualUnaryConversions() function is *not* called by this routine.
4233 /// C99 6.3.2.1p[2-4] all state:
4234 ///   Except when it is the operand of the sizeof operator ...
4235 ///
4236 /// C++ [expr.sizeof]p4
4237 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4238 ///   standard conversions are not applied to the operand of sizeof.
4239 ///
4240 /// This policy is followed for all of the unary trait expressions.
4241 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4242                                             SourceLocation OpLoc,
4243                                             SourceRange ExprRange,
4244                                             UnaryExprOrTypeTrait ExprKind) {
4245   if (ExprType->isDependentType())
4246     return false;
4247 
4248   // C++ [expr.sizeof]p2:
4249   //     When applied to a reference or a reference type, the result
4250   //     is the size of the referenced type.
4251   // C++11 [expr.alignof]p3:
4252   //     When alignof is applied to a reference type, the result
4253   //     shall be the alignment of the referenced type.
4254   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4255     ExprType = Ref->getPointeeType();
4256 
4257   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4258   //   When alignof or _Alignof is applied to an array type, the result
4259   //   is the alignment of the element type.
4260   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4261       ExprKind == UETT_OpenMPRequiredSimdAlign)
4262     ExprType = Context.getBaseElementType(ExprType);
4263 
4264   if (ExprKind == UETT_VecStep)
4265     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4266 
4267   // Explicitly list some types as extensions.
4268   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4269                                       ExprKind))
4270     return false;
4271 
4272   if (RequireCompleteSizedType(
4273           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4274           getTraitSpelling(ExprKind), ExprRange))
4275     return true;
4276 
4277   if (ExprType->isFunctionType()) {
4278     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4279         << getTraitSpelling(ExprKind) << ExprRange;
4280     return true;
4281   }
4282 
4283   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4284                                        ExprKind))
4285     return true;
4286 
4287   return false;
4288 }
4289 
4290 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4291   // Cannot know anything else if the expression is dependent.
4292   if (E->isTypeDependent())
4293     return false;
4294 
4295   if (E->getObjectKind() == OK_BitField) {
4296     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4297        << 1 << E->getSourceRange();
4298     return true;
4299   }
4300 
4301   ValueDecl *D = nullptr;
4302   Expr *Inner = E->IgnoreParens();
4303   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4304     D = DRE->getDecl();
4305   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4306     D = ME->getMemberDecl();
4307   }
4308 
4309   // If it's a field, require the containing struct to have a
4310   // complete definition so that we can compute the layout.
4311   //
4312   // This can happen in C++11 onwards, either by naming the member
4313   // in a way that is not transformed into a member access expression
4314   // (in an unevaluated operand, for instance), or by naming the member
4315   // in a trailing-return-type.
4316   //
4317   // For the record, since __alignof__ on expressions is a GCC
4318   // extension, GCC seems to permit this but always gives the
4319   // nonsensical answer 0.
4320   //
4321   // We don't really need the layout here --- we could instead just
4322   // directly check for all the appropriate alignment-lowing
4323   // attributes --- but that would require duplicating a lot of
4324   // logic that just isn't worth duplicating for such a marginal
4325   // use-case.
4326   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4327     // Fast path this check, since we at least know the record has a
4328     // definition if we can find a member of it.
4329     if (!FD->getParent()->isCompleteDefinition()) {
4330       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4331         << E->getSourceRange();
4332       return true;
4333     }
4334 
4335     // Otherwise, if it's a field, and the field doesn't have
4336     // reference type, then it must have a complete type (or be a
4337     // flexible array member, which we explicitly want to
4338     // white-list anyway), which makes the following checks trivial.
4339     if (!FD->getType()->isReferenceType())
4340       return false;
4341   }
4342 
4343   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4344 }
4345 
4346 bool Sema::CheckVecStepExpr(Expr *E) {
4347   E = E->IgnoreParens();
4348 
4349   // Cannot know anything else if the expression is dependent.
4350   if (E->isTypeDependent())
4351     return false;
4352 
4353   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4354 }
4355 
4356 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4357                                         CapturingScopeInfo *CSI) {
4358   assert(T->isVariablyModifiedType());
4359   assert(CSI != nullptr);
4360 
4361   // We're going to walk down into the type and look for VLA expressions.
4362   do {
4363     const Type *Ty = T.getTypePtr();
4364     switch (Ty->getTypeClass()) {
4365 #define TYPE(Class, Base)
4366 #define ABSTRACT_TYPE(Class, Base)
4367 #define NON_CANONICAL_TYPE(Class, Base)
4368 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4369 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4370 #include "clang/AST/TypeNodes.inc"
4371       T = QualType();
4372       break;
4373     // These types are never variably-modified.
4374     case Type::Builtin:
4375     case Type::Complex:
4376     case Type::Vector:
4377     case Type::ExtVector:
4378     case Type::ConstantMatrix:
4379     case Type::Record:
4380     case Type::Enum:
4381     case Type::Elaborated:
4382     case Type::TemplateSpecialization:
4383     case Type::ObjCObject:
4384     case Type::ObjCInterface:
4385     case Type::ObjCObjectPointer:
4386     case Type::ObjCTypeParam:
4387     case Type::Pipe:
4388     case Type::ExtInt:
4389       llvm_unreachable("type class is never variably-modified!");
4390     case Type::Adjusted:
4391       T = cast<AdjustedType>(Ty)->getOriginalType();
4392       break;
4393     case Type::Decayed:
4394       T = cast<DecayedType>(Ty)->getPointeeType();
4395       break;
4396     case Type::Pointer:
4397       T = cast<PointerType>(Ty)->getPointeeType();
4398       break;
4399     case Type::BlockPointer:
4400       T = cast<BlockPointerType>(Ty)->getPointeeType();
4401       break;
4402     case Type::LValueReference:
4403     case Type::RValueReference:
4404       T = cast<ReferenceType>(Ty)->getPointeeType();
4405       break;
4406     case Type::MemberPointer:
4407       T = cast<MemberPointerType>(Ty)->getPointeeType();
4408       break;
4409     case Type::ConstantArray:
4410     case Type::IncompleteArray:
4411       // Losing element qualification here is fine.
4412       T = cast<ArrayType>(Ty)->getElementType();
4413       break;
4414     case Type::VariableArray: {
4415       // Losing element qualification here is fine.
4416       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4417 
4418       // Unknown size indication requires no size computation.
4419       // Otherwise, evaluate and record it.
4420       auto Size = VAT->getSizeExpr();
4421       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4422           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4423         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4424 
4425       T = VAT->getElementType();
4426       break;
4427     }
4428     case Type::FunctionProto:
4429     case Type::FunctionNoProto:
4430       T = cast<FunctionType>(Ty)->getReturnType();
4431       break;
4432     case Type::Paren:
4433     case Type::TypeOf:
4434     case Type::UnaryTransform:
4435     case Type::Attributed:
4436     case Type::SubstTemplateTypeParm:
4437     case Type::MacroQualified:
4438       // Keep walking after single level desugaring.
4439       T = T.getSingleStepDesugaredType(Context);
4440       break;
4441     case Type::Typedef:
4442       T = cast<TypedefType>(Ty)->desugar();
4443       break;
4444     case Type::Decltype:
4445       T = cast<DecltypeType>(Ty)->desugar();
4446       break;
4447     case Type::Auto:
4448     case Type::DeducedTemplateSpecialization:
4449       T = cast<DeducedType>(Ty)->getDeducedType();
4450       break;
4451     case Type::TypeOfExpr:
4452       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4453       break;
4454     case Type::Atomic:
4455       T = cast<AtomicType>(Ty)->getValueType();
4456       break;
4457     }
4458   } while (!T.isNull() && T->isVariablyModifiedType());
4459 }
4460 
4461 /// Build a sizeof or alignof expression given a type operand.
4462 ExprResult
4463 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4464                                      SourceLocation OpLoc,
4465                                      UnaryExprOrTypeTrait ExprKind,
4466                                      SourceRange R) {
4467   if (!TInfo)
4468     return ExprError();
4469 
4470   QualType T = TInfo->getType();
4471 
4472   if (!T->isDependentType() &&
4473       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4474     return ExprError();
4475 
4476   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4477     if (auto *TT = T->getAs<TypedefType>()) {
4478       for (auto I = FunctionScopes.rbegin(),
4479                 E = std::prev(FunctionScopes.rend());
4480            I != E; ++I) {
4481         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4482         if (CSI == nullptr)
4483           break;
4484         DeclContext *DC = nullptr;
4485         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4486           DC = LSI->CallOperator;
4487         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4488           DC = CRSI->TheCapturedDecl;
4489         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4490           DC = BSI->TheDecl;
4491         if (DC) {
4492           if (DC->containsDecl(TT->getDecl()))
4493             break;
4494           captureVariablyModifiedType(Context, T, CSI);
4495         }
4496       }
4497     }
4498   }
4499 
4500   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4501   return new (Context) UnaryExprOrTypeTraitExpr(
4502       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4503 }
4504 
4505 /// Build a sizeof or alignof expression given an expression
4506 /// operand.
4507 ExprResult
4508 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4509                                      UnaryExprOrTypeTrait ExprKind) {
4510   ExprResult PE = CheckPlaceholderExpr(E);
4511   if (PE.isInvalid())
4512     return ExprError();
4513 
4514   E = PE.get();
4515 
4516   // Verify that the operand is valid.
4517   bool isInvalid = false;
4518   if (E->isTypeDependent()) {
4519     // Delay type-checking for type-dependent expressions.
4520   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4521     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4522   } else if (ExprKind == UETT_VecStep) {
4523     isInvalid = CheckVecStepExpr(E);
4524   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4525       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4526       isInvalid = true;
4527   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4528     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4529     isInvalid = true;
4530   } else {
4531     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4532   }
4533 
4534   if (isInvalid)
4535     return ExprError();
4536 
4537   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4538     PE = TransformToPotentiallyEvaluated(E);
4539     if (PE.isInvalid()) return ExprError();
4540     E = PE.get();
4541   }
4542 
4543   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4544   return new (Context) UnaryExprOrTypeTraitExpr(
4545       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4546 }
4547 
4548 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4549 /// expr and the same for @c alignof and @c __alignof
4550 /// Note that the ArgRange is invalid if isType is false.
4551 ExprResult
4552 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4553                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4554                                     void *TyOrEx, SourceRange ArgRange) {
4555   // If error parsing type, ignore.
4556   if (!TyOrEx) return ExprError();
4557 
4558   if (IsType) {
4559     TypeSourceInfo *TInfo;
4560     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4561     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4562   }
4563 
4564   Expr *ArgEx = (Expr *)TyOrEx;
4565   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4566   return Result;
4567 }
4568 
4569 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4570                                      bool IsReal) {
4571   if (V.get()->isTypeDependent())
4572     return S.Context.DependentTy;
4573 
4574   // _Real and _Imag are only l-values for normal l-values.
4575   if (V.get()->getObjectKind() != OK_Ordinary) {
4576     V = S.DefaultLvalueConversion(V.get());
4577     if (V.isInvalid())
4578       return QualType();
4579   }
4580 
4581   // These operators return the element type of a complex type.
4582   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4583     return CT->getElementType();
4584 
4585   // Otherwise they pass through real integer and floating point types here.
4586   if (V.get()->getType()->isArithmeticType())
4587     return V.get()->getType();
4588 
4589   // Test for placeholders.
4590   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4591   if (PR.isInvalid()) return QualType();
4592   if (PR.get() != V.get()) {
4593     V = PR;
4594     return CheckRealImagOperand(S, V, Loc, IsReal);
4595   }
4596 
4597   // Reject anything else.
4598   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4599     << (IsReal ? "__real" : "__imag");
4600   return QualType();
4601 }
4602 
4603 
4604 
4605 ExprResult
4606 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4607                           tok::TokenKind Kind, Expr *Input) {
4608   UnaryOperatorKind Opc;
4609   switch (Kind) {
4610   default: llvm_unreachable("Unknown unary op!");
4611   case tok::plusplus:   Opc = UO_PostInc; break;
4612   case tok::minusminus: Opc = UO_PostDec; break;
4613   }
4614 
4615   // Since this might is a postfix expression, get rid of ParenListExprs.
4616   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4617   if (Result.isInvalid()) return ExprError();
4618   Input = Result.get();
4619 
4620   return BuildUnaryOp(S, OpLoc, Opc, Input);
4621 }
4622 
4623 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4624 ///
4625 /// \return true on error
4626 static bool checkArithmeticOnObjCPointer(Sema &S,
4627                                          SourceLocation opLoc,
4628                                          Expr *op) {
4629   assert(op->getType()->isObjCObjectPointerType());
4630   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4631       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4632     return false;
4633 
4634   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4635     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4636     << op->getSourceRange();
4637   return true;
4638 }
4639 
4640 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4641   auto *BaseNoParens = Base->IgnoreParens();
4642   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4643     return MSProp->getPropertyDecl()->getType()->isArrayType();
4644   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4645 }
4646 
4647 ExprResult
4648 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4649                               Expr *idx, SourceLocation rbLoc) {
4650   if (base && !base->getType().isNull() &&
4651       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4652     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4653                                     SourceLocation(), /*Length*/ nullptr,
4654                                     /*Stride=*/nullptr, rbLoc);
4655 
4656   // Since this might be a postfix expression, get rid of ParenListExprs.
4657   if (isa<ParenListExpr>(base)) {
4658     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4659     if (result.isInvalid()) return ExprError();
4660     base = result.get();
4661   }
4662 
4663   // Check if base and idx form a MatrixSubscriptExpr.
4664   //
4665   // Helper to check for comma expressions, which are not allowed as indices for
4666   // matrix subscript expressions.
4667   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4668     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4669       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4670           << SourceRange(base->getBeginLoc(), rbLoc);
4671       return true;
4672     }
4673     return false;
4674   };
4675   // The matrix subscript operator ([][])is considered a single operator.
4676   // Separating the index expressions by parenthesis is not allowed.
4677   if (base->getType()->isSpecificPlaceholderType(
4678           BuiltinType::IncompleteMatrixIdx) &&
4679       !isa<MatrixSubscriptExpr>(base)) {
4680     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4681         << SourceRange(base->getBeginLoc(), rbLoc);
4682     return ExprError();
4683   }
4684   // If the base is a MatrixSubscriptExpr, try to create a new
4685   // MatrixSubscriptExpr.
4686   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4687   if (matSubscriptE) {
4688     if (CheckAndReportCommaError(idx))
4689       return ExprError();
4690 
4691     assert(matSubscriptE->isIncomplete() &&
4692            "base has to be an incomplete matrix subscript");
4693     return CreateBuiltinMatrixSubscriptExpr(
4694         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4695   }
4696 
4697   // Handle any non-overload placeholder types in the base and index
4698   // expressions.  We can't handle overloads here because the other
4699   // operand might be an overloadable type, in which case the overload
4700   // resolution for the operator overload should get the first crack
4701   // at the overload.
4702   bool IsMSPropertySubscript = false;
4703   if (base->getType()->isNonOverloadPlaceholderType()) {
4704     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4705     if (!IsMSPropertySubscript) {
4706       ExprResult result = CheckPlaceholderExpr(base);
4707       if (result.isInvalid())
4708         return ExprError();
4709       base = result.get();
4710     }
4711   }
4712 
4713   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4714   if (base->getType()->isMatrixType()) {
4715     if (CheckAndReportCommaError(idx))
4716       return ExprError();
4717 
4718     return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4719   }
4720 
4721   // A comma-expression as the index is deprecated in C++2a onwards.
4722   if (getLangOpts().CPlusPlus20 &&
4723       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4724        (isa<CXXOperatorCallExpr>(idx) &&
4725         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4726     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4727         << SourceRange(base->getBeginLoc(), rbLoc);
4728   }
4729 
4730   if (idx->getType()->isNonOverloadPlaceholderType()) {
4731     ExprResult result = CheckPlaceholderExpr(idx);
4732     if (result.isInvalid()) return ExprError();
4733     idx = result.get();
4734   }
4735 
4736   // Build an unanalyzed expression if either operand is type-dependent.
4737   if (getLangOpts().CPlusPlus &&
4738       (base->isTypeDependent() || idx->isTypeDependent())) {
4739     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4740                                             VK_LValue, OK_Ordinary, rbLoc);
4741   }
4742 
4743   // MSDN, property (C++)
4744   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4745   // This attribute can also be used in the declaration of an empty array in a
4746   // class or structure definition. For example:
4747   // __declspec(property(get=GetX, put=PutX)) int x[];
4748   // The above statement indicates that x[] can be used with one or more array
4749   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4750   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4751   if (IsMSPropertySubscript) {
4752     // Build MS property subscript expression if base is MS property reference
4753     // or MS property subscript.
4754     return new (Context) MSPropertySubscriptExpr(
4755         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4756   }
4757 
4758   // Use C++ overloaded-operator rules if either operand has record
4759   // type.  The spec says to do this if either type is *overloadable*,
4760   // but enum types can't declare subscript operators or conversion
4761   // operators, so there's nothing interesting for overload resolution
4762   // to do if there aren't any record types involved.
4763   //
4764   // ObjC pointers have their own subscripting logic that is not tied
4765   // to overload resolution and so should not take this path.
4766   if (getLangOpts().CPlusPlus &&
4767       (base->getType()->isRecordType() ||
4768        (!base->getType()->isObjCObjectPointerType() &&
4769         idx->getType()->isRecordType()))) {
4770     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4771   }
4772 
4773   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4774 
4775   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4776     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4777 
4778   return Res;
4779 }
4780 
4781 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4782   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4783   InitializationKind Kind =
4784       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4785   InitializationSequence InitSeq(*this, Entity, Kind, E);
4786   return InitSeq.Perform(*this, Entity, Kind, E);
4787 }
4788 
4789 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4790                                                   Expr *ColumnIdx,
4791                                                   SourceLocation RBLoc) {
4792   ExprResult BaseR = CheckPlaceholderExpr(Base);
4793   if (BaseR.isInvalid())
4794     return BaseR;
4795   Base = BaseR.get();
4796 
4797   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4798   if (RowR.isInvalid())
4799     return RowR;
4800   RowIdx = RowR.get();
4801 
4802   if (!ColumnIdx)
4803     return new (Context) MatrixSubscriptExpr(
4804         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4805 
4806   // Build an unanalyzed expression if any of the operands is type-dependent.
4807   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4808       ColumnIdx->isTypeDependent())
4809     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4810                                              Context.DependentTy, RBLoc);
4811 
4812   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4813   if (ColumnR.isInvalid())
4814     return ColumnR;
4815   ColumnIdx = ColumnR.get();
4816 
4817   // Check that IndexExpr is an integer expression. If it is a constant
4818   // expression, check that it is less than Dim (= the number of elements in the
4819   // corresponding dimension).
4820   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4821                           bool IsColumnIdx) -> Expr * {
4822     if (!IndexExpr->getType()->isIntegerType() &&
4823         !IndexExpr->isTypeDependent()) {
4824       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4825           << IsColumnIdx;
4826       return nullptr;
4827     }
4828 
4829     if (Optional<llvm::APSInt> Idx =
4830             IndexExpr->getIntegerConstantExpr(Context)) {
4831       if ((*Idx < 0 || *Idx >= Dim)) {
4832         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4833             << IsColumnIdx << Dim;
4834         return nullptr;
4835       }
4836     }
4837 
4838     ExprResult ConvExpr =
4839         tryConvertExprToType(IndexExpr, Context.getSizeType());
4840     assert(!ConvExpr.isInvalid() &&
4841            "should be able to convert any integer type to size type");
4842     return ConvExpr.get();
4843   };
4844 
4845   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4846   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4847   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4848   if (!RowIdx || !ColumnIdx)
4849     return ExprError();
4850 
4851   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4852                                            MTy->getElementType(), RBLoc);
4853 }
4854 
4855 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4856   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4857   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4858 
4859   // For expressions like `&(*s).b`, the base is recorded and what should be
4860   // checked.
4861   const MemberExpr *Member = nullptr;
4862   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4863     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4864 
4865   LastRecord.PossibleDerefs.erase(StrippedExpr);
4866 }
4867 
4868 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4869   if (isUnevaluatedContext())
4870     return;
4871 
4872   QualType ResultTy = E->getType();
4873   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4874 
4875   // Bail if the element is an array since it is not memory access.
4876   if (isa<ArrayType>(ResultTy))
4877     return;
4878 
4879   if (ResultTy->hasAttr(attr::NoDeref)) {
4880     LastRecord.PossibleDerefs.insert(E);
4881     return;
4882   }
4883 
4884   // Check if the base type is a pointer to a member access of a struct
4885   // marked with noderef.
4886   const Expr *Base = E->getBase();
4887   QualType BaseTy = Base->getType();
4888   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4889     // Not a pointer access
4890     return;
4891 
4892   const MemberExpr *Member = nullptr;
4893   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4894          Member->isArrow())
4895     Base = Member->getBase();
4896 
4897   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4898     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4899       LastRecord.PossibleDerefs.insert(E);
4900   }
4901 }
4902 
4903 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4904                                           Expr *LowerBound,
4905                                           SourceLocation ColonLocFirst,
4906                                           SourceLocation ColonLocSecond,
4907                                           Expr *Length, Expr *Stride,
4908                                           SourceLocation RBLoc) {
4909   if (Base->getType()->isPlaceholderType() &&
4910       !Base->getType()->isSpecificPlaceholderType(
4911           BuiltinType::OMPArraySection)) {
4912     ExprResult Result = CheckPlaceholderExpr(Base);
4913     if (Result.isInvalid())
4914       return ExprError();
4915     Base = Result.get();
4916   }
4917   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4918     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4919     if (Result.isInvalid())
4920       return ExprError();
4921     Result = DefaultLvalueConversion(Result.get());
4922     if (Result.isInvalid())
4923       return ExprError();
4924     LowerBound = Result.get();
4925   }
4926   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4927     ExprResult Result = CheckPlaceholderExpr(Length);
4928     if (Result.isInvalid())
4929       return ExprError();
4930     Result = DefaultLvalueConversion(Result.get());
4931     if (Result.isInvalid())
4932       return ExprError();
4933     Length = Result.get();
4934   }
4935   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4936     ExprResult Result = CheckPlaceholderExpr(Stride);
4937     if (Result.isInvalid())
4938       return ExprError();
4939     Result = DefaultLvalueConversion(Result.get());
4940     if (Result.isInvalid())
4941       return ExprError();
4942     Stride = Result.get();
4943   }
4944 
4945   // Build an unanalyzed expression if either operand is type-dependent.
4946   if (Base->isTypeDependent() ||
4947       (LowerBound &&
4948        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4949       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4950       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4951     return new (Context) OMPArraySectionExpr(
4952         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4953         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4954   }
4955 
4956   // Perform default conversions.
4957   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4958   QualType ResultTy;
4959   if (OriginalTy->isAnyPointerType()) {
4960     ResultTy = OriginalTy->getPointeeType();
4961   } else if (OriginalTy->isArrayType()) {
4962     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4963   } else {
4964     return ExprError(
4965         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4966         << Base->getSourceRange());
4967   }
4968   // C99 6.5.2.1p1
4969   if (LowerBound) {
4970     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4971                                                       LowerBound);
4972     if (Res.isInvalid())
4973       return ExprError(Diag(LowerBound->getExprLoc(),
4974                             diag::err_omp_typecheck_section_not_integer)
4975                        << 0 << LowerBound->getSourceRange());
4976     LowerBound = Res.get();
4977 
4978     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4979         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4980       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4981           << 0 << LowerBound->getSourceRange();
4982   }
4983   if (Length) {
4984     auto Res =
4985         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4986     if (Res.isInvalid())
4987       return ExprError(Diag(Length->getExprLoc(),
4988                             diag::err_omp_typecheck_section_not_integer)
4989                        << 1 << Length->getSourceRange());
4990     Length = Res.get();
4991 
4992     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4993         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4994       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4995           << 1 << Length->getSourceRange();
4996   }
4997   if (Stride) {
4998     ExprResult Res =
4999         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5000     if (Res.isInvalid())
5001       return ExprError(Diag(Stride->getExprLoc(),
5002                             diag::err_omp_typecheck_section_not_integer)
5003                        << 1 << Stride->getSourceRange());
5004     Stride = Res.get();
5005 
5006     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5007         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5008       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5009           << 1 << Stride->getSourceRange();
5010   }
5011 
5012   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5013   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5014   // type. Note that functions are not objects, and that (in C99 parlance)
5015   // incomplete types are not object types.
5016   if (ResultTy->isFunctionType()) {
5017     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5018         << ResultTy << Base->getSourceRange();
5019     return ExprError();
5020   }
5021 
5022   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5023                           diag::err_omp_section_incomplete_type, Base))
5024     return ExprError();
5025 
5026   if (LowerBound && !OriginalTy->isAnyPointerType()) {
5027     Expr::EvalResult Result;
5028     if (LowerBound->EvaluateAsInt(Result, Context)) {
5029       // OpenMP 5.0, [2.1.5 Array Sections]
5030       // The array section must be a subset of the original array.
5031       llvm::APSInt LowerBoundValue = Result.Val.getInt();
5032       if (LowerBoundValue.isNegative()) {
5033         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5034             << LowerBound->getSourceRange();
5035         return ExprError();
5036       }
5037     }
5038   }
5039 
5040   if (Length) {
5041     Expr::EvalResult Result;
5042     if (Length->EvaluateAsInt(Result, Context)) {
5043       // OpenMP 5.0, [2.1.5 Array Sections]
5044       // The length must evaluate to non-negative integers.
5045       llvm::APSInt LengthValue = Result.Val.getInt();
5046       if (LengthValue.isNegative()) {
5047         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5048             << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5049             << Length->getSourceRange();
5050         return ExprError();
5051       }
5052     }
5053   } else if (ColonLocFirst.isValid() &&
5054              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5055                                       !OriginalTy->isVariableArrayType()))) {
5056     // OpenMP 5.0, [2.1.5 Array Sections]
5057     // When the size of the array dimension is not known, the length must be
5058     // specified explicitly.
5059     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5060         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5061     return ExprError();
5062   }
5063 
5064   if (Stride) {
5065     Expr::EvalResult Result;
5066     if (Stride->EvaluateAsInt(Result, Context)) {
5067       // OpenMP 5.0, [2.1.5 Array Sections]
5068       // The stride must evaluate to a positive integer.
5069       llvm::APSInt StrideValue = Result.Val.getInt();
5070       if (!StrideValue.isStrictlyPositive()) {
5071         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5072             << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5073             << Stride->getSourceRange();
5074         return ExprError();
5075       }
5076     }
5077   }
5078 
5079   if (!Base->getType()->isSpecificPlaceholderType(
5080           BuiltinType::OMPArraySection)) {
5081     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5082     if (Result.isInvalid())
5083       return ExprError();
5084     Base = Result.get();
5085   }
5086   return new (Context) OMPArraySectionExpr(
5087       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5088       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5089 }
5090 
5091 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5092                                           SourceLocation RParenLoc,
5093                                           ArrayRef<Expr *> Dims,
5094                                           ArrayRef<SourceRange> Brackets) {
5095   if (Base->getType()->isPlaceholderType()) {
5096     ExprResult Result = CheckPlaceholderExpr(Base);
5097     if (Result.isInvalid())
5098       return ExprError();
5099     Result = DefaultLvalueConversion(Result.get());
5100     if (Result.isInvalid())
5101       return ExprError();
5102     Base = Result.get();
5103   }
5104   QualType BaseTy = Base->getType();
5105   // Delay analysis of the types/expressions if instantiation/specialization is
5106   // required.
5107   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5108     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5109                                        LParenLoc, RParenLoc, Dims, Brackets);
5110   if (!BaseTy->isPointerType() ||
5111       (!Base->isTypeDependent() &&
5112        BaseTy->getPointeeType()->isIncompleteType()))
5113     return ExprError(Diag(Base->getExprLoc(),
5114                           diag::err_omp_non_pointer_type_array_shaping_base)
5115                      << Base->getSourceRange());
5116 
5117   SmallVector<Expr *, 4> NewDims;
5118   bool ErrorFound = false;
5119   for (Expr *Dim : Dims) {
5120     if (Dim->getType()->isPlaceholderType()) {
5121       ExprResult Result = CheckPlaceholderExpr(Dim);
5122       if (Result.isInvalid()) {
5123         ErrorFound = true;
5124         continue;
5125       }
5126       Result = DefaultLvalueConversion(Result.get());
5127       if (Result.isInvalid()) {
5128         ErrorFound = true;
5129         continue;
5130       }
5131       Dim = Result.get();
5132     }
5133     if (!Dim->isTypeDependent()) {
5134       ExprResult Result =
5135           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5136       if (Result.isInvalid()) {
5137         ErrorFound = true;
5138         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5139             << Dim->getSourceRange();
5140         continue;
5141       }
5142       Dim = Result.get();
5143       Expr::EvalResult EvResult;
5144       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5145         // OpenMP 5.0, [2.1.4 Array Shaping]
5146         // Each si is an integral type expression that must evaluate to a
5147         // positive integer.
5148         llvm::APSInt Value = EvResult.Val.getInt();
5149         if (!Value.isStrictlyPositive()) {
5150           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5151               << toString(Value, /*Radix=*/10, /*Signed=*/true)
5152               << Dim->getSourceRange();
5153           ErrorFound = true;
5154           continue;
5155         }
5156       }
5157     }
5158     NewDims.push_back(Dim);
5159   }
5160   if (ErrorFound)
5161     return ExprError();
5162   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5163                                      LParenLoc, RParenLoc, NewDims, Brackets);
5164 }
5165 
5166 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5167                                       SourceLocation LLoc, SourceLocation RLoc,
5168                                       ArrayRef<OMPIteratorData> Data) {
5169   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5170   bool IsCorrect = true;
5171   for (const OMPIteratorData &D : Data) {
5172     TypeSourceInfo *TInfo = nullptr;
5173     SourceLocation StartLoc;
5174     QualType DeclTy;
5175     if (!D.Type.getAsOpaquePtr()) {
5176       // OpenMP 5.0, 2.1.6 Iterators
5177       // In an iterator-specifier, if the iterator-type is not specified then
5178       // the type of that iterator is of int type.
5179       DeclTy = Context.IntTy;
5180       StartLoc = D.DeclIdentLoc;
5181     } else {
5182       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5183       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5184     }
5185 
5186     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5187                              DeclTy->containsUnexpandedParameterPack() ||
5188                              DeclTy->isInstantiationDependentType();
5189     if (!IsDeclTyDependent) {
5190       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5191         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5192         // The iterator-type must be an integral or pointer type.
5193         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5194             << DeclTy;
5195         IsCorrect = false;
5196         continue;
5197       }
5198       if (DeclTy.isConstant(Context)) {
5199         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5200         // The iterator-type must not be const qualified.
5201         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5202             << DeclTy;
5203         IsCorrect = false;
5204         continue;
5205       }
5206     }
5207 
5208     // Iterator declaration.
5209     assert(D.DeclIdent && "Identifier expected.");
5210     // Always try to create iterator declarator to avoid extra error messages
5211     // about unknown declarations use.
5212     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5213                                D.DeclIdent, DeclTy, TInfo, SC_None);
5214     VD->setImplicit();
5215     if (S) {
5216       // Check for conflicting previous declaration.
5217       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5218       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5219                             ForVisibleRedeclaration);
5220       Previous.suppressDiagnostics();
5221       LookupName(Previous, S);
5222 
5223       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5224                            /*AllowInlineNamespace=*/false);
5225       if (!Previous.empty()) {
5226         NamedDecl *Old = Previous.getRepresentativeDecl();
5227         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5228         Diag(Old->getLocation(), diag::note_previous_definition);
5229       } else {
5230         PushOnScopeChains(VD, S);
5231       }
5232     } else {
5233       CurContext->addDecl(VD);
5234     }
5235     Expr *Begin = D.Range.Begin;
5236     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5237       ExprResult BeginRes =
5238           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5239       Begin = BeginRes.get();
5240     }
5241     Expr *End = D.Range.End;
5242     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5243       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5244       End = EndRes.get();
5245     }
5246     Expr *Step = D.Range.Step;
5247     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5248       if (!Step->getType()->isIntegralType(Context)) {
5249         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5250             << Step << Step->getSourceRange();
5251         IsCorrect = false;
5252         continue;
5253       }
5254       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5255       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5256       // If the step expression of a range-specification equals zero, the
5257       // behavior is unspecified.
5258       if (Result && Result->isZero()) {
5259         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5260             << Step << Step->getSourceRange();
5261         IsCorrect = false;
5262         continue;
5263       }
5264     }
5265     if (!Begin || !End || !IsCorrect) {
5266       IsCorrect = false;
5267       continue;
5268     }
5269     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5270     IDElem.IteratorDecl = VD;
5271     IDElem.AssignmentLoc = D.AssignLoc;
5272     IDElem.Range.Begin = Begin;
5273     IDElem.Range.End = End;
5274     IDElem.Range.Step = Step;
5275     IDElem.ColonLoc = D.ColonLoc;
5276     IDElem.SecondColonLoc = D.SecColonLoc;
5277   }
5278   if (!IsCorrect) {
5279     // Invalidate all created iterator declarations if error is found.
5280     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5281       if (Decl *ID = D.IteratorDecl)
5282         ID->setInvalidDecl();
5283     }
5284     return ExprError();
5285   }
5286   SmallVector<OMPIteratorHelperData, 4> Helpers;
5287   if (!CurContext->isDependentContext()) {
5288     // Build number of ityeration for each iteration range.
5289     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5290     // ((Begini-Stepi-1-Endi) / -Stepi);
5291     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5292       // (Endi - Begini)
5293       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5294                                           D.Range.Begin);
5295       if(!Res.isUsable()) {
5296         IsCorrect = false;
5297         continue;
5298       }
5299       ExprResult St, St1;
5300       if (D.Range.Step) {
5301         St = D.Range.Step;
5302         // (Endi - Begini) + Stepi
5303         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5304         if (!Res.isUsable()) {
5305           IsCorrect = false;
5306           continue;
5307         }
5308         // (Endi - Begini) + Stepi - 1
5309         Res =
5310             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5311                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5312         if (!Res.isUsable()) {
5313           IsCorrect = false;
5314           continue;
5315         }
5316         // ((Endi - Begini) + Stepi - 1) / Stepi
5317         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5318         if (!Res.isUsable()) {
5319           IsCorrect = false;
5320           continue;
5321         }
5322         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5323         // (Begini - Endi)
5324         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5325                                              D.Range.Begin, D.Range.End);
5326         if (!Res1.isUsable()) {
5327           IsCorrect = false;
5328           continue;
5329         }
5330         // (Begini - Endi) - Stepi
5331         Res1 =
5332             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5333         if (!Res1.isUsable()) {
5334           IsCorrect = false;
5335           continue;
5336         }
5337         // (Begini - Endi) - Stepi - 1
5338         Res1 =
5339             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5340                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5341         if (!Res1.isUsable()) {
5342           IsCorrect = false;
5343           continue;
5344         }
5345         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5346         Res1 =
5347             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5348         if (!Res1.isUsable()) {
5349           IsCorrect = false;
5350           continue;
5351         }
5352         // Stepi > 0.
5353         ExprResult CmpRes =
5354             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5355                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5356         if (!CmpRes.isUsable()) {
5357           IsCorrect = false;
5358           continue;
5359         }
5360         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5361                                  Res.get(), Res1.get());
5362         if (!Res.isUsable()) {
5363           IsCorrect = false;
5364           continue;
5365         }
5366       }
5367       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5368       if (!Res.isUsable()) {
5369         IsCorrect = false;
5370         continue;
5371       }
5372 
5373       // Build counter update.
5374       // Build counter.
5375       auto *CounterVD =
5376           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5377                           D.IteratorDecl->getBeginLoc(), nullptr,
5378                           Res.get()->getType(), nullptr, SC_None);
5379       CounterVD->setImplicit();
5380       ExprResult RefRes =
5381           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5382                            D.IteratorDecl->getBeginLoc());
5383       // Build counter update.
5384       // I = Begini + counter * Stepi;
5385       ExprResult UpdateRes;
5386       if (D.Range.Step) {
5387         UpdateRes = CreateBuiltinBinOp(
5388             D.AssignmentLoc, BO_Mul,
5389             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5390       } else {
5391         UpdateRes = DefaultLvalueConversion(RefRes.get());
5392       }
5393       if (!UpdateRes.isUsable()) {
5394         IsCorrect = false;
5395         continue;
5396       }
5397       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5398                                      UpdateRes.get());
5399       if (!UpdateRes.isUsable()) {
5400         IsCorrect = false;
5401         continue;
5402       }
5403       ExprResult VDRes =
5404           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5405                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5406                            D.IteratorDecl->getBeginLoc());
5407       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5408                                      UpdateRes.get());
5409       if (!UpdateRes.isUsable()) {
5410         IsCorrect = false;
5411         continue;
5412       }
5413       UpdateRes =
5414           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5415       if (!UpdateRes.isUsable()) {
5416         IsCorrect = false;
5417         continue;
5418       }
5419       ExprResult CounterUpdateRes =
5420           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5421       if (!CounterUpdateRes.isUsable()) {
5422         IsCorrect = false;
5423         continue;
5424       }
5425       CounterUpdateRes =
5426           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5427       if (!CounterUpdateRes.isUsable()) {
5428         IsCorrect = false;
5429         continue;
5430       }
5431       OMPIteratorHelperData &HD = Helpers.emplace_back();
5432       HD.CounterVD = CounterVD;
5433       HD.Upper = Res.get();
5434       HD.Update = UpdateRes.get();
5435       HD.CounterUpdate = CounterUpdateRes.get();
5436     }
5437   } else {
5438     Helpers.assign(ID.size(), {});
5439   }
5440   if (!IsCorrect) {
5441     // Invalidate all created iterator declarations if error is found.
5442     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5443       if (Decl *ID = D.IteratorDecl)
5444         ID->setInvalidDecl();
5445     }
5446     return ExprError();
5447   }
5448   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5449                                  LLoc, RLoc, ID, Helpers);
5450 }
5451 
5452 ExprResult
5453 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5454                                       Expr *Idx, SourceLocation RLoc) {
5455   Expr *LHSExp = Base;
5456   Expr *RHSExp = Idx;
5457 
5458   ExprValueKind VK = VK_LValue;
5459   ExprObjectKind OK = OK_Ordinary;
5460 
5461   // Per C++ core issue 1213, the result is an xvalue if either operand is
5462   // a non-lvalue array, and an lvalue otherwise.
5463   if (getLangOpts().CPlusPlus11) {
5464     for (auto *Op : {LHSExp, RHSExp}) {
5465       Op = Op->IgnoreImplicit();
5466       if (Op->getType()->isArrayType() && !Op->isLValue())
5467         VK = VK_XValue;
5468     }
5469   }
5470 
5471   // Perform default conversions.
5472   if (!LHSExp->getType()->getAs<VectorType>()) {
5473     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5474     if (Result.isInvalid())
5475       return ExprError();
5476     LHSExp = Result.get();
5477   }
5478   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5479   if (Result.isInvalid())
5480     return ExprError();
5481   RHSExp = Result.get();
5482 
5483   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5484 
5485   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5486   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5487   // in the subscript position. As a result, we need to derive the array base
5488   // and index from the expression types.
5489   Expr *BaseExpr, *IndexExpr;
5490   QualType ResultType;
5491   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5492     BaseExpr = LHSExp;
5493     IndexExpr = RHSExp;
5494     ResultType = Context.DependentTy;
5495   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5496     BaseExpr = LHSExp;
5497     IndexExpr = RHSExp;
5498     ResultType = PTy->getPointeeType();
5499   } else if (const ObjCObjectPointerType *PTy =
5500                LHSTy->getAs<ObjCObjectPointerType>()) {
5501     BaseExpr = LHSExp;
5502     IndexExpr = RHSExp;
5503 
5504     // Use custom logic if this should be the pseudo-object subscript
5505     // expression.
5506     if (!LangOpts.isSubscriptPointerArithmetic())
5507       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5508                                           nullptr);
5509 
5510     ResultType = PTy->getPointeeType();
5511   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5512      // Handle the uncommon case of "123[Ptr]".
5513     BaseExpr = RHSExp;
5514     IndexExpr = LHSExp;
5515     ResultType = PTy->getPointeeType();
5516   } else if (const ObjCObjectPointerType *PTy =
5517                RHSTy->getAs<ObjCObjectPointerType>()) {
5518      // Handle the uncommon case of "123[Ptr]".
5519     BaseExpr = RHSExp;
5520     IndexExpr = LHSExp;
5521     ResultType = PTy->getPointeeType();
5522     if (!LangOpts.isSubscriptPointerArithmetic()) {
5523       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5524         << ResultType << BaseExpr->getSourceRange();
5525       return ExprError();
5526     }
5527   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5528     BaseExpr = LHSExp;    // vectors: V[123]
5529     IndexExpr = RHSExp;
5530     // We apply C++ DR1213 to vector subscripting too.
5531     if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5532       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5533       if (Materialized.isInvalid())
5534         return ExprError();
5535       LHSExp = Materialized.get();
5536     }
5537     VK = LHSExp->getValueKind();
5538     if (VK != VK_PRValue)
5539       OK = OK_VectorComponent;
5540 
5541     ResultType = VTy->getElementType();
5542     QualType BaseType = BaseExpr->getType();
5543     Qualifiers BaseQuals = BaseType.getQualifiers();
5544     Qualifiers MemberQuals = ResultType.getQualifiers();
5545     Qualifiers Combined = BaseQuals + MemberQuals;
5546     if (Combined != MemberQuals)
5547       ResultType = Context.getQualifiedType(ResultType, Combined);
5548   } else if (LHSTy->isArrayType()) {
5549     // If we see an array that wasn't promoted by
5550     // DefaultFunctionArrayLvalueConversion, it must be an array that
5551     // wasn't promoted because of the C90 rule that doesn't
5552     // allow promoting non-lvalue arrays.  Warn, then
5553     // force the promotion here.
5554     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5555         << LHSExp->getSourceRange();
5556     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5557                                CK_ArrayToPointerDecay).get();
5558     LHSTy = LHSExp->getType();
5559 
5560     BaseExpr = LHSExp;
5561     IndexExpr = RHSExp;
5562     ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5563   } else if (RHSTy->isArrayType()) {
5564     // Same as previous, except for 123[f().a] case
5565     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5566         << RHSExp->getSourceRange();
5567     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5568                                CK_ArrayToPointerDecay).get();
5569     RHSTy = RHSExp->getType();
5570 
5571     BaseExpr = RHSExp;
5572     IndexExpr = LHSExp;
5573     ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5574   } else {
5575     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5576        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5577   }
5578   // C99 6.5.2.1p1
5579   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5580     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5581                      << IndexExpr->getSourceRange());
5582 
5583   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5584        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5585          && !IndexExpr->isTypeDependent())
5586     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5587 
5588   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5589   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5590   // type. Note that Functions are not objects, and that (in C99 parlance)
5591   // incomplete types are not object types.
5592   if (ResultType->isFunctionType()) {
5593     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5594         << ResultType << BaseExpr->getSourceRange();
5595     return ExprError();
5596   }
5597 
5598   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5599     // GNU extension: subscripting on pointer to void
5600     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5601       << BaseExpr->getSourceRange();
5602 
5603     // C forbids expressions of unqualified void type from being l-values.
5604     // See IsCForbiddenLValueType.
5605     if (!ResultType.hasQualifiers())
5606       VK = VK_PRValue;
5607   } else if (!ResultType->isDependentType() &&
5608              RequireCompleteSizedType(
5609                  LLoc, ResultType,
5610                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5611     return ExprError();
5612 
5613   assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5614          !ResultType.isCForbiddenLValueType());
5615 
5616   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5617       FunctionScopes.size() > 1) {
5618     if (auto *TT =
5619             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5620       for (auto I = FunctionScopes.rbegin(),
5621                 E = std::prev(FunctionScopes.rend());
5622            I != E; ++I) {
5623         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5624         if (CSI == nullptr)
5625           break;
5626         DeclContext *DC = nullptr;
5627         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5628           DC = LSI->CallOperator;
5629         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5630           DC = CRSI->TheCapturedDecl;
5631         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5632           DC = BSI->TheDecl;
5633         if (DC) {
5634           if (DC->containsDecl(TT->getDecl()))
5635             break;
5636           captureVariablyModifiedType(
5637               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5638         }
5639       }
5640     }
5641   }
5642 
5643   return new (Context)
5644       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5645 }
5646 
5647 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5648                                   ParmVarDecl *Param) {
5649   if (Param->hasUnparsedDefaultArg()) {
5650     // If we've already cleared out the location for the default argument,
5651     // that means we're parsing it right now.
5652     if (!UnparsedDefaultArgLocs.count(Param)) {
5653       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5654       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5655       Param->setInvalidDecl();
5656       return true;
5657     }
5658 
5659     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5660         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5661     Diag(UnparsedDefaultArgLocs[Param],
5662          diag::note_default_argument_declared_here);
5663     return true;
5664   }
5665 
5666   if (Param->hasUninstantiatedDefaultArg() &&
5667       InstantiateDefaultArgument(CallLoc, FD, Param))
5668     return true;
5669 
5670   assert(Param->hasInit() && "default argument but no initializer?");
5671 
5672   // If the default expression creates temporaries, we need to
5673   // push them to the current stack of expression temporaries so they'll
5674   // be properly destroyed.
5675   // FIXME: We should really be rebuilding the default argument with new
5676   // bound temporaries; see the comment in PR5810.
5677   // We don't need to do that with block decls, though, because
5678   // blocks in default argument expression can never capture anything.
5679   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5680     // Set the "needs cleanups" bit regardless of whether there are
5681     // any explicit objects.
5682     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5683 
5684     // Append all the objects to the cleanup list.  Right now, this
5685     // should always be a no-op, because blocks in default argument
5686     // expressions should never be able to capture anything.
5687     assert(!Init->getNumObjects() &&
5688            "default argument expression has capturing blocks?");
5689   }
5690 
5691   // We already type-checked the argument, so we know it works.
5692   // Just mark all of the declarations in this potentially-evaluated expression
5693   // as being "referenced".
5694   EnterExpressionEvaluationContext EvalContext(
5695       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5696   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5697                                    /*SkipLocalVariables=*/true);
5698   return false;
5699 }
5700 
5701 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5702                                         FunctionDecl *FD, ParmVarDecl *Param) {
5703   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5704   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5705     return ExprError();
5706   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5707 }
5708 
5709 Sema::VariadicCallType
5710 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5711                           Expr *Fn) {
5712   if (Proto && Proto->isVariadic()) {
5713     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5714       return VariadicConstructor;
5715     else if (Fn && Fn->getType()->isBlockPointerType())
5716       return VariadicBlock;
5717     else if (FDecl) {
5718       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5719         if (Method->isInstance())
5720           return VariadicMethod;
5721     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5722       return VariadicMethod;
5723     return VariadicFunction;
5724   }
5725   return VariadicDoesNotApply;
5726 }
5727 
5728 namespace {
5729 class FunctionCallCCC final : public FunctionCallFilterCCC {
5730 public:
5731   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5732                   unsigned NumArgs, MemberExpr *ME)
5733       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5734         FunctionName(FuncName) {}
5735 
5736   bool ValidateCandidate(const TypoCorrection &candidate) override {
5737     if (!candidate.getCorrectionSpecifier() ||
5738         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5739       return false;
5740     }
5741 
5742     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5743   }
5744 
5745   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5746     return std::make_unique<FunctionCallCCC>(*this);
5747   }
5748 
5749 private:
5750   const IdentifierInfo *const FunctionName;
5751 };
5752 }
5753 
5754 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5755                                                FunctionDecl *FDecl,
5756                                                ArrayRef<Expr *> Args) {
5757   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5758   DeclarationName FuncName = FDecl->getDeclName();
5759   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5760 
5761   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5762   if (TypoCorrection Corrected = S.CorrectTypo(
5763           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5764           S.getScopeForContext(S.CurContext), nullptr, CCC,
5765           Sema::CTK_ErrorRecovery)) {
5766     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5767       if (Corrected.isOverloaded()) {
5768         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5769         OverloadCandidateSet::iterator Best;
5770         for (NamedDecl *CD : Corrected) {
5771           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5772             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5773                                    OCS);
5774         }
5775         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5776         case OR_Success:
5777           ND = Best->FoundDecl;
5778           Corrected.setCorrectionDecl(ND);
5779           break;
5780         default:
5781           break;
5782         }
5783       }
5784       ND = ND->getUnderlyingDecl();
5785       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5786         return Corrected;
5787     }
5788   }
5789   return TypoCorrection();
5790 }
5791 
5792 /// ConvertArgumentsForCall - Converts the arguments specified in
5793 /// Args/NumArgs to the parameter types of the function FDecl with
5794 /// function prototype Proto. Call is the call expression itself, and
5795 /// Fn is the function expression. For a C++ member function, this
5796 /// routine does not attempt to convert the object argument. Returns
5797 /// true if the call is ill-formed.
5798 bool
5799 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5800                               FunctionDecl *FDecl,
5801                               const FunctionProtoType *Proto,
5802                               ArrayRef<Expr *> Args,
5803                               SourceLocation RParenLoc,
5804                               bool IsExecConfig) {
5805   // Bail out early if calling a builtin with custom typechecking.
5806   if (FDecl)
5807     if (unsigned ID = FDecl->getBuiltinID())
5808       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5809         return false;
5810 
5811   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5812   // assignment, to the types of the corresponding parameter, ...
5813   unsigned NumParams = Proto->getNumParams();
5814   bool Invalid = false;
5815   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5816   unsigned FnKind = Fn->getType()->isBlockPointerType()
5817                        ? 1 /* block */
5818                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5819                                        : 0 /* function */);
5820 
5821   // If too few arguments are available (and we don't have default
5822   // arguments for the remaining parameters), don't make the call.
5823   if (Args.size() < NumParams) {
5824     if (Args.size() < MinArgs) {
5825       TypoCorrection TC;
5826       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5827         unsigned diag_id =
5828             MinArgs == NumParams && !Proto->isVariadic()
5829                 ? diag::err_typecheck_call_too_few_args_suggest
5830                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5831         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5832                                         << static_cast<unsigned>(Args.size())
5833                                         << TC.getCorrectionRange());
5834       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5835         Diag(RParenLoc,
5836              MinArgs == NumParams && !Proto->isVariadic()
5837                  ? diag::err_typecheck_call_too_few_args_one
5838                  : diag::err_typecheck_call_too_few_args_at_least_one)
5839             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5840       else
5841         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5842                             ? diag::err_typecheck_call_too_few_args
5843                             : diag::err_typecheck_call_too_few_args_at_least)
5844             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5845             << Fn->getSourceRange();
5846 
5847       // Emit the location of the prototype.
5848       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5849         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5850 
5851       return true;
5852     }
5853     // We reserve space for the default arguments when we create
5854     // the call expression, before calling ConvertArgumentsForCall.
5855     assert((Call->getNumArgs() == NumParams) &&
5856            "We should have reserved space for the default arguments before!");
5857   }
5858 
5859   // If too many are passed and not variadic, error on the extras and drop
5860   // them.
5861   if (Args.size() > NumParams) {
5862     if (!Proto->isVariadic()) {
5863       TypoCorrection TC;
5864       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5865         unsigned diag_id =
5866             MinArgs == NumParams && !Proto->isVariadic()
5867                 ? diag::err_typecheck_call_too_many_args_suggest
5868                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5869         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5870                                         << static_cast<unsigned>(Args.size())
5871                                         << TC.getCorrectionRange());
5872       } else if (NumParams == 1 && FDecl &&
5873                  FDecl->getParamDecl(0)->getDeclName())
5874         Diag(Args[NumParams]->getBeginLoc(),
5875              MinArgs == NumParams
5876                  ? diag::err_typecheck_call_too_many_args_one
5877                  : diag::err_typecheck_call_too_many_args_at_most_one)
5878             << FnKind << FDecl->getParamDecl(0)
5879             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5880             << SourceRange(Args[NumParams]->getBeginLoc(),
5881                            Args.back()->getEndLoc());
5882       else
5883         Diag(Args[NumParams]->getBeginLoc(),
5884              MinArgs == NumParams
5885                  ? diag::err_typecheck_call_too_many_args
5886                  : diag::err_typecheck_call_too_many_args_at_most)
5887             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5888             << Fn->getSourceRange()
5889             << SourceRange(Args[NumParams]->getBeginLoc(),
5890                            Args.back()->getEndLoc());
5891 
5892       // Emit the location of the prototype.
5893       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5894         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5895 
5896       // This deletes the extra arguments.
5897       Call->shrinkNumArgs(NumParams);
5898       return true;
5899     }
5900   }
5901   SmallVector<Expr *, 8> AllArgs;
5902   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5903 
5904   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5905                                    AllArgs, CallType);
5906   if (Invalid)
5907     return true;
5908   unsigned TotalNumArgs = AllArgs.size();
5909   for (unsigned i = 0; i < TotalNumArgs; ++i)
5910     Call->setArg(i, AllArgs[i]);
5911 
5912   Call->computeDependence();
5913   return false;
5914 }
5915 
5916 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5917                                   const FunctionProtoType *Proto,
5918                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5919                                   SmallVectorImpl<Expr *> &AllArgs,
5920                                   VariadicCallType CallType, bool AllowExplicit,
5921                                   bool IsListInitialization) {
5922   unsigned NumParams = Proto->getNumParams();
5923   bool Invalid = false;
5924   size_t ArgIx = 0;
5925   // Continue to check argument types (even if we have too few/many args).
5926   for (unsigned i = FirstParam; i < NumParams; i++) {
5927     QualType ProtoArgType = Proto->getParamType(i);
5928 
5929     Expr *Arg;
5930     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5931     if (ArgIx < Args.size()) {
5932       Arg = Args[ArgIx++];
5933 
5934       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5935                               diag::err_call_incomplete_argument, Arg))
5936         return true;
5937 
5938       // Strip the unbridged-cast placeholder expression off, if applicable.
5939       bool CFAudited = false;
5940       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5941           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5942           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5943         Arg = stripARCUnbridgedCast(Arg);
5944       else if (getLangOpts().ObjCAutoRefCount &&
5945                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5946                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5947         CFAudited = true;
5948 
5949       if (Proto->getExtParameterInfo(i).isNoEscape() &&
5950           ProtoArgType->isBlockPointerType())
5951         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5952           BE->getBlockDecl()->setDoesNotEscape();
5953 
5954       InitializedEntity Entity =
5955           Param ? InitializedEntity::InitializeParameter(Context, Param,
5956                                                          ProtoArgType)
5957                 : InitializedEntity::InitializeParameter(
5958                       Context, ProtoArgType, Proto->isParamConsumed(i));
5959 
5960       // Remember that parameter belongs to a CF audited API.
5961       if (CFAudited)
5962         Entity.setParameterCFAudited();
5963 
5964       ExprResult ArgE = PerformCopyInitialization(
5965           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5966       if (ArgE.isInvalid())
5967         return true;
5968 
5969       Arg = ArgE.getAs<Expr>();
5970     } else {
5971       assert(Param && "can't use default arguments without a known callee");
5972 
5973       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5974       if (ArgExpr.isInvalid())
5975         return true;
5976 
5977       Arg = ArgExpr.getAs<Expr>();
5978     }
5979 
5980     // Check for array bounds violations for each argument to the call. This
5981     // check only triggers warnings when the argument isn't a more complex Expr
5982     // with its own checking, such as a BinaryOperator.
5983     CheckArrayAccess(Arg);
5984 
5985     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5986     CheckStaticArrayArgument(CallLoc, Param, Arg);
5987 
5988     AllArgs.push_back(Arg);
5989   }
5990 
5991   // If this is a variadic call, handle args passed through "...".
5992   if (CallType != VariadicDoesNotApply) {
5993     // Assume that extern "C" functions with variadic arguments that
5994     // return __unknown_anytype aren't *really* variadic.
5995     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5996         FDecl->isExternC()) {
5997       for (Expr *A : Args.slice(ArgIx)) {
5998         QualType paramType; // ignored
5999         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6000         Invalid |= arg.isInvalid();
6001         AllArgs.push_back(arg.get());
6002       }
6003 
6004     // Otherwise do argument promotion, (C99 6.5.2.2p7).
6005     } else {
6006       for (Expr *A : Args.slice(ArgIx)) {
6007         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6008         Invalid |= Arg.isInvalid();
6009         AllArgs.push_back(Arg.get());
6010       }
6011     }
6012 
6013     // Check for array bounds violations.
6014     for (Expr *A : Args.slice(ArgIx))
6015       CheckArrayAccess(A);
6016   }
6017   return Invalid;
6018 }
6019 
6020 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6021   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6022   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6023     TL = DTL.getOriginalLoc();
6024   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6025     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6026       << ATL.getLocalSourceRange();
6027 }
6028 
6029 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6030 /// array parameter, check that it is non-null, and that if it is formed by
6031 /// array-to-pointer decay, the underlying array is sufficiently large.
6032 ///
6033 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6034 /// array type derivation, then for each call to the function, the value of the
6035 /// corresponding actual argument shall provide access to the first element of
6036 /// an array with at least as many elements as specified by the size expression.
6037 void
6038 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6039                                ParmVarDecl *Param,
6040                                const Expr *ArgExpr) {
6041   // Static array parameters are not supported in C++.
6042   if (!Param || getLangOpts().CPlusPlus)
6043     return;
6044 
6045   QualType OrigTy = Param->getOriginalType();
6046 
6047   const ArrayType *AT = Context.getAsArrayType(OrigTy);
6048   if (!AT || AT->getSizeModifier() != ArrayType::Static)
6049     return;
6050 
6051   if (ArgExpr->isNullPointerConstant(Context,
6052                                      Expr::NPC_NeverValueDependent)) {
6053     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6054     DiagnoseCalleeStaticArrayParam(*this, Param);
6055     return;
6056   }
6057 
6058   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6059   if (!CAT)
6060     return;
6061 
6062   const ConstantArrayType *ArgCAT =
6063     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6064   if (!ArgCAT)
6065     return;
6066 
6067   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6068                                              ArgCAT->getElementType())) {
6069     if (ArgCAT->getSize().ult(CAT->getSize())) {
6070       Diag(CallLoc, diag::warn_static_array_too_small)
6071           << ArgExpr->getSourceRange()
6072           << (unsigned)ArgCAT->getSize().getZExtValue()
6073           << (unsigned)CAT->getSize().getZExtValue() << 0;
6074       DiagnoseCalleeStaticArrayParam(*this, Param);
6075     }
6076     return;
6077   }
6078 
6079   Optional<CharUnits> ArgSize =
6080       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6081   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6082   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6083     Diag(CallLoc, diag::warn_static_array_too_small)
6084         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6085         << (unsigned)ParmSize->getQuantity() << 1;
6086     DiagnoseCalleeStaticArrayParam(*this, Param);
6087   }
6088 }
6089 
6090 /// Given a function expression of unknown-any type, try to rebuild it
6091 /// to have a function type.
6092 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6093 
6094 /// Is the given type a placeholder that we need to lower out
6095 /// immediately during argument processing?
6096 static bool isPlaceholderToRemoveAsArg(QualType type) {
6097   // Placeholders are never sugared.
6098   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6099   if (!placeholder) return false;
6100 
6101   switch (placeholder->getKind()) {
6102   // Ignore all the non-placeholder types.
6103 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6104   case BuiltinType::Id:
6105 #include "clang/Basic/OpenCLImageTypes.def"
6106 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6107   case BuiltinType::Id:
6108 #include "clang/Basic/OpenCLExtensionTypes.def"
6109   // In practice we'll never use this, since all SVE types are sugared
6110   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6111 #define SVE_TYPE(Name, Id, SingletonId) \
6112   case BuiltinType::Id:
6113 #include "clang/Basic/AArch64SVEACLETypes.def"
6114 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6115   case BuiltinType::Id:
6116 #include "clang/Basic/PPCTypes.def"
6117 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6118 #include "clang/Basic/RISCVVTypes.def"
6119 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6120 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6121 #include "clang/AST/BuiltinTypes.def"
6122     return false;
6123 
6124   // We cannot lower out overload sets; they might validly be resolved
6125   // by the call machinery.
6126   case BuiltinType::Overload:
6127     return false;
6128 
6129   // Unbridged casts in ARC can be handled in some call positions and
6130   // should be left in place.
6131   case BuiltinType::ARCUnbridgedCast:
6132     return false;
6133 
6134   // Pseudo-objects should be converted as soon as possible.
6135   case BuiltinType::PseudoObject:
6136     return true;
6137 
6138   // The debugger mode could theoretically but currently does not try
6139   // to resolve unknown-typed arguments based on known parameter types.
6140   case BuiltinType::UnknownAny:
6141     return true;
6142 
6143   // These are always invalid as call arguments and should be reported.
6144   case BuiltinType::BoundMember:
6145   case BuiltinType::BuiltinFn:
6146   case BuiltinType::IncompleteMatrixIdx:
6147   case BuiltinType::OMPArraySection:
6148   case BuiltinType::OMPArrayShaping:
6149   case BuiltinType::OMPIterator:
6150     return true;
6151 
6152   }
6153   llvm_unreachable("bad builtin type kind");
6154 }
6155 
6156 /// Check an argument list for placeholders that we won't try to
6157 /// handle later.
6158 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6159   // Apply this processing to all the arguments at once instead of
6160   // dying at the first failure.
6161   bool hasInvalid = false;
6162   for (size_t i = 0, e = args.size(); i != e; i++) {
6163     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6164       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6165       if (result.isInvalid()) hasInvalid = true;
6166       else args[i] = result.get();
6167     }
6168   }
6169   return hasInvalid;
6170 }
6171 
6172 /// If a builtin function has a pointer argument with no explicit address
6173 /// space, then it should be able to accept a pointer to any address
6174 /// space as input.  In order to do this, we need to replace the
6175 /// standard builtin declaration with one that uses the same address space
6176 /// as the call.
6177 ///
6178 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6179 ///                  it does not contain any pointer arguments without
6180 ///                  an address space qualifer.  Otherwise the rewritten
6181 ///                  FunctionDecl is returned.
6182 /// TODO: Handle pointer return types.
6183 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6184                                                 FunctionDecl *FDecl,
6185                                                 MultiExprArg ArgExprs) {
6186 
6187   QualType DeclType = FDecl->getType();
6188   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6189 
6190   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6191       ArgExprs.size() < FT->getNumParams())
6192     return nullptr;
6193 
6194   bool NeedsNewDecl = false;
6195   unsigned i = 0;
6196   SmallVector<QualType, 8> OverloadParams;
6197 
6198   for (QualType ParamType : FT->param_types()) {
6199 
6200     // Convert array arguments to pointer to simplify type lookup.
6201     ExprResult ArgRes =
6202         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6203     if (ArgRes.isInvalid())
6204       return nullptr;
6205     Expr *Arg = ArgRes.get();
6206     QualType ArgType = Arg->getType();
6207     if (!ParamType->isPointerType() ||
6208         ParamType.hasAddressSpace() ||
6209         !ArgType->isPointerType() ||
6210         !ArgType->getPointeeType().hasAddressSpace()) {
6211       OverloadParams.push_back(ParamType);
6212       continue;
6213     }
6214 
6215     QualType PointeeType = ParamType->getPointeeType();
6216     if (PointeeType.hasAddressSpace())
6217       continue;
6218 
6219     NeedsNewDecl = true;
6220     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6221 
6222     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6223     OverloadParams.push_back(Context.getPointerType(PointeeType));
6224   }
6225 
6226   if (!NeedsNewDecl)
6227     return nullptr;
6228 
6229   FunctionProtoType::ExtProtoInfo EPI;
6230   EPI.Variadic = FT->isVariadic();
6231   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6232                                                 OverloadParams, EPI);
6233   DeclContext *Parent = FDecl->getParent();
6234   FunctionDecl *OverloadDecl = FunctionDecl::Create(
6235       Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6236       FDecl->getIdentifier(), OverloadTy,
6237       /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6238       false,
6239       /*hasPrototype=*/true);
6240   SmallVector<ParmVarDecl*, 16> Params;
6241   FT = cast<FunctionProtoType>(OverloadTy);
6242   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6243     QualType ParamType = FT->getParamType(i);
6244     ParmVarDecl *Parm =
6245         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6246                                 SourceLocation(), nullptr, ParamType,
6247                                 /*TInfo=*/nullptr, SC_None, nullptr);
6248     Parm->setScopeInfo(0, i);
6249     Params.push_back(Parm);
6250   }
6251   OverloadDecl->setParams(Params);
6252   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6253   return OverloadDecl;
6254 }
6255 
6256 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6257                                     FunctionDecl *Callee,
6258                                     MultiExprArg ArgExprs) {
6259   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6260   // similar attributes) really don't like it when functions are called with an
6261   // invalid number of args.
6262   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6263                          /*PartialOverloading=*/false) &&
6264       !Callee->isVariadic())
6265     return;
6266   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6267     return;
6268 
6269   if (const EnableIfAttr *Attr =
6270           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6271     S.Diag(Fn->getBeginLoc(),
6272            isa<CXXMethodDecl>(Callee)
6273                ? diag::err_ovl_no_viable_member_function_in_call
6274                : diag::err_ovl_no_viable_function_in_call)
6275         << Callee << Callee->getSourceRange();
6276     S.Diag(Callee->getLocation(),
6277            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6278         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6279     return;
6280   }
6281 }
6282 
6283 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6284     const UnresolvedMemberExpr *const UME, Sema &S) {
6285 
6286   const auto GetFunctionLevelDCIfCXXClass =
6287       [](Sema &S) -> const CXXRecordDecl * {
6288     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6289     if (!DC || !DC->getParent())
6290       return nullptr;
6291 
6292     // If the call to some member function was made from within a member
6293     // function body 'M' return return 'M's parent.
6294     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6295       return MD->getParent()->getCanonicalDecl();
6296     // else the call was made from within a default member initializer of a
6297     // class, so return the class.
6298     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6299       return RD->getCanonicalDecl();
6300     return nullptr;
6301   };
6302   // If our DeclContext is neither a member function nor a class (in the
6303   // case of a lambda in a default member initializer), we can't have an
6304   // enclosing 'this'.
6305 
6306   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6307   if (!CurParentClass)
6308     return false;
6309 
6310   // The naming class for implicit member functions call is the class in which
6311   // name lookup starts.
6312   const CXXRecordDecl *const NamingClass =
6313       UME->getNamingClass()->getCanonicalDecl();
6314   assert(NamingClass && "Must have naming class even for implicit access");
6315 
6316   // If the unresolved member functions were found in a 'naming class' that is
6317   // related (either the same or derived from) to the class that contains the
6318   // member function that itself contained the implicit member access.
6319 
6320   return CurParentClass == NamingClass ||
6321          CurParentClass->isDerivedFrom(NamingClass);
6322 }
6323 
6324 static void
6325 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6326     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6327 
6328   if (!UME)
6329     return;
6330 
6331   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6332   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6333   // already been captured, or if this is an implicit member function call (if
6334   // it isn't, an attempt to capture 'this' should already have been made).
6335   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6336       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6337     return;
6338 
6339   // Check if the naming class in which the unresolved members were found is
6340   // related (same as or is a base of) to the enclosing class.
6341 
6342   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6343     return;
6344 
6345 
6346   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6347   // If the enclosing function is not dependent, then this lambda is
6348   // capture ready, so if we can capture this, do so.
6349   if (!EnclosingFunctionCtx->isDependentContext()) {
6350     // If the current lambda and all enclosing lambdas can capture 'this' -
6351     // then go ahead and capture 'this' (since our unresolved overload set
6352     // contains at least one non-static member function).
6353     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6354       S.CheckCXXThisCapture(CallLoc);
6355   } else if (S.CurContext->isDependentContext()) {
6356     // ... since this is an implicit member reference, that might potentially
6357     // involve a 'this' capture, mark 'this' for potential capture in
6358     // enclosing lambdas.
6359     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6360       CurLSI->addPotentialThisCapture(CallLoc);
6361   }
6362 }
6363 
6364 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6365                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6366                                Expr *ExecConfig) {
6367   ExprResult Call =
6368       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6369                     /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6370   if (Call.isInvalid())
6371     return Call;
6372 
6373   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6374   // language modes.
6375   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6376     if (ULE->hasExplicitTemplateArgs() &&
6377         ULE->decls_begin() == ULE->decls_end()) {
6378       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6379                                  ? diag::warn_cxx17_compat_adl_only_template_id
6380                                  : diag::ext_adl_only_template_id)
6381           << ULE->getName();
6382     }
6383   }
6384 
6385   if (LangOpts.OpenMP)
6386     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6387                            ExecConfig);
6388 
6389   return Call;
6390 }
6391 
6392 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6393 /// This provides the location of the left/right parens and a list of comma
6394 /// locations.
6395 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6396                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6397                                Expr *ExecConfig, bool IsExecConfig,
6398                                bool AllowRecovery) {
6399   // Since this might be a postfix expression, get rid of ParenListExprs.
6400   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6401   if (Result.isInvalid()) return ExprError();
6402   Fn = Result.get();
6403 
6404   if (checkArgsForPlaceholders(*this, ArgExprs))
6405     return ExprError();
6406 
6407   if (getLangOpts().CPlusPlus) {
6408     // If this is a pseudo-destructor expression, build the call immediately.
6409     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6410       if (!ArgExprs.empty()) {
6411         // Pseudo-destructor calls should not have any arguments.
6412         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6413             << FixItHint::CreateRemoval(
6414                    SourceRange(ArgExprs.front()->getBeginLoc(),
6415                                ArgExprs.back()->getEndLoc()));
6416       }
6417 
6418       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6419                               VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6420     }
6421     if (Fn->getType() == Context.PseudoObjectTy) {
6422       ExprResult result = CheckPlaceholderExpr(Fn);
6423       if (result.isInvalid()) return ExprError();
6424       Fn = result.get();
6425     }
6426 
6427     // Determine whether this is a dependent call inside a C++ template,
6428     // in which case we won't do any semantic analysis now.
6429     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6430       if (ExecConfig) {
6431         return CUDAKernelCallExpr::Create(Context, Fn,
6432                                           cast<CallExpr>(ExecConfig), ArgExprs,
6433                                           Context.DependentTy, VK_PRValue,
6434                                           RParenLoc, CurFPFeatureOverrides());
6435       } else {
6436 
6437         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6438             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6439             Fn->getBeginLoc());
6440 
6441         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6442                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6443       }
6444     }
6445 
6446     // Determine whether this is a call to an object (C++ [over.call.object]).
6447     if (Fn->getType()->isRecordType())
6448       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6449                                           RParenLoc);
6450 
6451     if (Fn->getType() == Context.UnknownAnyTy) {
6452       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6453       if (result.isInvalid()) return ExprError();
6454       Fn = result.get();
6455     }
6456 
6457     if (Fn->getType() == Context.BoundMemberTy) {
6458       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6459                                        RParenLoc, ExecConfig, IsExecConfig,
6460                                        AllowRecovery);
6461     }
6462   }
6463 
6464   // Check for overloaded calls.  This can happen even in C due to extensions.
6465   if (Fn->getType() == Context.OverloadTy) {
6466     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6467 
6468     // We aren't supposed to apply this logic if there's an '&' involved.
6469     if (!find.HasFormOfMemberPointer) {
6470       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6471         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6472                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6473       OverloadExpr *ovl = find.Expression;
6474       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6475         return BuildOverloadedCallExpr(
6476             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6477             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6478       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6479                                        RParenLoc, ExecConfig, IsExecConfig,
6480                                        AllowRecovery);
6481     }
6482   }
6483 
6484   // If we're directly calling a function, get the appropriate declaration.
6485   if (Fn->getType() == Context.UnknownAnyTy) {
6486     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6487     if (result.isInvalid()) return ExprError();
6488     Fn = result.get();
6489   }
6490 
6491   Expr *NakedFn = Fn->IgnoreParens();
6492 
6493   bool CallingNDeclIndirectly = false;
6494   NamedDecl *NDecl = nullptr;
6495   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6496     if (UnOp->getOpcode() == UO_AddrOf) {
6497       CallingNDeclIndirectly = true;
6498       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6499     }
6500   }
6501 
6502   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6503     NDecl = DRE->getDecl();
6504 
6505     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6506     if (FDecl && FDecl->getBuiltinID()) {
6507       // Rewrite the function decl for this builtin by replacing parameters
6508       // with no explicit address space with the address space of the arguments
6509       // in ArgExprs.
6510       if ((FDecl =
6511                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6512         NDecl = FDecl;
6513         Fn = DeclRefExpr::Create(
6514             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6515             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6516             nullptr, DRE->isNonOdrUse());
6517       }
6518     }
6519   } else if (isa<MemberExpr>(NakedFn))
6520     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6521 
6522   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6523     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6524                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6525       return ExprError();
6526 
6527     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6528 
6529     // If this expression is a call to a builtin function in HIP device
6530     // compilation, allow a pointer-type argument to default address space to be
6531     // passed as a pointer-type parameter to a non-default address space.
6532     // If Arg is declared in the default address space and Param is declared
6533     // in a non-default address space, perform an implicit address space cast to
6534     // the parameter type.
6535     if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6536         FD->getBuiltinID()) {
6537       for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6538         ParmVarDecl *Param = FD->getParamDecl(Idx);
6539         if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6540             !ArgExprs[Idx]->getType()->isPointerType())
6541           continue;
6542 
6543         auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6544         auto ArgTy = ArgExprs[Idx]->getType();
6545         auto ArgPtTy = ArgTy->getPointeeType();
6546         auto ArgAS = ArgPtTy.getAddressSpace();
6547 
6548         // Only allow implicit casting from a non-default address space pointee
6549         // type to a default address space pointee type
6550         if (ArgAS != LangAS::Default || ParamAS == LangAS::Default)
6551           continue;
6552 
6553         // First, ensure that the Arg is an RValue.
6554         if (ArgExprs[Idx]->isGLValue()) {
6555           ArgExprs[Idx] = ImplicitCastExpr::Create(
6556               Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6557               nullptr, VK_PRValue, FPOptionsOverride());
6558         }
6559 
6560         // Construct a new arg type with address space of Param
6561         Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6562         ArgPtQuals.setAddressSpace(ParamAS);
6563         auto NewArgPtTy =
6564             Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6565         auto NewArgTy =
6566             Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6567                                      ArgTy.getQualifiers());
6568 
6569         // Finally perform an implicit address space cast
6570         ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6571                                           CK_AddressSpaceConversion)
6572                             .get();
6573       }
6574     }
6575   }
6576 
6577   if (Context.isDependenceAllowed() &&
6578       (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6579     assert(!getLangOpts().CPlusPlus);
6580     assert((Fn->containsErrors() ||
6581             llvm::any_of(ArgExprs,
6582                          [](clang::Expr *E) { return E->containsErrors(); })) &&
6583            "should only occur in error-recovery path.");
6584     QualType ReturnType =
6585         llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6586             ? cast<FunctionDecl>(NDecl)->getCallResultType()
6587             : Context.DependentTy;
6588     return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6589                             Expr::getValueKindForType(ReturnType), RParenLoc,
6590                             CurFPFeatureOverrides());
6591   }
6592   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6593                                ExecConfig, IsExecConfig);
6594 }
6595 
6596 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6597 //  with the specified CallArgs
6598 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6599                                  MultiExprArg CallArgs) {
6600   StringRef Name = Context.BuiltinInfo.getName(Id);
6601   LookupResult R(*this, &Context.Idents.get(Name), Loc,
6602                  Sema::LookupOrdinaryName);
6603   LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6604 
6605   auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6606   assert(BuiltInDecl && "failed to find builtin declaration");
6607 
6608   ExprResult DeclRef =
6609       BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6610   assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6611 
6612   ExprResult Call =
6613       BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6614 
6615   assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6616   return Call.get();
6617 }
6618 
6619 /// Parse a __builtin_astype expression.
6620 ///
6621 /// __builtin_astype( value, dst type )
6622 ///
6623 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6624                                  SourceLocation BuiltinLoc,
6625                                  SourceLocation RParenLoc) {
6626   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6627   return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6628 }
6629 
6630 /// Create a new AsTypeExpr node (bitcast) from the arguments.
6631 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6632                                  SourceLocation BuiltinLoc,
6633                                  SourceLocation RParenLoc) {
6634   ExprValueKind VK = VK_PRValue;
6635   ExprObjectKind OK = OK_Ordinary;
6636   QualType SrcTy = E->getType();
6637   if (!SrcTy->isDependentType() &&
6638       Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6639     return ExprError(
6640         Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6641         << DestTy << SrcTy << E->getSourceRange());
6642   return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6643 }
6644 
6645 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6646 /// provided arguments.
6647 ///
6648 /// __builtin_convertvector( value, dst type )
6649 ///
6650 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6651                                         SourceLocation BuiltinLoc,
6652                                         SourceLocation RParenLoc) {
6653   TypeSourceInfo *TInfo;
6654   GetTypeFromParser(ParsedDestTy, &TInfo);
6655   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6656 }
6657 
6658 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6659 /// i.e. an expression not of \p OverloadTy.  The expression should
6660 /// unary-convert to an expression of function-pointer or
6661 /// block-pointer type.
6662 ///
6663 /// \param NDecl the declaration being called, if available
6664 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6665                                        SourceLocation LParenLoc,
6666                                        ArrayRef<Expr *> Args,
6667                                        SourceLocation RParenLoc, Expr *Config,
6668                                        bool IsExecConfig, ADLCallKind UsesADL) {
6669   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6670   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6671 
6672   // Functions with 'interrupt' attribute cannot be called directly.
6673   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6674     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6675     return ExprError();
6676   }
6677 
6678   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6679   // so there's some risk when calling out to non-interrupt handler functions
6680   // that the callee might not preserve them. This is easy to diagnose here,
6681   // but can be very challenging to debug.
6682   // Likewise, X86 interrupt handlers may only call routines with attribute
6683   // no_caller_saved_registers since there is no efficient way to
6684   // save and restore the non-GPR state.
6685   if (auto *Caller = getCurFunctionDecl()) {
6686     if (Caller->hasAttr<ARMInterruptAttr>()) {
6687       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6688       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6689         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6690         if (FDecl)
6691           Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6692       }
6693     }
6694     if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6695         ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6696       Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6697       if (FDecl)
6698         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6699     }
6700   }
6701 
6702   // Promote the function operand.
6703   // We special-case function promotion here because we only allow promoting
6704   // builtin functions to function pointers in the callee of a call.
6705   ExprResult Result;
6706   QualType ResultTy;
6707   if (BuiltinID &&
6708       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6709     // Extract the return type from the (builtin) function pointer type.
6710     // FIXME Several builtins still have setType in
6711     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6712     // Builtins.def to ensure they are correct before removing setType calls.
6713     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6714     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6715     ResultTy = FDecl->getCallResultType();
6716   } else {
6717     Result = CallExprUnaryConversions(Fn);
6718     ResultTy = Context.BoolTy;
6719   }
6720   if (Result.isInvalid())
6721     return ExprError();
6722   Fn = Result.get();
6723 
6724   // Check for a valid function type, but only if it is not a builtin which
6725   // requires custom type checking. These will be handled by
6726   // CheckBuiltinFunctionCall below just after creation of the call expression.
6727   const FunctionType *FuncT = nullptr;
6728   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6729   retry:
6730     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6731       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6732       // have type pointer to function".
6733       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6734       if (!FuncT)
6735         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6736                          << Fn->getType() << Fn->getSourceRange());
6737     } else if (const BlockPointerType *BPT =
6738                    Fn->getType()->getAs<BlockPointerType>()) {
6739       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6740     } else {
6741       // Handle calls to expressions of unknown-any type.
6742       if (Fn->getType() == Context.UnknownAnyTy) {
6743         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6744         if (rewrite.isInvalid())
6745           return ExprError();
6746         Fn = rewrite.get();
6747         goto retry;
6748       }
6749 
6750       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6751                        << Fn->getType() << Fn->getSourceRange());
6752     }
6753   }
6754 
6755   // Get the number of parameters in the function prototype, if any.
6756   // We will allocate space for max(Args.size(), NumParams) arguments
6757   // in the call expression.
6758   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6759   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6760 
6761   CallExpr *TheCall;
6762   if (Config) {
6763     assert(UsesADL == ADLCallKind::NotADL &&
6764            "CUDAKernelCallExpr should not use ADL");
6765     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6766                                          Args, ResultTy, VK_PRValue, RParenLoc,
6767                                          CurFPFeatureOverrides(), NumParams);
6768   } else {
6769     TheCall =
6770         CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6771                          CurFPFeatureOverrides(), NumParams, UsesADL);
6772   }
6773 
6774   if (!Context.isDependenceAllowed()) {
6775     // Forget about the nulled arguments since typo correction
6776     // do not handle them well.
6777     TheCall->shrinkNumArgs(Args.size());
6778     // C cannot always handle TypoExpr nodes in builtin calls and direct
6779     // function calls as their argument checking don't necessarily handle
6780     // dependent types properly, so make sure any TypoExprs have been
6781     // dealt with.
6782     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6783     if (!Result.isUsable()) return ExprError();
6784     CallExpr *TheOldCall = TheCall;
6785     TheCall = dyn_cast<CallExpr>(Result.get());
6786     bool CorrectedTypos = TheCall != TheOldCall;
6787     if (!TheCall) return Result;
6788     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6789 
6790     // A new call expression node was created if some typos were corrected.
6791     // However it may not have been constructed with enough storage. In this
6792     // case, rebuild the node with enough storage. The waste of space is
6793     // immaterial since this only happens when some typos were corrected.
6794     if (CorrectedTypos && Args.size() < NumParams) {
6795       if (Config)
6796         TheCall = CUDAKernelCallExpr::Create(
6797             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6798             RParenLoc, CurFPFeatureOverrides(), NumParams);
6799       else
6800         TheCall =
6801             CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6802                              CurFPFeatureOverrides(), NumParams, UsesADL);
6803     }
6804     // We can now handle the nulled arguments for the default arguments.
6805     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6806   }
6807 
6808   // Bail out early if calling a builtin with custom type checking.
6809   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6810     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6811 
6812   if (getLangOpts().CUDA) {
6813     if (Config) {
6814       // CUDA: Kernel calls must be to global functions
6815       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6816         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6817             << FDecl << Fn->getSourceRange());
6818 
6819       // CUDA: Kernel function must have 'void' return type
6820       if (!FuncT->getReturnType()->isVoidType() &&
6821           !FuncT->getReturnType()->getAs<AutoType>() &&
6822           !FuncT->getReturnType()->isInstantiationDependentType())
6823         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6824             << Fn->getType() << Fn->getSourceRange());
6825     } else {
6826       // CUDA: Calls to global functions must be configured
6827       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6828         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6829             << FDecl << Fn->getSourceRange());
6830     }
6831   }
6832 
6833   // Check for a valid return type
6834   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6835                           FDecl))
6836     return ExprError();
6837 
6838   // We know the result type of the call, set it.
6839   TheCall->setType(FuncT->getCallResultType(Context));
6840   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6841 
6842   if (Proto) {
6843     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6844                                 IsExecConfig))
6845       return ExprError();
6846   } else {
6847     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6848 
6849     if (FDecl) {
6850       // Check if we have too few/too many template arguments, based
6851       // on our knowledge of the function definition.
6852       const FunctionDecl *Def = nullptr;
6853       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6854         Proto = Def->getType()->getAs<FunctionProtoType>();
6855        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6856           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6857           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6858       }
6859 
6860       // If the function we're calling isn't a function prototype, but we have
6861       // a function prototype from a prior declaratiom, use that prototype.
6862       if (!FDecl->hasPrototype())
6863         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6864     }
6865 
6866     // Promote the arguments (C99 6.5.2.2p6).
6867     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6868       Expr *Arg = Args[i];
6869 
6870       if (Proto && i < Proto->getNumParams()) {
6871         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6872             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6873         ExprResult ArgE =
6874             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6875         if (ArgE.isInvalid())
6876           return true;
6877 
6878         Arg = ArgE.getAs<Expr>();
6879 
6880       } else {
6881         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6882 
6883         if (ArgE.isInvalid())
6884           return true;
6885 
6886         Arg = ArgE.getAs<Expr>();
6887       }
6888 
6889       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6890                               diag::err_call_incomplete_argument, Arg))
6891         return ExprError();
6892 
6893       TheCall->setArg(i, Arg);
6894     }
6895     TheCall->computeDependence();
6896   }
6897 
6898   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6899     if (!Method->isStatic())
6900       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6901         << Fn->getSourceRange());
6902 
6903   // Check for sentinels
6904   if (NDecl)
6905     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6906 
6907   // Warn for unions passing across security boundary (CMSE).
6908   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6909     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6910       if (const auto *RT =
6911               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6912         if (RT->getDecl()->isOrContainsUnion())
6913           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6914               << 0 << i;
6915       }
6916     }
6917   }
6918 
6919   // Do special checking on direct calls to functions.
6920   if (FDecl) {
6921     if (CheckFunctionCall(FDecl, TheCall, Proto))
6922       return ExprError();
6923 
6924     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6925 
6926     if (BuiltinID)
6927       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6928   } else if (NDecl) {
6929     if (CheckPointerCall(NDecl, TheCall, Proto))
6930       return ExprError();
6931   } else {
6932     if (CheckOtherCall(TheCall, Proto))
6933       return ExprError();
6934   }
6935 
6936   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6937 }
6938 
6939 ExprResult
6940 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6941                            SourceLocation RParenLoc, Expr *InitExpr) {
6942   assert(Ty && "ActOnCompoundLiteral(): missing type");
6943   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6944 
6945   TypeSourceInfo *TInfo;
6946   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6947   if (!TInfo)
6948     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6949 
6950   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6951 }
6952 
6953 ExprResult
6954 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6955                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6956   QualType literalType = TInfo->getType();
6957 
6958   if (literalType->isArrayType()) {
6959     if (RequireCompleteSizedType(
6960             LParenLoc, Context.getBaseElementType(literalType),
6961             diag::err_array_incomplete_or_sizeless_type,
6962             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6963       return ExprError();
6964     if (literalType->isVariableArrayType()) {
6965       if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
6966                                            diag::err_variable_object_no_init)) {
6967         return ExprError();
6968       }
6969     }
6970   } else if (!literalType->isDependentType() &&
6971              RequireCompleteType(LParenLoc, literalType,
6972                diag::err_typecheck_decl_incomplete_type,
6973                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6974     return ExprError();
6975 
6976   InitializedEntity Entity
6977     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6978   InitializationKind Kind
6979     = InitializationKind::CreateCStyleCast(LParenLoc,
6980                                            SourceRange(LParenLoc, RParenLoc),
6981                                            /*InitList=*/true);
6982   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6983   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6984                                       &literalType);
6985   if (Result.isInvalid())
6986     return ExprError();
6987   LiteralExpr = Result.get();
6988 
6989   bool isFileScope = !CurContext->isFunctionOrMethod();
6990 
6991   // In C, compound literals are l-values for some reason.
6992   // For GCC compatibility, in C++, file-scope array compound literals with
6993   // constant initializers are also l-values, and compound literals are
6994   // otherwise prvalues.
6995   //
6996   // (GCC also treats C++ list-initialized file-scope array prvalues with
6997   // constant initializers as l-values, but that's non-conforming, so we don't
6998   // follow it there.)
6999   //
7000   // FIXME: It would be better to handle the lvalue cases as materializing and
7001   // lifetime-extending a temporary object, but our materialized temporaries
7002   // representation only supports lifetime extension from a variable, not "out
7003   // of thin air".
7004   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7005   // is bound to the result of applying array-to-pointer decay to the compound
7006   // literal.
7007   // FIXME: GCC supports compound literals of reference type, which should
7008   // obviously have a value kind derived from the kind of reference involved.
7009   ExprValueKind VK =
7010       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7011           ? VK_PRValue
7012           : VK_LValue;
7013 
7014   if (isFileScope)
7015     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7016       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7017         Expr *Init = ILE->getInit(i);
7018         ILE->setInit(i, ConstantExpr::Create(Context, Init));
7019       }
7020 
7021   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7022                                               VK, LiteralExpr, isFileScope);
7023   if (isFileScope) {
7024     if (!LiteralExpr->isTypeDependent() &&
7025         !LiteralExpr->isValueDependent() &&
7026         !literalType->isDependentType()) // C99 6.5.2.5p3
7027       if (CheckForConstantInitializer(LiteralExpr, literalType))
7028         return ExprError();
7029   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7030              literalType.getAddressSpace() != LangAS::Default) {
7031     // Embedded-C extensions to C99 6.5.2.5:
7032     //   "If the compound literal occurs inside the body of a function, the
7033     //   type name shall not be qualified by an address-space qualifier."
7034     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7035       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7036     return ExprError();
7037   }
7038 
7039   if (!isFileScope && !getLangOpts().CPlusPlus) {
7040     // Compound literals that have automatic storage duration are destroyed at
7041     // the end of the scope in C; in C++, they're just temporaries.
7042 
7043     // Emit diagnostics if it is or contains a C union type that is non-trivial
7044     // to destruct.
7045     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7046       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7047                             NTCUC_CompoundLiteral, NTCUK_Destruct);
7048 
7049     // Diagnose jumps that enter or exit the lifetime of the compound literal.
7050     if (literalType.isDestructedType()) {
7051       Cleanup.setExprNeedsCleanups(true);
7052       ExprCleanupObjects.push_back(E);
7053       getCurFunction()->setHasBranchProtectedScope();
7054     }
7055   }
7056 
7057   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7058       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7059     checkNonTrivialCUnionInInitializer(E->getInitializer(),
7060                                        E->getInitializer()->getExprLoc());
7061 
7062   return MaybeBindToTemporary(E);
7063 }
7064 
7065 ExprResult
7066 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7067                     SourceLocation RBraceLoc) {
7068   // Only produce each kind of designated initialization diagnostic once.
7069   SourceLocation FirstDesignator;
7070   bool DiagnosedArrayDesignator = false;
7071   bool DiagnosedNestedDesignator = false;
7072   bool DiagnosedMixedDesignator = false;
7073 
7074   // Check that any designated initializers are syntactically valid in the
7075   // current language mode.
7076   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7077     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7078       if (FirstDesignator.isInvalid())
7079         FirstDesignator = DIE->getBeginLoc();
7080 
7081       if (!getLangOpts().CPlusPlus)
7082         break;
7083 
7084       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7085         DiagnosedNestedDesignator = true;
7086         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7087           << DIE->getDesignatorsSourceRange();
7088       }
7089 
7090       for (auto &Desig : DIE->designators()) {
7091         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7092           DiagnosedArrayDesignator = true;
7093           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7094             << Desig.getSourceRange();
7095         }
7096       }
7097 
7098       if (!DiagnosedMixedDesignator &&
7099           !isa<DesignatedInitExpr>(InitArgList[0])) {
7100         DiagnosedMixedDesignator = true;
7101         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7102           << DIE->getSourceRange();
7103         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7104           << InitArgList[0]->getSourceRange();
7105       }
7106     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7107                isa<DesignatedInitExpr>(InitArgList[0])) {
7108       DiagnosedMixedDesignator = true;
7109       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7110       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7111         << DIE->getSourceRange();
7112       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7113         << InitArgList[I]->getSourceRange();
7114     }
7115   }
7116 
7117   if (FirstDesignator.isValid()) {
7118     // Only diagnose designated initiaization as a C++20 extension if we didn't
7119     // already diagnose use of (non-C++20) C99 designator syntax.
7120     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7121         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7122       Diag(FirstDesignator, getLangOpts().CPlusPlus20
7123                                 ? diag::warn_cxx17_compat_designated_init
7124                                 : diag::ext_cxx_designated_init);
7125     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7126       Diag(FirstDesignator, diag::ext_designated_init);
7127     }
7128   }
7129 
7130   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7131 }
7132 
7133 ExprResult
7134 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7135                     SourceLocation RBraceLoc) {
7136   // Semantic analysis for initializers is done by ActOnDeclarator() and
7137   // CheckInitializer() - it requires knowledge of the object being initialized.
7138 
7139   // Immediately handle non-overload placeholders.  Overloads can be
7140   // resolved contextually, but everything else here can't.
7141   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7142     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7143       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7144 
7145       // Ignore failures; dropping the entire initializer list because
7146       // of one failure would be terrible for indexing/etc.
7147       if (result.isInvalid()) continue;
7148 
7149       InitArgList[I] = result.get();
7150     }
7151   }
7152 
7153   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7154                                                RBraceLoc);
7155   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7156   return E;
7157 }
7158 
7159 /// Do an explicit extend of the given block pointer if we're in ARC.
7160 void Sema::maybeExtendBlockObject(ExprResult &E) {
7161   assert(E.get()->getType()->isBlockPointerType());
7162   assert(E.get()->isPRValue());
7163 
7164   // Only do this in an r-value context.
7165   if (!getLangOpts().ObjCAutoRefCount) return;
7166 
7167   E = ImplicitCastExpr::Create(
7168       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7169       /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7170   Cleanup.setExprNeedsCleanups(true);
7171 }
7172 
7173 /// Prepare a conversion of the given expression to an ObjC object
7174 /// pointer type.
7175 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7176   QualType type = E.get()->getType();
7177   if (type->isObjCObjectPointerType()) {
7178     return CK_BitCast;
7179   } else if (type->isBlockPointerType()) {
7180     maybeExtendBlockObject(E);
7181     return CK_BlockPointerToObjCPointerCast;
7182   } else {
7183     assert(type->isPointerType());
7184     return CK_CPointerToObjCPointerCast;
7185   }
7186 }
7187 
7188 /// Prepares for a scalar cast, performing all the necessary stages
7189 /// except the final cast and returning the kind required.
7190 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7191   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7192   // Also, callers should have filtered out the invalid cases with
7193   // pointers.  Everything else should be possible.
7194 
7195   QualType SrcTy = Src.get()->getType();
7196   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7197     return CK_NoOp;
7198 
7199   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7200   case Type::STK_MemberPointer:
7201     llvm_unreachable("member pointer type in C");
7202 
7203   case Type::STK_CPointer:
7204   case Type::STK_BlockPointer:
7205   case Type::STK_ObjCObjectPointer:
7206     switch (DestTy->getScalarTypeKind()) {
7207     case Type::STK_CPointer: {
7208       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7209       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7210       if (SrcAS != DestAS)
7211         return CK_AddressSpaceConversion;
7212       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7213         return CK_NoOp;
7214       return CK_BitCast;
7215     }
7216     case Type::STK_BlockPointer:
7217       return (SrcKind == Type::STK_BlockPointer
7218                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7219     case Type::STK_ObjCObjectPointer:
7220       if (SrcKind == Type::STK_ObjCObjectPointer)
7221         return CK_BitCast;
7222       if (SrcKind == Type::STK_CPointer)
7223         return CK_CPointerToObjCPointerCast;
7224       maybeExtendBlockObject(Src);
7225       return CK_BlockPointerToObjCPointerCast;
7226     case Type::STK_Bool:
7227       return CK_PointerToBoolean;
7228     case Type::STK_Integral:
7229       return CK_PointerToIntegral;
7230     case Type::STK_Floating:
7231     case Type::STK_FloatingComplex:
7232     case Type::STK_IntegralComplex:
7233     case Type::STK_MemberPointer:
7234     case Type::STK_FixedPoint:
7235       llvm_unreachable("illegal cast from pointer");
7236     }
7237     llvm_unreachable("Should have returned before this");
7238 
7239   case Type::STK_FixedPoint:
7240     switch (DestTy->getScalarTypeKind()) {
7241     case Type::STK_FixedPoint:
7242       return CK_FixedPointCast;
7243     case Type::STK_Bool:
7244       return CK_FixedPointToBoolean;
7245     case Type::STK_Integral:
7246       return CK_FixedPointToIntegral;
7247     case Type::STK_Floating:
7248       return CK_FixedPointToFloating;
7249     case Type::STK_IntegralComplex:
7250     case Type::STK_FloatingComplex:
7251       Diag(Src.get()->getExprLoc(),
7252            diag::err_unimplemented_conversion_with_fixed_point_type)
7253           << DestTy;
7254       return CK_IntegralCast;
7255     case Type::STK_CPointer:
7256     case Type::STK_ObjCObjectPointer:
7257     case Type::STK_BlockPointer:
7258     case Type::STK_MemberPointer:
7259       llvm_unreachable("illegal cast to pointer type");
7260     }
7261     llvm_unreachable("Should have returned before this");
7262 
7263   case Type::STK_Bool: // casting from bool is like casting from an integer
7264   case Type::STK_Integral:
7265     switch (DestTy->getScalarTypeKind()) {
7266     case Type::STK_CPointer:
7267     case Type::STK_ObjCObjectPointer:
7268     case Type::STK_BlockPointer:
7269       if (Src.get()->isNullPointerConstant(Context,
7270                                            Expr::NPC_ValueDependentIsNull))
7271         return CK_NullToPointer;
7272       return CK_IntegralToPointer;
7273     case Type::STK_Bool:
7274       return CK_IntegralToBoolean;
7275     case Type::STK_Integral:
7276       return CK_IntegralCast;
7277     case Type::STK_Floating:
7278       return CK_IntegralToFloating;
7279     case Type::STK_IntegralComplex:
7280       Src = ImpCastExprToType(Src.get(),
7281                       DestTy->castAs<ComplexType>()->getElementType(),
7282                       CK_IntegralCast);
7283       return CK_IntegralRealToComplex;
7284     case Type::STK_FloatingComplex:
7285       Src = ImpCastExprToType(Src.get(),
7286                       DestTy->castAs<ComplexType>()->getElementType(),
7287                       CK_IntegralToFloating);
7288       return CK_FloatingRealToComplex;
7289     case Type::STK_MemberPointer:
7290       llvm_unreachable("member pointer type in C");
7291     case Type::STK_FixedPoint:
7292       return CK_IntegralToFixedPoint;
7293     }
7294     llvm_unreachable("Should have returned before this");
7295 
7296   case Type::STK_Floating:
7297     switch (DestTy->getScalarTypeKind()) {
7298     case Type::STK_Floating:
7299       return CK_FloatingCast;
7300     case Type::STK_Bool:
7301       return CK_FloatingToBoolean;
7302     case Type::STK_Integral:
7303       return CK_FloatingToIntegral;
7304     case Type::STK_FloatingComplex:
7305       Src = ImpCastExprToType(Src.get(),
7306                               DestTy->castAs<ComplexType>()->getElementType(),
7307                               CK_FloatingCast);
7308       return CK_FloatingRealToComplex;
7309     case Type::STK_IntegralComplex:
7310       Src = ImpCastExprToType(Src.get(),
7311                               DestTy->castAs<ComplexType>()->getElementType(),
7312                               CK_FloatingToIntegral);
7313       return CK_IntegralRealToComplex;
7314     case Type::STK_CPointer:
7315     case Type::STK_ObjCObjectPointer:
7316     case Type::STK_BlockPointer:
7317       llvm_unreachable("valid float->pointer cast?");
7318     case Type::STK_MemberPointer:
7319       llvm_unreachable("member pointer type in C");
7320     case Type::STK_FixedPoint:
7321       return CK_FloatingToFixedPoint;
7322     }
7323     llvm_unreachable("Should have returned before this");
7324 
7325   case Type::STK_FloatingComplex:
7326     switch (DestTy->getScalarTypeKind()) {
7327     case Type::STK_FloatingComplex:
7328       return CK_FloatingComplexCast;
7329     case Type::STK_IntegralComplex:
7330       return CK_FloatingComplexToIntegralComplex;
7331     case Type::STK_Floating: {
7332       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7333       if (Context.hasSameType(ET, DestTy))
7334         return CK_FloatingComplexToReal;
7335       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7336       return CK_FloatingCast;
7337     }
7338     case Type::STK_Bool:
7339       return CK_FloatingComplexToBoolean;
7340     case Type::STK_Integral:
7341       Src = ImpCastExprToType(Src.get(),
7342                               SrcTy->castAs<ComplexType>()->getElementType(),
7343                               CK_FloatingComplexToReal);
7344       return CK_FloatingToIntegral;
7345     case Type::STK_CPointer:
7346     case Type::STK_ObjCObjectPointer:
7347     case Type::STK_BlockPointer:
7348       llvm_unreachable("valid complex float->pointer cast?");
7349     case Type::STK_MemberPointer:
7350       llvm_unreachable("member pointer type in C");
7351     case Type::STK_FixedPoint:
7352       Diag(Src.get()->getExprLoc(),
7353            diag::err_unimplemented_conversion_with_fixed_point_type)
7354           << SrcTy;
7355       return CK_IntegralCast;
7356     }
7357     llvm_unreachable("Should have returned before this");
7358 
7359   case Type::STK_IntegralComplex:
7360     switch (DestTy->getScalarTypeKind()) {
7361     case Type::STK_FloatingComplex:
7362       return CK_IntegralComplexToFloatingComplex;
7363     case Type::STK_IntegralComplex:
7364       return CK_IntegralComplexCast;
7365     case Type::STK_Integral: {
7366       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7367       if (Context.hasSameType(ET, DestTy))
7368         return CK_IntegralComplexToReal;
7369       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7370       return CK_IntegralCast;
7371     }
7372     case Type::STK_Bool:
7373       return CK_IntegralComplexToBoolean;
7374     case Type::STK_Floating:
7375       Src = ImpCastExprToType(Src.get(),
7376                               SrcTy->castAs<ComplexType>()->getElementType(),
7377                               CK_IntegralComplexToReal);
7378       return CK_IntegralToFloating;
7379     case Type::STK_CPointer:
7380     case Type::STK_ObjCObjectPointer:
7381     case Type::STK_BlockPointer:
7382       llvm_unreachable("valid complex int->pointer cast?");
7383     case Type::STK_MemberPointer:
7384       llvm_unreachable("member pointer type in C");
7385     case Type::STK_FixedPoint:
7386       Diag(Src.get()->getExprLoc(),
7387            diag::err_unimplemented_conversion_with_fixed_point_type)
7388           << SrcTy;
7389       return CK_IntegralCast;
7390     }
7391     llvm_unreachable("Should have returned before this");
7392   }
7393 
7394   llvm_unreachable("Unhandled scalar cast");
7395 }
7396 
7397 static bool breakDownVectorType(QualType type, uint64_t &len,
7398                                 QualType &eltType) {
7399   // Vectors are simple.
7400   if (const VectorType *vecType = type->getAs<VectorType>()) {
7401     len = vecType->getNumElements();
7402     eltType = vecType->getElementType();
7403     assert(eltType->isScalarType());
7404     return true;
7405   }
7406 
7407   // We allow lax conversion to and from non-vector types, but only if
7408   // they're real types (i.e. non-complex, non-pointer scalar types).
7409   if (!type->isRealType()) return false;
7410 
7411   len = 1;
7412   eltType = type;
7413   return true;
7414 }
7415 
7416 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7417 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7418 /// allowed?
7419 ///
7420 /// This will also return false if the two given types do not make sense from
7421 /// the perspective of SVE bitcasts.
7422 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7423   assert(srcTy->isVectorType() || destTy->isVectorType());
7424 
7425   auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7426     if (!FirstType->isSizelessBuiltinType())
7427       return false;
7428 
7429     const auto *VecTy = SecondType->getAs<VectorType>();
7430     return VecTy &&
7431            VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7432   };
7433 
7434   return ValidScalableConversion(srcTy, destTy) ||
7435          ValidScalableConversion(destTy, srcTy);
7436 }
7437 
7438 /// Are the two types matrix types and do they have the same dimensions i.e.
7439 /// do they have the same number of rows and the same number of columns?
7440 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7441   if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7442     return false;
7443 
7444   const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7445   const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7446 
7447   return matSrcType->getNumRows() == matDestType->getNumRows() &&
7448          matSrcType->getNumColumns() == matDestType->getNumColumns();
7449 }
7450 
7451 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7452   assert(DestTy->isVectorType() || SrcTy->isVectorType());
7453 
7454   uint64_t SrcLen, DestLen;
7455   QualType SrcEltTy, DestEltTy;
7456   if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7457     return false;
7458   if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7459     return false;
7460 
7461   // ASTContext::getTypeSize will return the size rounded up to a
7462   // power of 2, so instead of using that, we need to use the raw
7463   // element size multiplied by the element count.
7464   uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7465   uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7466 
7467   return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7468 }
7469 
7470 /// Are the two types lax-compatible vector types?  That is, given
7471 /// that one of them is a vector, do they have equal storage sizes,
7472 /// where the storage size is the number of elements times the element
7473 /// size?
7474 ///
7475 /// This will also return false if either of the types is neither a
7476 /// vector nor a real type.
7477 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7478   assert(destTy->isVectorType() || srcTy->isVectorType());
7479 
7480   // Disallow lax conversions between scalars and ExtVectors (these
7481   // conversions are allowed for other vector types because common headers
7482   // depend on them).  Most scalar OP ExtVector cases are handled by the
7483   // splat path anyway, which does what we want (convert, not bitcast).
7484   // What this rules out for ExtVectors is crazy things like char4*float.
7485   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7486   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7487 
7488   return areVectorTypesSameSize(srcTy, destTy);
7489 }
7490 
7491 /// Is this a legal conversion between two types, one of which is
7492 /// known to be a vector type?
7493 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7494   assert(destTy->isVectorType() || srcTy->isVectorType());
7495 
7496   switch (Context.getLangOpts().getLaxVectorConversions()) {
7497   case LangOptions::LaxVectorConversionKind::None:
7498     return false;
7499 
7500   case LangOptions::LaxVectorConversionKind::Integer:
7501     if (!srcTy->isIntegralOrEnumerationType()) {
7502       auto *Vec = srcTy->getAs<VectorType>();
7503       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7504         return false;
7505     }
7506     if (!destTy->isIntegralOrEnumerationType()) {
7507       auto *Vec = destTy->getAs<VectorType>();
7508       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7509         return false;
7510     }
7511     // OK, integer (vector) -> integer (vector) bitcast.
7512     break;
7513 
7514     case LangOptions::LaxVectorConversionKind::All:
7515     break;
7516   }
7517 
7518   return areLaxCompatibleVectorTypes(srcTy, destTy);
7519 }
7520 
7521 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7522                            CastKind &Kind) {
7523   if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7524     if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7525       return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7526              << DestTy << SrcTy << R;
7527     }
7528   } else if (SrcTy->isMatrixType()) {
7529     return Diag(R.getBegin(),
7530                 diag::err_invalid_conversion_between_matrix_and_type)
7531            << SrcTy << DestTy << R;
7532   } else if (DestTy->isMatrixType()) {
7533     return Diag(R.getBegin(),
7534                 diag::err_invalid_conversion_between_matrix_and_type)
7535            << DestTy << SrcTy << R;
7536   }
7537 
7538   Kind = CK_MatrixCast;
7539   return false;
7540 }
7541 
7542 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7543                            CastKind &Kind) {
7544   assert(VectorTy->isVectorType() && "Not a vector type!");
7545 
7546   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7547     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7548       return Diag(R.getBegin(),
7549                   Ty->isVectorType() ?
7550                   diag::err_invalid_conversion_between_vectors :
7551                   diag::err_invalid_conversion_between_vector_and_integer)
7552         << VectorTy << Ty << R;
7553   } else
7554     return Diag(R.getBegin(),
7555                 diag::err_invalid_conversion_between_vector_and_scalar)
7556       << VectorTy << Ty << R;
7557 
7558   Kind = CK_BitCast;
7559   return false;
7560 }
7561 
7562 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7563   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7564 
7565   if (DestElemTy == SplattedExpr->getType())
7566     return SplattedExpr;
7567 
7568   assert(DestElemTy->isFloatingType() ||
7569          DestElemTy->isIntegralOrEnumerationType());
7570 
7571   CastKind CK;
7572   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7573     // OpenCL requires that we convert `true` boolean expressions to -1, but
7574     // only when splatting vectors.
7575     if (DestElemTy->isFloatingType()) {
7576       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7577       // in two steps: boolean to signed integral, then to floating.
7578       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7579                                                  CK_BooleanToSignedIntegral);
7580       SplattedExpr = CastExprRes.get();
7581       CK = CK_IntegralToFloating;
7582     } else {
7583       CK = CK_BooleanToSignedIntegral;
7584     }
7585   } else {
7586     ExprResult CastExprRes = SplattedExpr;
7587     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7588     if (CastExprRes.isInvalid())
7589       return ExprError();
7590     SplattedExpr = CastExprRes.get();
7591   }
7592   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7593 }
7594 
7595 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7596                                     Expr *CastExpr, CastKind &Kind) {
7597   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7598 
7599   QualType SrcTy = CastExpr->getType();
7600 
7601   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7602   // an ExtVectorType.
7603   // In OpenCL, casts between vectors of different types are not allowed.
7604   // (See OpenCL 6.2).
7605   if (SrcTy->isVectorType()) {
7606     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7607         (getLangOpts().OpenCL &&
7608          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7609       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7610         << DestTy << SrcTy << R;
7611       return ExprError();
7612     }
7613     Kind = CK_BitCast;
7614     return CastExpr;
7615   }
7616 
7617   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7618   // conversion will take place first from scalar to elt type, and then
7619   // splat from elt type to vector.
7620   if (SrcTy->isPointerType())
7621     return Diag(R.getBegin(),
7622                 diag::err_invalid_conversion_between_vector_and_scalar)
7623       << DestTy << SrcTy << R;
7624 
7625   Kind = CK_VectorSplat;
7626   return prepareVectorSplat(DestTy, CastExpr);
7627 }
7628 
7629 ExprResult
7630 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7631                     Declarator &D, ParsedType &Ty,
7632                     SourceLocation RParenLoc, Expr *CastExpr) {
7633   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7634          "ActOnCastExpr(): missing type or expr");
7635 
7636   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7637   if (D.isInvalidType())
7638     return ExprError();
7639 
7640   if (getLangOpts().CPlusPlus) {
7641     // Check that there are no default arguments (C++ only).
7642     CheckExtraCXXDefaultArguments(D);
7643   } else {
7644     // Make sure any TypoExprs have been dealt with.
7645     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7646     if (!Res.isUsable())
7647       return ExprError();
7648     CastExpr = Res.get();
7649   }
7650 
7651   checkUnusedDeclAttributes(D);
7652 
7653   QualType castType = castTInfo->getType();
7654   Ty = CreateParsedType(castType, castTInfo);
7655 
7656   bool isVectorLiteral = false;
7657 
7658   // Check for an altivec or OpenCL literal,
7659   // i.e. all the elements are integer constants.
7660   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7661   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7662   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7663        && castType->isVectorType() && (PE || PLE)) {
7664     if (PLE && PLE->getNumExprs() == 0) {
7665       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7666       return ExprError();
7667     }
7668     if (PE || PLE->getNumExprs() == 1) {
7669       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7670       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7671         isVectorLiteral = true;
7672     }
7673     else
7674       isVectorLiteral = true;
7675   }
7676 
7677   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7678   // then handle it as such.
7679   if (isVectorLiteral)
7680     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7681 
7682   // If the Expr being casted is a ParenListExpr, handle it specially.
7683   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7684   // sequence of BinOp comma operators.
7685   if (isa<ParenListExpr>(CastExpr)) {
7686     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7687     if (Result.isInvalid()) return ExprError();
7688     CastExpr = Result.get();
7689   }
7690 
7691   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7692       !getSourceManager().isInSystemMacro(LParenLoc))
7693     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7694 
7695   CheckTollFreeBridgeCast(castType, CastExpr);
7696 
7697   CheckObjCBridgeRelatedCast(castType, CastExpr);
7698 
7699   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7700 
7701   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7702 }
7703 
7704 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7705                                     SourceLocation RParenLoc, Expr *E,
7706                                     TypeSourceInfo *TInfo) {
7707   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7708          "Expected paren or paren list expression");
7709 
7710   Expr **exprs;
7711   unsigned numExprs;
7712   Expr *subExpr;
7713   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7714   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7715     LiteralLParenLoc = PE->getLParenLoc();
7716     LiteralRParenLoc = PE->getRParenLoc();
7717     exprs = PE->getExprs();
7718     numExprs = PE->getNumExprs();
7719   } else { // isa<ParenExpr> by assertion at function entrance
7720     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7721     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7722     subExpr = cast<ParenExpr>(E)->getSubExpr();
7723     exprs = &subExpr;
7724     numExprs = 1;
7725   }
7726 
7727   QualType Ty = TInfo->getType();
7728   assert(Ty->isVectorType() && "Expected vector type");
7729 
7730   SmallVector<Expr *, 8> initExprs;
7731   const VectorType *VTy = Ty->castAs<VectorType>();
7732   unsigned numElems = VTy->getNumElements();
7733 
7734   // '(...)' form of vector initialization in AltiVec: the number of
7735   // initializers must be one or must match the size of the vector.
7736   // If a single value is specified in the initializer then it will be
7737   // replicated to all the components of the vector
7738   if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
7739                                  VTy->getElementType()))
7740     return ExprError();
7741   if (ShouldSplatAltivecScalarInCast(VTy)) {
7742     // The number of initializers must be one or must match the size of the
7743     // vector. If a single value is specified in the initializer then it will
7744     // be replicated to all the components of the vector
7745     if (numExprs == 1) {
7746       QualType ElemTy = VTy->getElementType();
7747       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7748       if (Literal.isInvalid())
7749         return ExprError();
7750       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7751                                   PrepareScalarCast(Literal, ElemTy));
7752       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7753     }
7754     else if (numExprs < numElems) {
7755       Diag(E->getExprLoc(),
7756            diag::err_incorrect_number_of_vector_initializers);
7757       return ExprError();
7758     }
7759     else
7760       initExprs.append(exprs, exprs + numExprs);
7761   }
7762   else {
7763     // For OpenCL, when the number of initializers is a single value,
7764     // it will be replicated to all components of the vector.
7765     if (getLangOpts().OpenCL &&
7766         VTy->getVectorKind() == VectorType::GenericVector &&
7767         numExprs == 1) {
7768         QualType ElemTy = VTy->getElementType();
7769         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7770         if (Literal.isInvalid())
7771           return ExprError();
7772         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7773                                     PrepareScalarCast(Literal, ElemTy));
7774         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7775     }
7776 
7777     initExprs.append(exprs, exprs + numExprs);
7778   }
7779   // FIXME: This means that pretty-printing the final AST will produce curly
7780   // braces instead of the original commas.
7781   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7782                                                    initExprs, LiteralRParenLoc);
7783   initE->setType(Ty);
7784   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7785 }
7786 
7787 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7788 /// the ParenListExpr into a sequence of comma binary operators.
7789 ExprResult
7790 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7791   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7792   if (!E)
7793     return OrigExpr;
7794 
7795   ExprResult Result(E->getExpr(0));
7796 
7797   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7798     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7799                         E->getExpr(i));
7800 
7801   if (Result.isInvalid()) return ExprError();
7802 
7803   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7804 }
7805 
7806 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7807                                     SourceLocation R,
7808                                     MultiExprArg Val) {
7809   return ParenListExpr::Create(Context, L, Val, R);
7810 }
7811 
7812 /// Emit a specialized diagnostic when one expression is a null pointer
7813 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7814 /// emitted.
7815 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7816                                       SourceLocation QuestionLoc) {
7817   Expr *NullExpr = LHSExpr;
7818   Expr *NonPointerExpr = RHSExpr;
7819   Expr::NullPointerConstantKind NullKind =
7820       NullExpr->isNullPointerConstant(Context,
7821                                       Expr::NPC_ValueDependentIsNotNull);
7822 
7823   if (NullKind == Expr::NPCK_NotNull) {
7824     NullExpr = RHSExpr;
7825     NonPointerExpr = LHSExpr;
7826     NullKind =
7827         NullExpr->isNullPointerConstant(Context,
7828                                         Expr::NPC_ValueDependentIsNotNull);
7829   }
7830 
7831   if (NullKind == Expr::NPCK_NotNull)
7832     return false;
7833 
7834   if (NullKind == Expr::NPCK_ZeroExpression)
7835     return false;
7836 
7837   if (NullKind == Expr::NPCK_ZeroLiteral) {
7838     // In this case, check to make sure that we got here from a "NULL"
7839     // string in the source code.
7840     NullExpr = NullExpr->IgnoreParenImpCasts();
7841     SourceLocation loc = NullExpr->getExprLoc();
7842     if (!findMacroSpelling(loc, "NULL"))
7843       return false;
7844   }
7845 
7846   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7847   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7848       << NonPointerExpr->getType() << DiagType
7849       << NonPointerExpr->getSourceRange();
7850   return true;
7851 }
7852 
7853 /// Return false if the condition expression is valid, true otherwise.
7854 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7855   QualType CondTy = Cond->getType();
7856 
7857   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7858   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7859     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7860       << CondTy << Cond->getSourceRange();
7861     return true;
7862   }
7863 
7864   // C99 6.5.15p2
7865   if (CondTy->isScalarType()) return false;
7866 
7867   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7868     << CondTy << Cond->getSourceRange();
7869   return true;
7870 }
7871 
7872 /// Handle when one or both operands are void type.
7873 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7874                                          ExprResult &RHS) {
7875     Expr *LHSExpr = LHS.get();
7876     Expr *RHSExpr = RHS.get();
7877 
7878     if (!LHSExpr->getType()->isVoidType())
7879       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7880           << RHSExpr->getSourceRange();
7881     if (!RHSExpr->getType()->isVoidType())
7882       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7883           << LHSExpr->getSourceRange();
7884     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7885     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7886     return S.Context.VoidTy;
7887 }
7888 
7889 /// Return false if the NullExpr can be promoted to PointerTy,
7890 /// true otherwise.
7891 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7892                                         QualType PointerTy) {
7893   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7894       !NullExpr.get()->isNullPointerConstant(S.Context,
7895                                             Expr::NPC_ValueDependentIsNull))
7896     return true;
7897 
7898   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7899   return false;
7900 }
7901 
7902 /// Checks compatibility between two pointers and return the resulting
7903 /// type.
7904 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7905                                                      ExprResult &RHS,
7906                                                      SourceLocation Loc) {
7907   QualType LHSTy = LHS.get()->getType();
7908   QualType RHSTy = RHS.get()->getType();
7909 
7910   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7911     // Two identical pointers types are always compatible.
7912     return LHSTy;
7913   }
7914 
7915   QualType lhptee, rhptee;
7916 
7917   // Get the pointee types.
7918   bool IsBlockPointer = false;
7919   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7920     lhptee = LHSBTy->getPointeeType();
7921     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7922     IsBlockPointer = true;
7923   } else {
7924     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7925     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7926   }
7927 
7928   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7929   // differently qualified versions of compatible types, the result type is
7930   // a pointer to an appropriately qualified version of the composite
7931   // type.
7932 
7933   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7934   // clause doesn't make sense for our extensions. E.g. address space 2 should
7935   // be incompatible with address space 3: they may live on different devices or
7936   // anything.
7937   Qualifiers lhQual = lhptee.getQualifiers();
7938   Qualifiers rhQual = rhptee.getQualifiers();
7939 
7940   LangAS ResultAddrSpace = LangAS::Default;
7941   LangAS LAddrSpace = lhQual.getAddressSpace();
7942   LangAS RAddrSpace = rhQual.getAddressSpace();
7943 
7944   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7945   // spaces is disallowed.
7946   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7947     ResultAddrSpace = LAddrSpace;
7948   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7949     ResultAddrSpace = RAddrSpace;
7950   else {
7951     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7952         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7953         << RHS.get()->getSourceRange();
7954     return QualType();
7955   }
7956 
7957   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7958   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7959   lhQual.removeCVRQualifiers();
7960   rhQual.removeCVRQualifiers();
7961 
7962   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7963   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7964   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7965   // qual types are compatible iff
7966   //  * corresponded types are compatible
7967   //  * CVR qualifiers are equal
7968   //  * address spaces are equal
7969   // Thus for conditional operator we merge CVR and address space unqualified
7970   // pointees and if there is a composite type we return a pointer to it with
7971   // merged qualifiers.
7972   LHSCastKind =
7973       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7974   RHSCastKind =
7975       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7976   lhQual.removeAddressSpace();
7977   rhQual.removeAddressSpace();
7978 
7979   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7980   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7981 
7982   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7983 
7984   if (CompositeTy.isNull()) {
7985     // In this situation, we assume void* type. No especially good
7986     // reason, but this is what gcc does, and we do have to pick
7987     // to get a consistent AST.
7988     QualType incompatTy;
7989     incompatTy = S.Context.getPointerType(
7990         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7991     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7992     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7993 
7994     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7995     // for casts between types with incompatible address space qualifiers.
7996     // For the following code the compiler produces casts between global and
7997     // local address spaces of the corresponded innermost pointees:
7998     // local int *global *a;
7999     // global int *global *b;
8000     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8001     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8002         << LHSTy << RHSTy << LHS.get()->getSourceRange()
8003         << RHS.get()->getSourceRange();
8004 
8005     return incompatTy;
8006   }
8007 
8008   // The pointer types are compatible.
8009   // In case of OpenCL ResultTy should have the address space qualifier
8010   // which is a superset of address spaces of both the 2nd and the 3rd
8011   // operands of the conditional operator.
8012   QualType ResultTy = [&, ResultAddrSpace]() {
8013     if (S.getLangOpts().OpenCL) {
8014       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8015       CompositeQuals.setAddressSpace(ResultAddrSpace);
8016       return S.Context
8017           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8018           .withCVRQualifiers(MergedCVRQual);
8019     }
8020     return CompositeTy.withCVRQualifiers(MergedCVRQual);
8021   }();
8022   if (IsBlockPointer)
8023     ResultTy = S.Context.getBlockPointerType(ResultTy);
8024   else
8025     ResultTy = S.Context.getPointerType(ResultTy);
8026 
8027   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8028   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8029   return ResultTy;
8030 }
8031 
8032 /// Return the resulting type when the operands are both block pointers.
8033 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8034                                                           ExprResult &LHS,
8035                                                           ExprResult &RHS,
8036                                                           SourceLocation Loc) {
8037   QualType LHSTy = LHS.get()->getType();
8038   QualType RHSTy = RHS.get()->getType();
8039 
8040   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8041     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8042       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8043       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8044       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8045       return destType;
8046     }
8047     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8048       << LHSTy << RHSTy << LHS.get()->getSourceRange()
8049       << RHS.get()->getSourceRange();
8050     return QualType();
8051   }
8052 
8053   // We have 2 block pointer types.
8054   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8055 }
8056 
8057 /// Return the resulting type when the operands are both pointers.
8058 static QualType
8059 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8060                                             ExprResult &RHS,
8061                                             SourceLocation Loc) {
8062   // get the pointer types
8063   QualType LHSTy = LHS.get()->getType();
8064   QualType RHSTy = RHS.get()->getType();
8065 
8066   // get the "pointed to" types
8067   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8068   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8069 
8070   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8071   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8072     // Figure out necessary qualifiers (C99 6.5.15p6)
8073     QualType destPointee
8074       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8075     QualType destType = S.Context.getPointerType(destPointee);
8076     // Add qualifiers if necessary.
8077     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8078     // Promote to void*.
8079     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8080     return destType;
8081   }
8082   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8083     QualType destPointee
8084       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8085     QualType destType = S.Context.getPointerType(destPointee);
8086     // Add qualifiers if necessary.
8087     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8088     // Promote to void*.
8089     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8090     return destType;
8091   }
8092 
8093   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8094 }
8095 
8096 /// Return false if the first expression is not an integer and the second
8097 /// expression is not a pointer, true otherwise.
8098 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8099                                         Expr* PointerExpr, SourceLocation Loc,
8100                                         bool IsIntFirstExpr) {
8101   if (!PointerExpr->getType()->isPointerType() ||
8102       !Int.get()->getType()->isIntegerType())
8103     return false;
8104 
8105   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8106   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8107 
8108   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8109     << Expr1->getType() << Expr2->getType()
8110     << Expr1->getSourceRange() << Expr2->getSourceRange();
8111   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8112                             CK_IntegralToPointer);
8113   return true;
8114 }
8115 
8116 /// Simple conversion between integer and floating point types.
8117 ///
8118 /// Used when handling the OpenCL conditional operator where the
8119 /// condition is a vector while the other operands are scalar.
8120 ///
8121 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8122 /// types are either integer or floating type. Between the two
8123 /// operands, the type with the higher rank is defined as the "result
8124 /// type". The other operand needs to be promoted to the same type. No
8125 /// other type promotion is allowed. We cannot use
8126 /// UsualArithmeticConversions() for this purpose, since it always
8127 /// promotes promotable types.
8128 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8129                                             ExprResult &RHS,
8130                                             SourceLocation QuestionLoc) {
8131   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8132   if (LHS.isInvalid())
8133     return QualType();
8134   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8135   if (RHS.isInvalid())
8136     return QualType();
8137 
8138   // For conversion purposes, we ignore any qualifiers.
8139   // For example, "const float" and "float" are equivalent.
8140   QualType LHSType =
8141     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8142   QualType RHSType =
8143     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8144 
8145   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8146     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8147       << LHSType << LHS.get()->getSourceRange();
8148     return QualType();
8149   }
8150 
8151   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8152     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8153       << RHSType << RHS.get()->getSourceRange();
8154     return QualType();
8155   }
8156 
8157   // If both types are identical, no conversion is needed.
8158   if (LHSType == RHSType)
8159     return LHSType;
8160 
8161   // Now handle "real" floating types (i.e. float, double, long double).
8162   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8163     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8164                                  /*IsCompAssign = */ false);
8165 
8166   // Finally, we have two differing integer types.
8167   return handleIntegerConversion<doIntegralCast, doIntegralCast>
8168   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8169 }
8170 
8171 /// Convert scalar operands to a vector that matches the
8172 ///        condition in length.
8173 ///
8174 /// Used when handling the OpenCL conditional operator where the
8175 /// condition is a vector while the other operands are scalar.
8176 ///
8177 /// We first compute the "result type" for the scalar operands
8178 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8179 /// into a vector of that type where the length matches the condition
8180 /// vector type. s6.11.6 requires that the element types of the result
8181 /// and the condition must have the same number of bits.
8182 static QualType
8183 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8184                               QualType CondTy, SourceLocation QuestionLoc) {
8185   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8186   if (ResTy.isNull()) return QualType();
8187 
8188   const VectorType *CV = CondTy->getAs<VectorType>();
8189   assert(CV);
8190 
8191   // Determine the vector result type
8192   unsigned NumElements = CV->getNumElements();
8193   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8194 
8195   // Ensure that all types have the same number of bits
8196   if (S.Context.getTypeSize(CV->getElementType())
8197       != S.Context.getTypeSize(ResTy)) {
8198     // Since VectorTy is created internally, it does not pretty print
8199     // with an OpenCL name. Instead, we just print a description.
8200     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8201     SmallString<64> Str;
8202     llvm::raw_svector_ostream OS(Str);
8203     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8204     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8205       << CondTy << OS.str();
8206     return QualType();
8207   }
8208 
8209   // Convert operands to the vector result type
8210   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8211   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8212 
8213   return VectorTy;
8214 }
8215 
8216 /// Return false if this is a valid OpenCL condition vector
8217 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8218                                        SourceLocation QuestionLoc) {
8219   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8220   // integral type.
8221   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8222   assert(CondTy);
8223   QualType EleTy = CondTy->getElementType();
8224   if (EleTy->isIntegerType()) return false;
8225 
8226   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8227     << Cond->getType() << Cond->getSourceRange();
8228   return true;
8229 }
8230 
8231 /// Return false if the vector condition type and the vector
8232 ///        result type are compatible.
8233 ///
8234 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8235 /// number of elements, and their element types have the same number
8236 /// of bits.
8237 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8238                               SourceLocation QuestionLoc) {
8239   const VectorType *CV = CondTy->getAs<VectorType>();
8240   const VectorType *RV = VecResTy->getAs<VectorType>();
8241   assert(CV && RV);
8242 
8243   if (CV->getNumElements() != RV->getNumElements()) {
8244     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8245       << CondTy << VecResTy;
8246     return true;
8247   }
8248 
8249   QualType CVE = CV->getElementType();
8250   QualType RVE = RV->getElementType();
8251 
8252   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8253     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8254       << CondTy << VecResTy;
8255     return true;
8256   }
8257 
8258   return false;
8259 }
8260 
8261 /// Return the resulting type for the conditional operator in
8262 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8263 ///        s6.3.i) when the condition is a vector type.
8264 static QualType
8265 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8266                              ExprResult &LHS, ExprResult &RHS,
8267                              SourceLocation QuestionLoc) {
8268   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8269   if (Cond.isInvalid())
8270     return QualType();
8271   QualType CondTy = Cond.get()->getType();
8272 
8273   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8274     return QualType();
8275 
8276   // If either operand is a vector then find the vector type of the
8277   // result as specified in OpenCL v1.1 s6.3.i.
8278   if (LHS.get()->getType()->isVectorType() ||
8279       RHS.get()->getType()->isVectorType()) {
8280     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8281                                               /*isCompAssign*/false,
8282                                               /*AllowBothBool*/true,
8283                                               /*AllowBoolConversions*/false);
8284     if (VecResTy.isNull()) return QualType();
8285     // The result type must match the condition type as specified in
8286     // OpenCL v1.1 s6.11.6.
8287     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8288       return QualType();
8289     return VecResTy;
8290   }
8291 
8292   // Both operands are scalar.
8293   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8294 }
8295 
8296 /// Return true if the Expr is block type
8297 static bool checkBlockType(Sema &S, const Expr *E) {
8298   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8299     QualType Ty = CE->getCallee()->getType();
8300     if (Ty->isBlockPointerType()) {
8301       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8302       return true;
8303     }
8304   }
8305   return false;
8306 }
8307 
8308 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8309 /// In that case, LHS = cond.
8310 /// C99 6.5.15
8311 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8312                                         ExprResult &RHS, ExprValueKind &VK,
8313                                         ExprObjectKind &OK,
8314                                         SourceLocation QuestionLoc) {
8315 
8316   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8317   if (!LHSResult.isUsable()) return QualType();
8318   LHS = LHSResult;
8319 
8320   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8321   if (!RHSResult.isUsable()) return QualType();
8322   RHS = RHSResult;
8323 
8324   // C++ is sufficiently different to merit its own checker.
8325   if (getLangOpts().CPlusPlus)
8326     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8327 
8328   VK = VK_PRValue;
8329   OK = OK_Ordinary;
8330 
8331   if (Context.isDependenceAllowed() &&
8332       (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8333        RHS.get()->isTypeDependent())) {
8334     assert(!getLangOpts().CPlusPlus);
8335     assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8336             RHS.get()->containsErrors()) &&
8337            "should only occur in error-recovery path.");
8338     return Context.DependentTy;
8339   }
8340 
8341   // The OpenCL operator with a vector condition is sufficiently
8342   // different to merit its own checker.
8343   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8344       Cond.get()->getType()->isExtVectorType())
8345     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8346 
8347   // First, check the condition.
8348   Cond = UsualUnaryConversions(Cond.get());
8349   if (Cond.isInvalid())
8350     return QualType();
8351   if (checkCondition(*this, Cond.get(), QuestionLoc))
8352     return QualType();
8353 
8354   // Now check the two expressions.
8355   if (LHS.get()->getType()->isVectorType() ||
8356       RHS.get()->getType()->isVectorType())
8357     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8358                                /*AllowBothBool*/true,
8359                                /*AllowBoolConversions*/false);
8360 
8361   QualType ResTy =
8362       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8363   if (LHS.isInvalid() || RHS.isInvalid())
8364     return QualType();
8365 
8366   QualType LHSTy = LHS.get()->getType();
8367   QualType RHSTy = RHS.get()->getType();
8368 
8369   // Diagnose attempts to convert between __ibm128, __float128 and long double
8370   // where such conversions currently can't be handled.
8371   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8372     Diag(QuestionLoc,
8373          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8374       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8375     return QualType();
8376   }
8377 
8378   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8379   // selection operator (?:).
8380   if (getLangOpts().OpenCL &&
8381       ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8382     return QualType();
8383   }
8384 
8385   // If both operands have arithmetic type, do the usual arithmetic conversions
8386   // to find a common type: C99 6.5.15p3,5.
8387   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8388     // Disallow invalid arithmetic conversions, such as those between ExtInts of
8389     // different sizes, or between ExtInts and other types.
8390     if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8391       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8392           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8393           << RHS.get()->getSourceRange();
8394       return QualType();
8395     }
8396 
8397     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8398     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8399 
8400     return ResTy;
8401   }
8402 
8403   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8404   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8405     return LHSTy;
8406   }
8407 
8408   // If both operands are the same structure or union type, the result is that
8409   // type.
8410   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8411     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8412       if (LHSRT->getDecl() == RHSRT->getDecl())
8413         // "If both the operands have structure or union type, the result has
8414         // that type."  This implies that CV qualifiers are dropped.
8415         return LHSTy.getUnqualifiedType();
8416     // FIXME: Type of conditional expression must be complete in C mode.
8417   }
8418 
8419   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8420   // The following || allows only one side to be void (a GCC-ism).
8421   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8422     return checkConditionalVoidType(*this, LHS, RHS);
8423   }
8424 
8425   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8426   // the type of the other operand."
8427   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8428   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8429 
8430   // All objective-c pointer type analysis is done here.
8431   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8432                                                         QuestionLoc);
8433   if (LHS.isInvalid() || RHS.isInvalid())
8434     return QualType();
8435   if (!compositeType.isNull())
8436     return compositeType;
8437 
8438 
8439   // Handle block pointer types.
8440   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8441     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8442                                                      QuestionLoc);
8443 
8444   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8445   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8446     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8447                                                        QuestionLoc);
8448 
8449   // GCC compatibility: soften pointer/integer mismatch.  Note that
8450   // null pointers have been filtered out by this point.
8451   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8452       /*IsIntFirstExpr=*/true))
8453     return RHSTy;
8454   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8455       /*IsIntFirstExpr=*/false))
8456     return LHSTy;
8457 
8458   // Allow ?: operations in which both operands have the same
8459   // built-in sizeless type.
8460   if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8461     return LHSTy;
8462 
8463   // Emit a better diagnostic if one of the expressions is a null pointer
8464   // constant and the other is not a pointer type. In this case, the user most
8465   // likely forgot to take the address of the other expression.
8466   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8467     return QualType();
8468 
8469   // Otherwise, the operands are not compatible.
8470   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8471     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8472     << RHS.get()->getSourceRange();
8473   return QualType();
8474 }
8475 
8476 /// FindCompositeObjCPointerType - Helper method to find composite type of
8477 /// two objective-c pointer types of the two input expressions.
8478 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8479                                             SourceLocation QuestionLoc) {
8480   QualType LHSTy = LHS.get()->getType();
8481   QualType RHSTy = RHS.get()->getType();
8482 
8483   // Handle things like Class and struct objc_class*.  Here we case the result
8484   // to the pseudo-builtin, because that will be implicitly cast back to the
8485   // redefinition type if an attempt is made to access its fields.
8486   if (LHSTy->isObjCClassType() &&
8487       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8488     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8489     return LHSTy;
8490   }
8491   if (RHSTy->isObjCClassType() &&
8492       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8493     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8494     return RHSTy;
8495   }
8496   // And the same for struct objc_object* / id
8497   if (LHSTy->isObjCIdType() &&
8498       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8499     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8500     return LHSTy;
8501   }
8502   if (RHSTy->isObjCIdType() &&
8503       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8504     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8505     return RHSTy;
8506   }
8507   // And the same for struct objc_selector* / SEL
8508   if (Context.isObjCSelType(LHSTy) &&
8509       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8510     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8511     return LHSTy;
8512   }
8513   if (Context.isObjCSelType(RHSTy) &&
8514       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8515     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8516     return RHSTy;
8517   }
8518   // Check constraints for Objective-C object pointers types.
8519   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8520 
8521     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8522       // Two identical object pointer types are always compatible.
8523       return LHSTy;
8524     }
8525     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8526     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8527     QualType compositeType = LHSTy;
8528 
8529     // If both operands are interfaces and either operand can be
8530     // assigned to the other, use that type as the composite
8531     // type. This allows
8532     //   xxx ? (A*) a : (B*) b
8533     // where B is a subclass of A.
8534     //
8535     // Additionally, as for assignment, if either type is 'id'
8536     // allow silent coercion. Finally, if the types are
8537     // incompatible then make sure to use 'id' as the composite
8538     // type so the result is acceptable for sending messages to.
8539 
8540     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8541     // It could return the composite type.
8542     if (!(compositeType =
8543           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8544       // Nothing more to do.
8545     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8546       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8547     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8548       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8549     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8550                 RHSOPT->isObjCQualifiedIdType()) &&
8551                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8552                                                          true)) {
8553       // Need to handle "id<xx>" explicitly.
8554       // GCC allows qualified id and any Objective-C type to devolve to
8555       // id. Currently localizing to here until clear this should be
8556       // part of ObjCQualifiedIdTypesAreCompatible.
8557       compositeType = Context.getObjCIdType();
8558     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8559       compositeType = Context.getObjCIdType();
8560     } else {
8561       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8562       << LHSTy << RHSTy
8563       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8564       QualType incompatTy = Context.getObjCIdType();
8565       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8566       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8567       return incompatTy;
8568     }
8569     // The object pointer types are compatible.
8570     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8571     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8572     return compositeType;
8573   }
8574   // Check Objective-C object pointer types and 'void *'
8575   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8576     if (getLangOpts().ObjCAutoRefCount) {
8577       // ARC forbids the implicit conversion of object pointers to 'void *',
8578       // so these types are not compatible.
8579       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8580           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8581       LHS = RHS = true;
8582       return QualType();
8583     }
8584     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8585     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8586     QualType destPointee
8587     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8588     QualType destType = Context.getPointerType(destPointee);
8589     // Add qualifiers if necessary.
8590     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8591     // Promote to void*.
8592     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8593     return destType;
8594   }
8595   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8596     if (getLangOpts().ObjCAutoRefCount) {
8597       // ARC forbids the implicit conversion of object pointers to 'void *',
8598       // so these types are not compatible.
8599       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8600           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8601       LHS = RHS = true;
8602       return QualType();
8603     }
8604     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8605     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8606     QualType destPointee
8607     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8608     QualType destType = Context.getPointerType(destPointee);
8609     // Add qualifiers if necessary.
8610     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8611     // Promote to void*.
8612     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8613     return destType;
8614   }
8615   return QualType();
8616 }
8617 
8618 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8619 /// ParenRange in parentheses.
8620 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8621                                const PartialDiagnostic &Note,
8622                                SourceRange ParenRange) {
8623   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8624   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8625       EndLoc.isValid()) {
8626     Self.Diag(Loc, Note)
8627       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8628       << FixItHint::CreateInsertion(EndLoc, ")");
8629   } else {
8630     // We can't display the parentheses, so just show the bare note.
8631     Self.Diag(Loc, Note) << ParenRange;
8632   }
8633 }
8634 
8635 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8636   return BinaryOperator::isAdditiveOp(Opc) ||
8637          BinaryOperator::isMultiplicativeOp(Opc) ||
8638          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8639   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8640   // not any of the logical operators.  Bitwise-xor is commonly used as a
8641   // logical-xor because there is no logical-xor operator.  The logical
8642   // operators, including uses of xor, have a high false positive rate for
8643   // precedence warnings.
8644 }
8645 
8646 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8647 /// expression, either using a built-in or overloaded operator,
8648 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8649 /// expression.
8650 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8651                                    Expr **RHSExprs) {
8652   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8653   E = E->IgnoreImpCasts();
8654   E = E->IgnoreConversionOperatorSingleStep();
8655   E = E->IgnoreImpCasts();
8656   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8657     E = MTE->getSubExpr();
8658     E = E->IgnoreImpCasts();
8659   }
8660 
8661   // Built-in binary operator.
8662   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8663     if (IsArithmeticOp(OP->getOpcode())) {
8664       *Opcode = OP->getOpcode();
8665       *RHSExprs = OP->getRHS();
8666       return true;
8667     }
8668   }
8669 
8670   // Overloaded operator.
8671   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8672     if (Call->getNumArgs() != 2)
8673       return false;
8674 
8675     // Make sure this is really a binary operator that is safe to pass into
8676     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8677     OverloadedOperatorKind OO = Call->getOperator();
8678     if (OO < OO_Plus || OO > OO_Arrow ||
8679         OO == OO_PlusPlus || OO == OO_MinusMinus)
8680       return false;
8681 
8682     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8683     if (IsArithmeticOp(OpKind)) {
8684       *Opcode = OpKind;
8685       *RHSExprs = Call->getArg(1);
8686       return true;
8687     }
8688   }
8689 
8690   return false;
8691 }
8692 
8693 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8694 /// or is a logical expression such as (x==y) which has int type, but is
8695 /// commonly interpreted as boolean.
8696 static bool ExprLooksBoolean(Expr *E) {
8697   E = E->IgnoreParenImpCasts();
8698 
8699   if (E->getType()->isBooleanType())
8700     return true;
8701   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8702     return OP->isComparisonOp() || OP->isLogicalOp();
8703   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8704     return OP->getOpcode() == UO_LNot;
8705   if (E->getType()->isPointerType())
8706     return true;
8707   // FIXME: What about overloaded operator calls returning "unspecified boolean
8708   // type"s (commonly pointer-to-members)?
8709 
8710   return false;
8711 }
8712 
8713 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8714 /// and binary operator are mixed in a way that suggests the programmer assumed
8715 /// the conditional operator has higher precedence, for example:
8716 /// "int x = a + someBinaryCondition ? 1 : 2".
8717 static void DiagnoseConditionalPrecedence(Sema &Self,
8718                                           SourceLocation OpLoc,
8719                                           Expr *Condition,
8720                                           Expr *LHSExpr,
8721                                           Expr *RHSExpr) {
8722   BinaryOperatorKind CondOpcode;
8723   Expr *CondRHS;
8724 
8725   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8726     return;
8727   if (!ExprLooksBoolean(CondRHS))
8728     return;
8729 
8730   // The condition is an arithmetic binary expression, with a right-
8731   // hand side that looks boolean, so warn.
8732 
8733   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8734                         ? diag::warn_precedence_bitwise_conditional
8735                         : diag::warn_precedence_conditional;
8736 
8737   Self.Diag(OpLoc, DiagID)
8738       << Condition->getSourceRange()
8739       << BinaryOperator::getOpcodeStr(CondOpcode);
8740 
8741   SuggestParentheses(
8742       Self, OpLoc,
8743       Self.PDiag(diag::note_precedence_silence)
8744           << BinaryOperator::getOpcodeStr(CondOpcode),
8745       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8746 
8747   SuggestParentheses(Self, OpLoc,
8748                      Self.PDiag(diag::note_precedence_conditional_first),
8749                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8750 }
8751 
8752 /// Compute the nullability of a conditional expression.
8753 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8754                                               QualType LHSTy, QualType RHSTy,
8755                                               ASTContext &Ctx) {
8756   if (!ResTy->isAnyPointerType())
8757     return ResTy;
8758 
8759   auto GetNullability = [&Ctx](QualType Ty) {
8760     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8761     if (Kind) {
8762       // For our purposes, treat _Nullable_result as _Nullable.
8763       if (*Kind == NullabilityKind::NullableResult)
8764         return NullabilityKind::Nullable;
8765       return *Kind;
8766     }
8767     return NullabilityKind::Unspecified;
8768   };
8769 
8770   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8771   NullabilityKind MergedKind;
8772 
8773   // Compute nullability of a binary conditional expression.
8774   if (IsBin) {
8775     if (LHSKind == NullabilityKind::NonNull)
8776       MergedKind = NullabilityKind::NonNull;
8777     else
8778       MergedKind = RHSKind;
8779   // Compute nullability of a normal conditional expression.
8780   } else {
8781     if (LHSKind == NullabilityKind::Nullable ||
8782         RHSKind == NullabilityKind::Nullable)
8783       MergedKind = NullabilityKind::Nullable;
8784     else if (LHSKind == NullabilityKind::NonNull)
8785       MergedKind = RHSKind;
8786     else if (RHSKind == NullabilityKind::NonNull)
8787       MergedKind = LHSKind;
8788     else
8789       MergedKind = NullabilityKind::Unspecified;
8790   }
8791 
8792   // Return if ResTy already has the correct nullability.
8793   if (GetNullability(ResTy) == MergedKind)
8794     return ResTy;
8795 
8796   // Strip all nullability from ResTy.
8797   while (ResTy->getNullability(Ctx))
8798     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8799 
8800   // Create a new AttributedType with the new nullability kind.
8801   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8802   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8803 }
8804 
8805 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8806 /// in the case of a the GNU conditional expr extension.
8807 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8808                                     SourceLocation ColonLoc,
8809                                     Expr *CondExpr, Expr *LHSExpr,
8810                                     Expr *RHSExpr) {
8811   if (!Context.isDependenceAllowed()) {
8812     // C cannot handle TypoExpr nodes in the condition because it
8813     // doesn't handle dependent types properly, so make sure any TypoExprs have
8814     // been dealt with before checking the operands.
8815     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8816     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8817     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8818 
8819     if (!CondResult.isUsable())
8820       return ExprError();
8821 
8822     if (LHSExpr) {
8823       if (!LHSResult.isUsable())
8824         return ExprError();
8825     }
8826 
8827     if (!RHSResult.isUsable())
8828       return ExprError();
8829 
8830     CondExpr = CondResult.get();
8831     LHSExpr = LHSResult.get();
8832     RHSExpr = RHSResult.get();
8833   }
8834 
8835   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8836   // was the condition.
8837   OpaqueValueExpr *opaqueValue = nullptr;
8838   Expr *commonExpr = nullptr;
8839   if (!LHSExpr) {
8840     commonExpr = CondExpr;
8841     // Lower out placeholder types first.  This is important so that we don't
8842     // try to capture a placeholder. This happens in few cases in C++; such
8843     // as Objective-C++'s dictionary subscripting syntax.
8844     if (commonExpr->hasPlaceholderType()) {
8845       ExprResult result = CheckPlaceholderExpr(commonExpr);
8846       if (!result.isUsable()) return ExprError();
8847       commonExpr = result.get();
8848     }
8849     // We usually want to apply unary conversions *before* saving, except
8850     // in the special case of a C++ l-value conditional.
8851     if (!(getLangOpts().CPlusPlus
8852           && !commonExpr->isTypeDependent()
8853           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8854           && commonExpr->isGLValue()
8855           && commonExpr->isOrdinaryOrBitFieldObject()
8856           && RHSExpr->isOrdinaryOrBitFieldObject()
8857           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8858       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8859       if (commonRes.isInvalid())
8860         return ExprError();
8861       commonExpr = commonRes.get();
8862     }
8863 
8864     // If the common expression is a class or array prvalue, materialize it
8865     // so that we can safely refer to it multiple times.
8866     if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8867                                     commonExpr->getType()->isArrayType())) {
8868       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8869       if (MatExpr.isInvalid())
8870         return ExprError();
8871       commonExpr = MatExpr.get();
8872     }
8873 
8874     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8875                                                 commonExpr->getType(),
8876                                                 commonExpr->getValueKind(),
8877                                                 commonExpr->getObjectKind(),
8878                                                 commonExpr);
8879     LHSExpr = CondExpr = opaqueValue;
8880   }
8881 
8882   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8883   ExprValueKind VK = VK_PRValue;
8884   ExprObjectKind OK = OK_Ordinary;
8885   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8886   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8887                                              VK, OK, QuestionLoc);
8888   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8889       RHS.isInvalid())
8890     return ExprError();
8891 
8892   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8893                                 RHS.get());
8894 
8895   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8896 
8897   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8898                                          Context);
8899 
8900   if (!commonExpr)
8901     return new (Context)
8902         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8903                             RHS.get(), result, VK, OK);
8904 
8905   return new (Context) BinaryConditionalOperator(
8906       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8907       ColonLoc, result, VK, OK);
8908 }
8909 
8910 // Check if we have a conversion between incompatible cmse function pointer
8911 // types, that is, a conversion between a function pointer with the
8912 // cmse_nonsecure_call attribute and one without.
8913 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8914                                           QualType ToType) {
8915   if (const auto *ToFn =
8916           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8917     if (const auto *FromFn =
8918             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8919       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8920       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8921 
8922       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8923     }
8924   }
8925   return false;
8926 }
8927 
8928 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8929 // being closely modeled after the C99 spec:-). The odd characteristic of this
8930 // routine is it effectively iqnores the qualifiers on the top level pointee.
8931 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8932 // FIXME: add a couple examples in this comment.
8933 static Sema::AssignConvertType
8934 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8935   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8936   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8937 
8938   // get the "pointed to" type (ignoring qualifiers at the top level)
8939   const Type *lhptee, *rhptee;
8940   Qualifiers lhq, rhq;
8941   std::tie(lhptee, lhq) =
8942       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8943   std::tie(rhptee, rhq) =
8944       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8945 
8946   Sema::AssignConvertType ConvTy = Sema::Compatible;
8947 
8948   // C99 6.5.16.1p1: This following citation is common to constraints
8949   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8950   // qualifiers of the type *pointed to* by the right;
8951 
8952   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8953   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8954       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8955     // Ignore lifetime for further calculation.
8956     lhq.removeObjCLifetime();
8957     rhq.removeObjCLifetime();
8958   }
8959 
8960   if (!lhq.compatiblyIncludes(rhq)) {
8961     // Treat address-space mismatches as fatal.
8962     if (!lhq.isAddressSpaceSupersetOf(rhq))
8963       return Sema::IncompatiblePointerDiscardsQualifiers;
8964 
8965     // It's okay to add or remove GC or lifetime qualifiers when converting to
8966     // and from void*.
8967     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8968                         .compatiblyIncludes(
8969                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8970              && (lhptee->isVoidType() || rhptee->isVoidType()))
8971       ; // keep old
8972 
8973     // Treat lifetime mismatches as fatal.
8974     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8975       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8976 
8977     // For GCC/MS compatibility, other qualifier mismatches are treated
8978     // as still compatible in C.
8979     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8980   }
8981 
8982   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8983   // incomplete type and the other is a pointer to a qualified or unqualified
8984   // version of void...
8985   if (lhptee->isVoidType()) {
8986     if (rhptee->isIncompleteOrObjectType())
8987       return ConvTy;
8988 
8989     // As an extension, we allow cast to/from void* to function pointer.
8990     assert(rhptee->isFunctionType());
8991     return Sema::FunctionVoidPointer;
8992   }
8993 
8994   if (rhptee->isVoidType()) {
8995     if (lhptee->isIncompleteOrObjectType())
8996       return ConvTy;
8997 
8998     // As an extension, we allow cast to/from void* to function pointer.
8999     assert(lhptee->isFunctionType());
9000     return Sema::FunctionVoidPointer;
9001   }
9002 
9003   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9004   // unqualified versions of compatible types, ...
9005   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9006   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9007     // Check if the pointee types are compatible ignoring the sign.
9008     // We explicitly check for char so that we catch "char" vs
9009     // "unsigned char" on systems where "char" is unsigned.
9010     if (lhptee->isCharType())
9011       ltrans = S.Context.UnsignedCharTy;
9012     else if (lhptee->hasSignedIntegerRepresentation())
9013       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9014 
9015     if (rhptee->isCharType())
9016       rtrans = S.Context.UnsignedCharTy;
9017     else if (rhptee->hasSignedIntegerRepresentation())
9018       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9019 
9020     if (ltrans == rtrans) {
9021       // Types are compatible ignoring the sign. Qualifier incompatibility
9022       // takes priority over sign incompatibility because the sign
9023       // warning can be disabled.
9024       if (ConvTy != Sema::Compatible)
9025         return ConvTy;
9026 
9027       return Sema::IncompatiblePointerSign;
9028     }
9029 
9030     // If we are a multi-level pointer, it's possible that our issue is simply
9031     // one of qualification - e.g. char ** -> const char ** is not allowed. If
9032     // the eventual target type is the same and the pointers have the same
9033     // level of indirection, this must be the issue.
9034     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9035       do {
9036         std::tie(lhptee, lhq) =
9037           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9038         std::tie(rhptee, rhq) =
9039           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9040 
9041         // Inconsistent address spaces at this point is invalid, even if the
9042         // address spaces would be compatible.
9043         // FIXME: This doesn't catch address space mismatches for pointers of
9044         // different nesting levels, like:
9045         //   __local int *** a;
9046         //   int ** b = a;
9047         // It's not clear how to actually determine when such pointers are
9048         // invalidly incompatible.
9049         if (lhq.getAddressSpace() != rhq.getAddressSpace())
9050           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9051 
9052       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9053 
9054       if (lhptee == rhptee)
9055         return Sema::IncompatibleNestedPointerQualifiers;
9056     }
9057 
9058     // General pointer incompatibility takes priority over qualifiers.
9059     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9060       return Sema::IncompatibleFunctionPointer;
9061     return Sema::IncompatiblePointer;
9062   }
9063   if (!S.getLangOpts().CPlusPlus &&
9064       S.IsFunctionConversion(ltrans, rtrans, ltrans))
9065     return Sema::IncompatibleFunctionPointer;
9066   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9067     return Sema::IncompatibleFunctionPointer;
9068   return ConvTy;
9069 }
9070 
9071 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9072 /// block pointer types are compatible or whether a block and normal pointer
9073 /// are compatible. It is more restrict than comparing two function pointer
9074 // types.
9075 static Sema::AssignConvertType
9076 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9077                                     QualType RHSType) {
9078   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9079   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9080 
9081   QualType lhptee, rhptee;
9082 
9083   // get the "pointed to" type (ignoring qualifiers at the top level)
9084   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9085   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9086 
9087   // In C++, the types have to match exactly.
9088   if (S.getLangOpts().CPlusPlus)
9089     return Sema::IncompatibleBlockPointer;
9090 
9091   Sema::AssignConvertType ConvTy = Sema::Compatible;
9092 
9093   // For blocks we enforce that qualifiers are identical.
9094   Qualifiers LQuals = lhptee.getLocalQualifiers();
9095   Qualifiers RQuals = rhptee.getLocalQualifiers();
9096   if (S.getLangOpts().OpenCL) {
9097     LQuals.removeAddressSpace();
9098     RQuals.removeAddressSpace();
9099   }
9100   if (LQuals != RQuals)
9101     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9102 
9103   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9104   // assignment.
9105   // The current behavior is similar to C++ lambdas. A block might be
9106   // assigned to a variable iff its return type and parameters are compatible
9107   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9108   // an assignment. Presumably it should behave in way that a function pointer
9109   // assignment does in C, so for each parameter and return type:
9110   //  * CVR and address space of LHS should be a superset of CVR and address
9111   //  space of RHS.
9112   //  * unqualified types should be compatible.
9113   if (S.getLangOpts().OpenCL) {
9114     if (!S.Context.typesAreBlockPointerCompatible(
9115             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9116             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9117       return Sema::IncompatibleBlockPointer;
9118   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9119     return Sema::IncompatibleBlockPointer;
9120 
9121   return ConvTy;
9122 }
9123 
9124 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9125 /// for assignment compatibility.
9126 static Sema::AssignConvertType
9127 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9128                                    QualType RHSType) {
9129   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9130   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9131 
9132   if (LHSType->isObjCBuiltinType()) {
9133     // Class is not compatible with ObjC object pointers.
9134     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9135         !RHSType->isObjCQualifiedClassType())
9136       return Sema::IncompatiblePointer;
9137     return Sema::Compatible;
9138   }
9139   if (RHSType->isObjCBuiltinType()) {
9140     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9141         !LHSType->isObjCQualifiedClassType())
9142       return Sema::IncompatiblePointer;
9143     return Sema::Compatible;
9144   }
9145   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9146   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9147 
9148   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9149       // make an exception for id<P>
9150       !LHSType->isObjCQualifiedIdType())
9151     return Sema::CompatiblePointerDiscardsQualifiers;
9152 
9153   if (S.Context.typesAreCompatible(LHSType, RHSType))
9154     return Sema::Compatible;
9155   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9156     return Sema::IncompatibleObjCQualifiedId;
9157   return Sema::IncompatiblePointer;
9158 }
9159 
9160 Sema::AssignConvertType
9161 Sema::CheckAssignmentConstraints(SourceLocation Loc,
9162                                  QualType LHSType, QualType RHSType) {
9163   // Fake up an opaque expression.  We don't actually care about what
9164   // cast operations are required, so if CheckAssignmentConstraints
9165   // adds casts to this they'll be wasted, but fortunately that doesn't
9166   // usually happen on valid code.
9167   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9168   ExprResult RHSPtr = &RHSExpr;
9169   CastKind K;
9170 
9171   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9172 }
9173 
9174 /// This helper function returns true if QT is a vector type that has element
9175 /// type ElementType.
9176 static bool isVector(QualType QT, QualType ElementType) {
9177   if (const VectorType *VT = QT->getAs<VectorType>())
9178     return VT->getElementType().getCanonicalType() == ElementType;
9179   return false;
9180 }
9181 
9182 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9183 /// has code to accommodate several GCC extensions when type checking
9184 /// pointers. Here are some objectionable examples that GCC considers warnings:
9185 ///
9186 ///  int a, *pint;
9187 ///  short *pshort;
9188 ///  struct foo *pfoo;
9189 ///
9190 ///  pint = pshort; // warning: assignment from incompatible pointer type
9191 ///  a = pint; // warning: assignment makes integer from pointer without a cast
9192 ///  pint = a; // warning: assignment makes pointer from integer without a cast
9193 ///  pint = pfoo; // warning: assignment from incompatible pointer type
9194 ///
9195 /// As a result, the code for dealing with pointers is more complex than the
9196 /// C99 spec dictates.
9197 ///
9198 /// Sets 'Kind' for any result kind except Incompatible.
9199 Sema::AssignConvertType
9200 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9201                                  CastKind &Kind, bool ConvertRHS) {
9202   QualType RHSType = RHS.get()->getType();
9203   QualType OrigLHSType = LHSType;
9204 
9205   // Get canonical types.  We're not formatting these types, just comparing
9206   // them.
9207   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9208   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9209 
9210   // Common case: no conversion required.
9211   if (LHSType == RHSType) {
9212     Kind = CK_NoOp;
9213     return Compatible;
9214   }
9215 
9216   // If we have an atomic type, try a non-atomic assignment, then just add an
9217   // atomic qualification step.
9218   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9219     Sema::AssignConvertType result =
9220       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9221     if (result != Compatible)
9222       return result;
9223     if (Kind != CK_NoOp && ConvertRHS)
9224       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9225     Kind = CK_NonAtomicToAtomic;
9226     return Compatible;
9227   }
9228 
9229   // If the left-hand side is a reference type, then we are in a
9230   // (rare!) case where we've allowed the use of references in C,
9231   // e.g., as a parameter type in a built-in function. In this case,
9232   // just make sure that the type referenced is compatible with the
9233   // right-hand side type. The caller is responsible for adjusting
9234   // LHSType so that the resulting expression does not have reference
9235   // type.
9236   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9237     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9238       Kind = CK_LValueBitCast;
9239       return Compatible;
9240     }
9241     return Incompatible;
9242   }
9243 
9244   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9245   // to the same ExtVector type.
9246   if (LHSType->isExtVectorType()) {
9247     if (RHSType->isExtVectorType())
9248       return Incompatible;
9249     if (RHSType->isArithmeticType()) {
9250       // CK_VectorSplat does T -> vector T, so first cast to the element type.
9251       if (ConvertRHS)
9252         RHS = prepareVectorSplat(LHSType, RHS.get());
9253       Kind = CK_VectorSplat;
9254       return Compatible;
9255     }
9256   }
9257 
9258   // Conversions to or from vector type.
9259   if (LHSType->isVectorType() || RHSType->isVectorType()) {
9260     if (LHSType->isVectorType() && RHSType->isVectorType()) {
9261       // Allow assignments of an AltiVec vector type to an equivalent GCC
9262       // vector type and vice versa
9263       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9264         Kind = CK_BitCast;
9265         return Compatible;
9266       }
9267 
9268       // If we are allowing lax vector conversions, and LHS and RHS are both
9269       // vectors, the total size only needs to be the same. This is a bitcast;
9270       // no bits are changed but the result type is different.
9271       if (isLaxVectorConversion(RHSType, LHSType)) {
9272         Kind = CK_BitCast;
9273         return IncompatibleVectors;
9274       }
9275     }
9276 
9277     // When the RHS comes from another lax conversion (e.g. binops between
9278     // scalars and vectors) the result is canonicalized as a vector. When the
9279     // LHS is also a vector, the lax is allowed by the condition above. Handle
9280     // the case where LHS is a scalar.
9281     if (LHSType->isScalarType()) {
9282       const VectorType *VecType = RHSType->getAs<VectorType>();
9283       if (VecType && VecType->getNumElements() == 1 &&
9284           isLaxVectorConversion(RHSType, LHSType)) {
9285         ExprResult *VecExpr = &RHS;
9286         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9287         Kind = CK_BitCast;
9288         return Compatible;
9289       }
9290     }
9291 
9292     // Allow assignments between fixed-length and sizeless SVE vectors.
9293     if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9294         (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9295       if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9296           Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9297         Kind = CK_BitCast;
9298         return Compatible;
9299       }
9300 
9301     return Incompatible;
9302   }
9303 
9304   // Diagnose attempts to convert between __ibm128, __float128 and long double
9305   // where such conversions currently can't be handled.
9306   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9307     return Incompatible;
9308 
9309   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9310   // discards the imaginary part.
9311   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9312       !LHSType->getAs<ComplexType>())
9313     return Incompatible;
9314 
9315   // Arithmetic conversions.
9316   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9317       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9318     if (ConvertRHS)
9319       Kind = PrepareScalarCast(RHS, LHSType);
9320     return Compatible;
9321   }
9322 
9323   // Conversions to normal pointers.
9324   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9325     // U* -> T*
9326     if (isa<PointerType>(RHSType)) {
9327       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9328       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9329       if (AddrSpaceL != AddrSpaceR)
9330         Kind = CK_AddressSpaceConversion;
9331       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9332         Kind = CK_NoOp;
9333       else
9334         Kind = CK_BitCast;
9335       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9336     }
9337 
9338     // int -> T*
9339     if (RHSType->isIntegerType()) {
9340       Kind = CK_IntegralToPointer; // FIXME: null?
9341       return IntToPointer;
9342     }
9343 
9344     // C pointers are not compatible with ObjC object pointers,
9345     // with two exceptions:
9346     if (isa<ObjCObjectPointerType>(RHSType)) {
9347       //  - conversions to void*
9348       if (LHSPointer->getPointeeType()->isVoidType()) {
9349         Kind = CK_BitCast;
9350         return Compatible;
9351       }
9352 
9353       //  - conversions from 'Class' to the redefinition type
9354       if (RHSType->isObjCClassType() &&
9355           Context.hasSameType(LHSType,
9356                               Context.getObjCClassRedefinitionType())) {
9357         Kind = CK_BitCast;
9358         return Compatible;
9359       }
9360 
9361       Kind = CK_BitCast;
9362       return IncompatiblePointer;
9363     }
9364 
9365     // U^ -> void*
9366     if (RHSType->getAs<BlockPointerType>()) {
9367       if (LHSPointer->getPointeeType()->isVoidType()) {
9368         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9369         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9370                                 ->getPointeeType()
9371                                 .getAddressSpace();
9372         Kind =
9373             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9374         return Compatible;
9375       }
9376     }
9377 
9378     return Incompatible;
9379   }
9380 
9381   // Conversions to block pointers.
9382   if (isa<BlockPointerType>(LHSType)) {
9383     // U^ -> T^
9384     if (RHSType->isBlockPointerType()) {
9385       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9386                               ->getPointeeType()
9387                               .getAddressSpace();
9388       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9389                               ->getPointeeType()
9390                               .getAddressSpace();
9391       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9392       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9393     }
9394 
9395     // int or null -> T^
9396     if (RHSType->isIntegerType()) {
9397       Kind = CK_IntegralToPointer; // FIXME: null
9398       return IntToBlockPointer;
9399     }
9400 
9401     // id -> T^
9402     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9403       Kind = CK_AnyPointerToBlockPointerCast;
9404       return Compatible;
9405     }
9406 
9407     // void* -> T^
9408     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9409       if (RHSPT->getPointeeType()->isVoidType()) {
9410         Kind = CK_AnyPointerToBlockPointerCast;
9411         return Compatible;
9412       }
9413 
9414     return Incompatible;
9415   }
9416 
9417   // Conversions to Objective-C pointers.
9418   if (isa<ObjCObjectPointerType>(LHSType)) {
9419     // A* -> B*
9420     if (RHSType->isObjCObjectPointerType()) {
9421       Kind = CK_BitCast;
9422       Sema::AssignConvertType result =
9423         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9424       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9425           result == Compatible &&
9426           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9427         result = IncompatibleObjCWeakRef;
9428       return result;
9429     }
9430 
9431     // int or null -> A*
9432     if (RHSType->isIntegerType()) {
9433       Kind = CK_IntegralToPointer; // FIXME: null
9434       return IntToPointer;
9435     }
9436 
9437     // In general, C pointers are not compatible with ObjC object pointers,
9438     // with two exceptions:
9439     if (isa<PointerType>(RHSType)) {
9440       Kind = CK_CPointerToObjCPointerCast;
9441 
9442       //  - conversions from 'void*'
9443       if (RHSType->isVoidPointerType()) {
9444         return Compatible;
9445       }
9446 
9447       //  - conversions to 'Class' from its redefinition type
9448       if (LHSType->isObjCClassType() &&
9449           Context.hasSameType(RHSType,
9450                               Context.getObjCClassRedefinitionType())) {
9451         return Compatible;
9452       }
9453 
9454       return IncompatiblePointer;
9455     }
9456 
9457     // Only under strict condition T^ is compatible with an Objective-C pointer.
9458     if (RHSType->isBlockPointerType() &&
9459         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9460       if (ConvertRHS)
9461         maybeExtendBlockObject(RHS);
9462       Kind = CK_BlockPointerToObjCPointerCast;
9463       return Compatible;
9464     }
9465 
9466     return Incompatible;
9467   }
9468 
9469   // Conversions from pointers that are not covered by the above.
9470   if (isa<PointerType>(RHSType)) {
9471     // T* -> _Bool
9472     if (LHSType == Context.BoolTy) {
9473       Kind = CK_PointerToBoolean;
9474       return Compatible;
9475     }
9476 
9477     // T* -> int
9478     if (LHSType->isIntegerType()) {
9479       Kind = CK_PointerToIntegral;
9480       return PointerToInt;
9481     }
9482 
9483     return Incompatible;
9484   }
9485 
9486   // Conversions from Objective-C pointers that are not covered by the above.
9487   if (isa<ObjCObjectPointerType>(RHSType)) {
9488     // T* -> _Bool
9489     if (LHSType == Context.BoolTy) {
9490       Kind = CK_PointerToBoolean;
9491       return Compatible;
9492     }
9493 
9494     // T* -> int
9495     if (LHSType->isIntegerType()) {
9496       Kind = CK_PointerToIntegral;
9497       return PointerToInt;
9498     }
9499 
9500     return Incompatible;
9501   }
9502 
9503   // struct A -> struct B
9504   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9505     if (Context.typesAreCompatible(LHSType, RHSType)) {
9506       Kind = CK_NoOp;
9507       return Compatible;
9508     }
9509   }
9510 
9511   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9512     Kind = CK_IntToOCLSampler;
9513     return Compatible;
9514   }
9515 
9516   return Incompatible;
9517 }
9518 
9519 /// Constructs a transparent union from an expression that is
9520 /// used to initialize the transparent union.
9521 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9522                                       ExprResult &EResult, QualType UnionType,
9523                                       FieldDecl *Field) {
9524   // Build an initializer list that designates the appropriate member
9525   // of the transparent union.
9526   Expr *E = EResult.get();
9527   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9528                                                    E, SourceLocation());
9529   Initializer->setType(UnionType);
9530   Initializer->setInitializedFieldInUnion(Field);
9531 
9532   // Build a compound literal constructing a value of the transparent
9533   // union type from this initializer list.
9534   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9535   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9536                                         VK_PRValue, Initializer, false);
9537 }
9538 
9539 Sema::AssignConvertType
9540 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9541                                                ExprResult &RHS) {
9542   QualType RHSType = RHS.get()->getType();
9543 
9544   // If the ArgType is a Union type, we want to handle a potential
9545   // transparent_union GCC extension.
9546   const RecordType *UT = ArgType->getAsUnionType();
9547   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9548     return Incompatible;
9549 
9550   // The field to initialize within the transparent union.
9551   RecordDecl *UD = UT->getDecl();
9552   FieldDecl *InitField = nullptr;
9553   // It's compatible if the expression matches any of the fields.
9554   for (auto *it : UD->fields()) {
9555     if (it->getType()->isPointerType()) {
9556       // If the transparent union contains a pointer type, we allow:
9557       // 1) void pointer
9558       // 2) null pointer constant
9559       if (RHSType->isPointerType())
9560         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9561           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9562           InitField = it;
9563           break;
9564         }
9565 
9566       if (RHS.get()->isNullPointerConstant(Context,
9567                                            Expr::NPC_ValueDependentIsNull)) {
9568         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9569                                 CK_NullToPointer);
9570         InitField = it;
9571         break;
9572       }
9573     }
9574 
9575     CastKind Kind;
9576     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9577           == Compatible) {
9578       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9579       InitField = it;
9580       break;
9581     }
9582   }
9583 
9584   if (!InitField)
9585     return Incompatible;
9586 
9587   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9588   return Compatible;
9589 }
9590 
9591 Sema::AssignConvertType
9592 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9593                                        bool Diagnose,
9594                                        bool DiagnoseCFAudited,
9595                                        bool ConvertRHS) {
9596   // We need to be able to tell the caller whether we diagnosed a problem, if
9597   // they ask us to issue diagnostics.
9598   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9599 
9600   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9601   // we can't avoid *all* modifications at the moment, so we need some somewhere
9602   // to put the updated value.
9603   ExprResult LocalRHS = CallerRHS;
9604   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9605 
9606   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9607     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9608       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9609           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9610         Diag(RHS.get()->getExprLoc(),
9611              diag::warn_noderef_to_dereferenceable_pointer)
9612             << RHS.get()->getSourceRange();
9613       }
9614     }
9615   }
9616 
9617   if (getLangOpts().CPlusPlus) {
9618     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9619       // C++ 5.17p3: If the left operand is not of class type, the
9620       // expression is implicitly converted (C++ 4) to the
9621       // cv-unqualified type of the left operand.
9622       QualType RHSType = RHS.get()->getType();
9623       if (Diagnose) {
9624         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9625                                         AA_Assigning);
9626       } else {
9627         ImplicitConversionSequence ICS =
9628             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9629                                   /*SuppressUserConversions=*/false,
9630                                   AllowedExplicit::None,
9631                                   /*InOverloadResolution=*/false,
9632                                   /*CStyle=*/false,
9633                                   /*AllowObjCWritebackConversion=*/false);
9634         if (ICS.isFailure())
9635           return Incompatible;
9636         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9637                                         ICS, AA_Assigning);
9638       }
9639       if (RHS.isInvalid())
9640         return Incompatible;
9641       Sema::AssignConvertType result = Compatible;
9642       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9643           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9644         result = IncompatibleObjCWeakRef;
9645       return result;
9646     }
9647 
9648     // FIXME: Currently, we fall through and treat C++ classes like C
9649     // structures.
9650     // FIXME: We also fall through for atomics; not sure what should
9651     // happen there, though.
9652   } else if (RHS.get()->getType() == Context.OverloadTy) {
9653     // As a set of extensions to C, we support overloading on functions. These
9654     // functions need to be resolved here.
9655     DeclAccessPair DAP;
9656     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9657             RHS.get(), LHSType, /*Complain=*/false, DAP))
9658       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9659     else
9660       return Incompatible;
9661   }
9662 
9663   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9664   // a null pointer constant.
9665   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9666        LHSType->isBlockPointerType()) &&
9667       RHS.get()->isNullPointerConstant(Context,
9668                                        Expr::NPC_ValueDependentIsNull)) {
9669     if (Diagnose || ConvertRHS) {
9670       CastKind Kind;
9671       CXXCastPath Path;
9672       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9673                              /*IgnoreBaseAccess=*/false, Diagnose);
9674       if (ConvertRHS)
9675         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9676     }
9677     return Compatible;
9678   }
9679 
9680   // OpenCL queue_t type assignment.
9681   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9682                                  Context, Expr::NPC_ValueDependentIsNull)) {
9683     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9684     return Compatible;
9685   }
9686 
9687   // This check seems unnatural, however it is necessary to ensure the proper
9688   // conversion of functions/arrays. If the conversion were done for all
9689   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9690   // expressions that suppress this implicit conversion (&, sizeof).
9691   //
9692   // Suppress this for references: C++ 8.5.3p5.
9693   if (!LHSType->isReferenceType()) {
9694     // FIXME: We potentially allocate here even if ConvertRHS is false.
9695     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9696     if (RHS.isInvalid())
9697       return Incompatible;
9698   }
9699   CastKind Kind;
9700   Sema::AssignConvertType result =
9701     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9702 
9703   // C99 6.5.16.1p2: The value of the right operand is converted to the
9704   // type of the assignment expression.
9705   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9706   // so that we can use references in built-in functions even in C.
9707   // The getNonReferenceType() call makes sure that the resulting expression
9708   // does not have reference type.
9709   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9710     QualType Ty = LHSType.getNonLValueExprType(Context);
9711     Expr *E = RHS.get();
9712 
9713     // Check for various Objective-C errors. If we are not reporting
9714     // diagnostics and just checking for errors, e.g., during overload
9715     // resolution, return Incompatible to indicate the failure.
9716     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9717         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9718                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9719       if (!Diagnose)
9720         return Incompatible;
9721     }
9722     if (getLangOpts().ObjC &&
9723         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9724                                            E->getType(), E, Diagnose) ||
9725          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9726       if (!Diagnose)
9727         return Incompatible;
9728       // Replace the expression with a corrected version and continue so we
9729       // can find further errors.
9730       RHS = E;
9731       return Compatible;
9732     }
9733 
9734     if (ConvertRHS)
9735       RHS = ImpCastExprToType(E, Ty, Kind);
9736   }
9737 
9738   return result;
9739 }
9740 
9741 namespace {
9742 /// The original operand to an operator, prior to the application of the usual
9743 /// arithmetic conversions and converting the arguments of a builtin operator
9744 /// candidate.
9745 struct OriginalOperand {
9746   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9747     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9748       Op = MTE->getSubExpr();
9749     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9750       Op = BTE->getSubExpr();
9751     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9752       Orig = ICE->getSubExprAsWritten();
9753       Conversion = ICE->getConversionFunction();
9754     }
9755   }
9756 
9757   QualType getType() const { return Orig->getType(); }
9758 
9759   Expr *Orig;
9760   NamedDecl *Conversion;
9761 };
9762 }
9763 
9764 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9765                                ExprResult &RHS) {
9766   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9767 
9768   Diag(Loc, diag::err_typecheck_invalid_operands)
9769     << OrigLHS.getType() << OrigRHS.getType()
9770     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9771 
9772   // If a user-defined conversion was applied to either of the operands prior
9773   // to applying the built-in operator rules, tell the user about it.
9774   if (OrigLHS.Conversion) {
9775     Diag(OrigLHS.Conversion->getLocation(),
9776          diag::note_typecheck_invalid_operands_converted)
9777       << 0 << LHS.get()->getType();
9778   }
9779   if (OrigRHS.Conversion) {
9780     Diag(OrigRHS.Conversion->getLocation(),
9781          diag::note_typecheck_invalid_operands_converted)
9782       << 1 << RHS.get()->getType();
9783   }
9784 
9785   return QualType();
9786 }
9787 
9788 // Diagnose cases where a scalar was implicitly converted to a vector and
9789 // diagnose the underlying types. Otherwise, diagnose the error
9790 // as invalid vector logical operands for non-C++ cases.
9791 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9792                                             ExprResult &RHS) {
9793   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9794   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9795 
9796   bool LHSNatVec = LHSType->isVectorType();
9797   bool RHSNatVec = RHSType->isVectorType();
9798 
9799   if (!(LHSNatVec && RHSNatVec)) {
9800     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9801     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9802     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9803         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9804         << Vector->getSourceRange();
9805     return QualType();
9806   }
9807 
9808   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9809       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9810       << RHS.get()->getSourceRange();
9811 
9812   return QualType();
9813 }
9814 
9815 /// Try to convert a value of non-vector type to a vector type by converting
9816 /// the type to the element type of the vector and then performing a splat.
9817 /// If the language is OpenCL, we only use conversions that promote scalar
9818 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9819 /// for float->int.
9820 ///
9821 /// OpenCL V2.0 6.2.6.p2:
9822 /// An error shall occur if any scalar operand type has greater rank
9823 /// than the type of the vector element.
9824 ///
9825 /// \param scalar - if non-null, actually perform the conversions
9826 /// \return true if the operation fails (but without diagnosing the failure)
9827 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9828                                      QualType scalarTy,
9829                                      QualType vectorEltTy,
9830                                      QualType vectorTy,
9831                                      unsigned &DiagID) {
9832   // The conversion to apply to the scalar before splatting it,
9833   // if necessary.
9834   CastKind scalarCast = CK_NoOp;
9835 
9836   if (vectorEltTy->isIntegralType(S.Context)) {
9837     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9838         (scalarTy->isIntegerType() &&
9839          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9840       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9841       return true;
9842     }
9843     if (!scalarTy->isIntegralType(S.Context))
9844       return true;
9845     scalarCast = CK_IntegralCast;
9846   } else if (vectorEltTy->isRealFloatingType()) {
9847     if (scalarTy->isRealFloatingType()) {
9848       if (S.getLangOpts().OpenCL &&
9849           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9850         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9851         return true;
9852       }
9853       scalarCast = CK_FloatingCast;
9854     }
9855     else if (scalarTy->isIntegralType(S.Context))
9856       scalarCast = CK_IntegralToFloating;
9857     else
9858       return true;
9859   } else {
9860     return true;
9861   }
9862 
9863   // Adjust scalar if desired.
9864   if (scalar) {
9865     if (scalarCast != CK_NoOp)
9866       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9867     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9868   }
9869   return false;
9870 }
9871 
9872 /// Convert vector E to a vector with the same number of elements but different
9873 /// element type.
9874 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9875   const auto *VecTy = E->getType()->getAs<VectorType>();
9876   assert(VecTy && "Expression E must be a vector");
9877   QualType NewVecTy = S.Context.getVectorType(ElementType,
9878                                               VecTy->getNumElements(),
9879                                               VecTy->getVectorKind());
9880 
9881   // Look through the implicit cast. Return the subexpression if its type is
9882   // NewVecTy.
9883   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9884     if (ICE->getSubExpr()->getType() == NewVecTy)
9885       return ICE->getSubExpr();
9886 
9887   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9888   return S.ImpCastExprToType(E, NewVecTy, Cast);
9889 }
9890 
9891 /// Test if a (constant) integer Int can be casted to another integer type
9892 /// IntTy without losing precision.
9893 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9894                                       QualType OtherIntTy) {
9895   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9896 
9897   // Reject cases where the value of the Int is unknown as that would
9898   // possibly cause truncation, but accept cases where the scalar can be
9899   // demoted without loss of precision.
9900   Expr::EvalResult EVResult;
9901   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9902   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9903   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9904   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9905 
9906   if (CstInt) {
9907     // If the scalar is constant and is of a higher order and has more active
9908     // bits that the vector element type, reject it.
9909     llvm::APSInt Result = EVResult.Val.getInt();
9910     unsigned NumBits = IntSigned
9911                            ? (Result.isNegative() ? Result.getMinSignedBits()
9912                                                   : Result.getActiveBits())
9913                            : Result.getActiveBits();
9914     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9915       return true;
9916 
9917     // If the signedness of the scalar type and the vector element type
9918     // differs and the number of bits is greater than that of the vector
9919     // element reject it.
9920     return (IntSigned != OtherIntSigned &&
9921             NumBits > S.Context.getIntWidth(OtherIntTy));
9922   }
9923 
9924   // Reject cases where the value of the scalar is not constant and it's
9925   // order is greater than that of the vector element type.
9926   return (Order < 0);
9927 }
9928 
9929 /// Test if a (constant) integer Int can be casted to floating point type
9930 /// FloatTy without losing precision.
9931 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9932                                      QualType FloatTy) {
9933   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9934 
9935   // Determine if the integer constant can be expressed as a floating point
9936   // number of the appropriate type.
9937   Expr::EvalResult EVResult;
9938   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9939 
9940   uint64_t Bits = 0;
9941   if (CstInt) {
9942     // Reject constants that would be truncated if they were converted to
9943     // the floating point type. Test by simple to/from conversion.
9944     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9945     //        could be avoided if there was a convertFromAPInt method
9946     //        which could signal back if implicit truncation occurred.
9947     llvm::APSInt Result = EVResult.Val.getInt();
9948     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9949     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9950                            llvm::APFloat::rmTowardZero);
9951     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9952                              !IntTy->hasSignedIntegerRepresentation());
9953     bool Ignored = false;
9954     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9955                            &Ignored);
9956     if (Result != ConvertBack)
9957       return true;
9958   } else {
9959     // Reject types that cannot be fully encoded into the mantissa of
9960     // the float.
9961     Bits = S.Context.getTypeSize(IntTy);
9962     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9963         S.Context.getFloatTypeSemantics(FloatTy));
9964     if (Bits > FloatPrec)
9965       return true;
9966   }
9967 
9968   return false;
9969 }
9970 
9971 /// Attempt to convert and splat Scalar into a vector whose types matches
9972 /// Vector following GCC conversion rules. The rule is that implicit
9973 /// conversion can occur when Scalar can be casted to match Vector's element
9974 /// type without causing truncation of Scalar.
9975 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9976                                         ExprResult *Vector) {
9977   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9978   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9979   const VectorType *VT = VectorTy->getAs<VectorType>();
9980 
9981   assert(!isa<ExtVectorType>(VT) &&
9982          "ExtVectorTypes should not be handled here!");
9983 
9984   QualType VectorEltTy = VT->getElementType();
9985 
9986   // Reject cases where the vector element type or the scalar element type are
9987   // not integral or floating point types.
9988   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9989     return true;
9990 
9991   // The conversion to apply to the scalar before splatting it,
9992   // if necessary.
9993   CastKind ScalarCast = CK_NoOp;
9994 
9995   // Accept cases where the vector elements are integers and the scalar is
9996   // an integer.
9997   // FIXME: Notionally if the scalar was a floating point value with a precise
9998   //        integral representation, we could cast it to an appropriate integer
9999   //        type and then perform the rest of the checks here. GCC will perform
10000   //        this conversion in some cases as determined by the input language.
10001   //        We should accept it on a language independent basis.
10002   if (VectorEltTy->isIntegralType(S.Context) &&
10003       ScalarTy->isIntegralType(S.Context) &&
10004       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10005 
10006     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10007       return true;
10008 
10009     ScalarCast = CK_IntegralCast;
10010   } else if (VectorEltTy->isIntegralType(S.Context) &&
10011              ScalarTy->isRealFloatingType()) {
10012     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10013       ScalarCast = CK_FloatingToIntegral;
10014     else
10015       return true;
10016   } else if (VectorEltTy->isRealFloatingType()) {
10017     if (ScalarTy->isRealFloatingType()) {
10018 
10019       // Reject cases where the scalar type is not a constant and has a higher
10020       // Order than the vector element type.
10021       llvm::APFloat Result(0.0);
10022 
10023       // Determine whether this is a constant scalar. In the event that the
10024       // value is dependent (and thus cannot be evaluated by the constant
10025       // evaluator), skip the evaluation. This will then diagnose once the
10026       // expression is instantiated.
10027       bool CstScalar = Scalar->get()->isValueDependent() ||
10028                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
10029       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10030       if (!CstScalar && Order < 0)
10031         return true;
10032 
10033       // If the scalar cannot be safely casted to the vector element type,
10034       // reject it.
10035       if (CstScalar) {
10036         bool Truncated = false;
10037         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10038                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
10039         if (Truncated)
10040           return true;
10041       }
10042 
10043       ScalarCast = CK_FloatingCast;
10044     } else if (ScalarTy->isIntegralType(S.Context)) {
10045       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10046         return true;
10047 
10048       ScalarCast = CK_IntegralToFloating;
10049     } else
10050       return true;
10051   } else if (ScalarTy->isEnumeralType())
10052     return true;
10053 
10054   // Adjust scalar if desired.
10055   if (Scalar) {
10056     if (ScalarCast != CK_NoOp)
10057       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10058     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10059   }
10060   return false;
10061 }
10062 
10063 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10064                                    SourceLocation Loc, bool IsCompAssign,
10065                                    bool AllowBothBool,
10066                                    bool AllowBoolConversions) {
10067   if (!IsCompAssign) {
10068     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10069     if (LHS.isInvalid())
10070       return QualType();
10071   }
10072   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10073   if (RHS.isInvalid())
10074     return QualType();
10075 
10076   // For conversion purposes, we ignore any qualifiers.
10077   // For example, "const float" and "float" are equivalent.
10078   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10079   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10080 
10081   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10082   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10083   assert(LHSVecType || RHSVecType);
10084 
10085   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10086       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10087     return InvalidOperands(Loc, LHS, RHS);
10088 
10089   // AltiVec-style "vector bool op vector bool" combinations are allowed
10090   // for some operators but not others.
10091   if (!AllowBothBool &&
10092       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10093       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10094     return InvalidOperands(Loc, LHS, RHS);
10095 
10096   // If the vector types are identical, return.
10097   if (Context.hasSameType(LHSType, RHSType))
10098     return LHSType;
10099 
10100   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10101   if (LHSVecType && RHSVecType &&
10102       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10103     if (isa<ExtVectorType>(LHSVecType)) {
10104       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10105       return LHSType;
10106     }
10107 
10108     if (!IsCompAssign)
10109       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10110     return RHSType;
10111   }
10112 
10113   // AllowBoolConversions says that bool and non-bool AltiVec vectors
10114   // can be mixed, with the result being the non-bool type.  The non-bool
10115   // operand must have integer element type.
10116   if (AllowBoolConversions && LHSVecType && RHSVecType &&
10117       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10118       (Context.getTypeSize(LHSVecType->getElementType()) ==
10119        Context.getTypeSize(RHSVecType->getElementType()))) {
10120     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10121         LHSVecType->getElementType()->isIntegerType() &&
10122         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10123       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10124       return LHSType;
10125     }
10126     if (!IsCompAssign &&
10127         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10128         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10129         RHSVecType->getElementType()->isIntegerType()) {
10130       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10131       return RHSType;
10132     }
10133   }
10134 
10135   // Expressions containing fixed-length and sizeless SVE vectors are invalid
10136   // since the ambiguity can affect the ABI.
10137   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10138     const VectorType *VecType = SecondType->getAs<VectorType>();
10139     return FirstType->isSizelessBuiltinType() && VecType &&
10140            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10141             VecType->getVectorKind() ==
10142                 VectorType::SveFixedLengthPredicateVector);
10143   };
10144 
10145   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10146     Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10147     return QualType();
10148   }
10149 
10150   // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10151   // since the ambiguity can affect the ABI.
10152   auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10153     const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10154     const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10155 
10156     if (FirstVecType && SecondVecType)
10157       return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10158              (SecondVecType->getVectorKind() ==
10159                   VectorType::SveFixedLengthDataVector ||
10160               SecondVecType->getVectorKind() ==
10161                   VectorType::SveFixedLengthPredicateVector);
10162 
10163     return FirstType->isSizelessBuiltinType() && SecondVecType &&
10164            SecondVecType->getVectorKind() == VectorType::GenericVector;
10165   };
10166 
10167   if (IsSveGnuConversion(LHSType, RHSType) ||
10168       IsSveGnuConversion(RHSType, LHSType)) {
10169     Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10170     return QualType();
10171   }
10172 
10173   // If there's a vector type and a scalar, try to convert the scalar to
10174   // the vector element type and splat.
10175   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10176   if (!RHSVecType) {
10177     if (isa<ExtVectorType>(LHSVecType)) {
10178       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10179                                     LHSVecType->getElementType(), LHSType,
10180                                     DiagID))
10181         return LHSType;
10182     } else {
10183       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10184         return LHSType;
10185     }
10186   }
10187   if (!LHSVecType) {
10188     if (isa<ExtVectorType>(RHSVecType)) {
10189       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10190                                     LHSType, RHSVecType->getElementType(),
10191                                     RHSType, DiagID))
10192         return RHSType;
10193     } else {
10194       if (LHS.get()->isLValue() ||
10195           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10196         return RHSType;
10197     }
10198   }
10199 
10200   // FIXME: The code below also handles conversion between vectors and
10201   // non-scalars, we should break this down into fine grained specific checks
10202   // and emit proper diagnostics.
10203   QualType VecType = LHSVecType ? LHSType : RHSType;
10204   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10205   QualType OtherType = LHSVecType ? RHSType : LHSType;
10206   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10207   if (isLaxVectorConversion(OtherType, VecType)) {
10208     // If we're allowing lax vector conversions, only the total (data) size
10209     // needs to be the same. For non compound assignment, if one of the types is
10210     // scalar, the result is always the vector type.
10211     if (!IsCompAssign) {
10212       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10213       return VecType;
10214     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10215     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10216     // type. Note that this is already done by non-compound assignments in
10217     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10218     // <1 x T> -> T. The result is also a vector type.
10219     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10220                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10221       ExprResult *RHSExpr = &RHS;
10222       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10223       return VecType;
10224     }
10225   }
10226 
10227   // Okay, the expression is invalid.
10228 
10229   // If there's a non-vector, non-real operand, diagnose that.
10230   if ((!RHSVecType && !RHSType->isRealType()) ||
10231       (!LHSVecType && !LHSType->isRealType())) {
10232     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10233       << LHSType << RHSType
10234       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10235     return QualType();
10236   }
10237 
10238   // OpenCL V1.1 6.2.6.p1:
10239   // If the operands are of more than one vector type, then an error shall
10240   // occur. Implicit conversions between vector types are not permitted, per
10241   // section 6.2.1.
10242   if (getLangOpts().OpenCL &&
10243       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10244       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10245     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10246                                                            << RHSType;
10247     return QualType();
10248   }
10249 
10250 
10251   // If there is a vector type that is not a ExtVector and a scalar, we reach
10252   // this point if scalar could not be converted to the vector's element type
10253   // without truncation.
10254   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10255       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10256     QualType Scalar = LHSVecType ? RHSType : LHSType;
10257     QualType Vector = LHSVecType ? LHSType : RHSType;
10258     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10259     Diag(Loc,
10260          diag::err_typecheck_vector_not_convertable_implict_truncation)
10261         << ScalarOrVector << Scalar << Vector;
10262 
10263     return QualType();
10264   }
10265 
10266   // Otherwise, use the generic diagnostic.
10267   Diag(Loc, DiagID)
10268     << LHSType << RHSType
10269     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10270   return QualType();
10271 }
10272 
10273 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10274 // expression.  These are mainly cases where the null pointer is used as an
10275 // integer instead of a pointer.
10276 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10277                                 SourceLocation Loc, bool IsCompare) {
10278   // The canonical way to check for a GNU null is with isNullPointerConstant,
10279   // but we use a bit of a hack here for speed; this is a relatively
10280   // hot path, and isNullPointerConstant is slow.
10281   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10282   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10283 
10284   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10285 
10286   // Avoid analyzing cases where the result will either be invalid (and
10287   // diagnosed as such) or entirely valid and not something to warn about.
10288   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10289       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10290     return;
10291 
10292   // Comparison operations would not make sense with a null pointer no matter
10293   // what the other expression is.
10294   if (!IsCompare) {
10295     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10296         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10297         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10298     return;
10299   }
10300 
10301   // The rest of the operations only make sense with a null pointer
10302   // if the other expression is a pointer.
10303   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10304       NonNullType->canDecayToPointerType())
10305     return;
10306 
10307   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10308       << LHSNull /* LHS is NULL */ << NonNullType
10309       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10310 }
10311 
10312 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10313                                           SourceLocation Loc) {
10314   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10315   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10316   if (!LUE || !RUE)
10317     return;
10318   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10319       RUE->getKind() != UETT_SizeOf)
10320     return;
10321 
10322   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10323   QualType LHSTy = LHSArg->getType();
10324   QualType RHSTy;
10325 
10326   if (RUE->isArgumentType())
10327     RHSTy = RUE->getArgumentType().getNonReferenceType();
10328   else
10329     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10330 
10331   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10332     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10333       return;
10334 
10335     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10336     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10337       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10338         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10339             << LHSArgDecl;
10340     }
10341   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10342     QualType ArrayElemTy = ArrayTy->getElementType();
10343     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10344         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10345         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10346         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10347       return;
10348     S.Diag(Loc, diag::warn_division_sizeof_array)
10349         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10350     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10351       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10352         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10353             << LHSArgDecl;
10354     }
10355 
10356     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10357   }
10358 }
10359 
10360 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10361                                                ExprResult &RHS,
10362                                                SourceLocation Loc, bool IsDiv) {
10363   // Check for division/remainder by zero.
10364   Expr::EvalResult RHSValue;
10365   if (!RHS.get()->isValueDependent() &&
10366       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10367       RHSValue.Val.getInt() == 0)
10368     S.DiagRuntimeBehavior(Loc, RHS.get(),
10369                           S.PDiag(diag::warn_remainder_division_by_zero)
10370                             << IsDiv << RHS.get()->getSourceRange());
10371 }
10372 
10373 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10374                                            SourceLocation Loc,
10375                                            bool IsCompAssign, bool IsDiv) {
10376   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10377 
10378   QualType LHSTy = LHS.get()->getType();
10379   QualType RHSTy = RHS.get()->getType();
10380   if (LHSTy->isVectorType() || RHSTy->isVectorType())
10381     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10382                                /*AllowBothBool*/getLangOpts().AltiVec,
10383                                /*AllowBoolConversions*/false);
10384   if (!IsDiv &&
10385       (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10386     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10387   // For division, only matrix-by-scalar is supported. Other combinations with
10388   // matrix types are invalid.
10389   if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10390     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10391 
10392   QualType compType = UsualArithmeticConversions(
10393       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10394   if (LHS.isInvalid() || RHS.isInvalid())
10395     return QualType();
10396 
10397 
10398   if (compType.isNull() || !compType->isArithmeticType())
10399     return InvalidOperands(Loc, LHS, RHS);
10400   if (IsDiv) {
10401     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10402     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10403   }
10404   return compType;
10405 }
10406 
10407 QualType Sema::CheckRemainderOperands(
10408   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10409   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10410 
10411   if (LHS.get()->getType()->isVectorType() ||
10412       RHS.get()->getType()->isVectorType()) {
10413     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10414         RHS.get()->getType()->hasIntegerRepresentation())
10415       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10416                                  /*AllowBothBool*/getLangOpts().AltiVec,
10417                                  /*AllowBoolConversions*/false);
10418     return InvalidOperands(Loc, LHS, RHS);
10419   }
10420 
10421   QualType compType = UsualArithmeticConversions(
10422       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10423   if (LHS.isInvalid() || RHS.isInvalid())
10424     return QualType();
10425 
10426   if (compType.isNull() || !compType->isIntegerType())
10427     return InvalidOperands(Loc, LHS, RHS);
10428   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10429   return compType;
10430 }
10431 
10432 /// Diagnose invalid arithmetic on two void pointers.
10433 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10434                                                 Expr *LHSExpr, Expr *RHSExpr) {
10435   S.Diag(Loc, S.getLangOpts().CPlusPlus
10436                 ? diag::err_typecheck_pointer_arith_void_type
10437                 : diag::ext_gnu_void_ptr)
10438     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10439                             << RHSExpr->getSourceRange();
10440 }
10441 
10442 /// Diagnose invalid arithmetic on a void pointer.
10443 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10444                                             Expr *Pointer) {
10445   S.Diag(Loc, S.getLangOpts().CPlusPlus
10446                 ? diag::err_typecheck_pointer_arith_void_type
10447                 : diag::ext_gnu_void_ptr)
10448     << 0 /* one pointer */ << Pointer->getSourceRange();
10449 }
10450 
10451 /// Diagnose invalid arithmetic on a null pointer.
10452 ///
10453 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10454 /// idiom, which we recognize as a GNU extension.
10455 ///
10456 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10457                                             Expr *Pointer, bool IsGNUIdiom) {
10458   if (IsGNUIdiom)
10459     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10460       << Pointer->getSourceRange();
10461   else
10462     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10463       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10464 }
10465 
10466 /// Diagnose invalid subraction on a null pointer.
10467 ///
10468 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10469                                              Expr *Pointer, bool BothNull) {
10470   // Null - null is valid in C++ [expr.add]p7
10471   if (BothNull && S.getLangOpts().CPlusPlus)
10472     return;
10473 
10474   // Is this s a macro from a system header?
10475   if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10476     return;
10477 
10478   S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
10479       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10480 }
10481 
10482 /// Diagnose invalid arithmetic on two function pointers.
10483 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10484                                                     Expr *LHS, Expr *RHS) {
10485   assert(LHS->getType()->isAnyPointerType());
10486   assert(RHS->getType()->isAnyPointerType());
10487   S.Diag(Loc, S.getLangOpts().CPlusPlus
10488                 ? diag::err_typecheck_pointer_arith_function_type
10489                 : diag::ext_gnu_ptr_func_arith)
10490     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10491     // We only show the second type if it differs from the first.
10492     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10493                                                    RHS->getType())
10494     << RHS->getType()->getPointeeType()
10495     << LHS->getSourceRange() << RHS->getSourceRange();
10496 }
10497 
10498 /// Diagnose invalid arithmetic on a function pointer.
10499 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10500                                                 Expr *Pointer) {
10501   assert(Pointer->getType()->isAnyPointerType());
10502   S.Diag(Loc, S.getLangOpts().CPlusPlus
10503                 ? diag::err_typecheck_pointer_arith_function_type
10504                 : diag::ext_gnu_ptr_func_arith)
10505     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10506     << 0 /* one pointer, so only one type */
10507     << Pointer->getSourceRange();
10508 }
10509 
10510 /// Emit error if Operand is incomplete pointer type
10511 ///
10512 /// \returns True if pointer has incomplete type
10513 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10514                                                  Expr *Operand) {
10515   QualType ResType = Operand->getType();
10516   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10517     ResType = ResAtomicType->getValueType();
10518 
10519   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10520   QualType PointeeTy = ResType->getPointeeType();
10521   return S.RequireCompleteSizedType(
10522       Loc, PointeeTy,
10523       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10524       Operand->getSourceRange());
10525 }
10526 
10527 /// Check the validity of an arithmetic pointer operand.
10528 ///
10529 /// If the operand has pointer type, this code will check for pointer types
10530 /// which are invalid in arithmetic operations. These will be diagnosed
10531 /// appropriately, including whether or not the use is supported as an
10532 /// extension.
10533 ///
10534 /// \returns True when the operand is valid to use (even if as an extension).
10535 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10536                                             Expr *Operand) {
10537   QualType ResType = Operand->getType();
10538   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10539     ResType = ResAtomicType->getValueType();
10540 
10541   if (!ResType->isAnyPointerType()) return true;
10542 
10543   QualType PointeeTy = ResType->getPointeeType();
10544   if (PointeeTy->isVoidType()) {
10545     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10546     return !S.getLangOpts().CPlusPlus;
10547   }
10548   if (PointeeTy->isFunctionType()) {
10549     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10550     return !S.getLangOpts().CPlusPlus;
10551   }
10552 
10553   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10554 
10555   return true;
10556 }
10557 
10558 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10559 /// operands.
10560 ///
10561 /// This routine will diagnose any invalid arithmetic on pointer operands much
10562 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10563 /// for emitting a single diagnostic even for operations where both LHS and RHS
10564 /// are (potentially problematic) pointers.
10565 ///
10566 /// \returns True when the operand is valid to use (even if as an extension).
10567 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10568                                                 Expr *LHSExpr, Expr *RHSExpr) {
10569   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10570   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10571   if (!isLHSPointer && !isRHSPointer) return true;
10572 
10573   QualType LHSPointeeTy, RHSPointeeTy;
10574   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10575   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10576 
10577   // if both are pointers check if operation is valid wrt address spaces
10578   if (isLHSPointer && isRHSPointer) {
10579     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10580       S.Diag(Loc,
10581              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10582           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10583           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10584       return false;
10585     }
10586   }
10587 
10588   // Check for arithmetic on pointers to incomplete types.
10589   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10590   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10591   if (isLHSVoidPtr || isRHSVoidPtr) {
10592     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10593     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10594     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10595 
10596     return !S.getLangOpts().CPlusPlus;
10597   }
10598 
10599   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10600   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10601   if (isLHSFuncPtr || isRHSFuncPtr) {
10602     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10603     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10604                                                                 RHSExpr);
10605     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10606 
10607     return !S.getLangOpts().CPlusPlus;
10608   }
10609 
10610   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10611     return false;
10612   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10613     return false;
10614 
10615   return true;
10616 }
10617 
10618 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10619 /// literal.
10620 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10621                                   Expr *LHSExpr, Expr *RHSExpr) {
10622   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10623   Expr* IndexExpr = RHSExpr;
10624   if (!StrExpr) {
10625     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10626     IndexExpr = LHSExpr;
10627   }
10628 
10629   bool IsStringPlusInt = StrExpr &&
10630       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10631   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10632     return;
10633 
10634   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10635   Self.Diag(OpLoc, diag::warn_string_plus_int)
10636       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10637 
10638   // Only print a fixit for "str" + int, not for int + "str".
10639   if (IndexExpr == RHSExpr) {
10640     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10641     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10642         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10643         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10644         << FixItHint::CreateInsertion(EndLoc, "]");
10645   } else
10646     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10647 }
10648 
10649 /// Emit a warning when adding a char literal to a string.
10650 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10651                                    Expr *LHSExpr, Expr *RHSExpr) {
10652   const Expr *StringRefExpr = LHSExpr;
10653   const CharacterLiteral *CharExpr =
10654       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10655 
10656   if (!CharExpr) {
10657     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10658     StringRefExpr = RHSExpr;
10659   }
10660 
10661   if (!CharExpr || !StringRefExpr)
10662     return;
10663 
10664   const QualType StringType = StringRefExpr->getType();
10665 
10666   // Return if not a PointerType.
10667   if (!StringType->isAnyPointerType())
10668     return;
10669 
10670   // Return if not a CharacterType.
10671   if (!StringType->getPointeeType()->isAnyCharacterType())
10672     return;
10673 
10674   ASTContext &Ctx = Self.getASTContext();
10675   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10676 
10677   const QualType CharType = CharExpr->getType();
10678   if (!CharType->isAnyCharacterType() &&
10679       CharType->isIntegerType() &&
10680       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10681     Self.Diag(OpLoc, diag::warn_string_plus_char)
10682         << DiagRange << Ctx.CharTy;
10683   } else {
10684     Self.Diag(OpLoc, diag::warn_string_plus_char)
10685         << DiagRange << CharExpr->getType();
10686   }
10687 
10688   // Only print a fixit for str + char, not for char + str.
10689   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10690     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10691     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10692         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10693         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10694         << FixItHint::CreateInsertion(EndLoc, "]");
10695   } else {
10696     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10697   }
10698 }
10699 
10700 /// Emit error when two pointers are incompatible.
10701 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10702                                            Expr *LHSExpr, Expr *RHSExpr) {
10703   assert(LHSExpr->getType()->isAnyPointerType());
10704   assert(RHSExpr->getType()->isAnyPointerType());
10705   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10706     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10707     << RHSExpr->getSourceRange();
10708 }
10709 
10710 // C99 6.5.6
10711 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10712                                      SourceLocation Loc, BinaryOperatorKind Opc,
10713                                      QualType* CompLHSTy) {
10714   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10715 
10716   if (LHS.get()->getType()->isVectorType() ||
10717       RHS.get()->getType()->isVectorType()) {
10718     QualType compType = CheckVectorOperands(
10719         LHS, RHS, Loc, CompLHSTy,
10720         /*AllowBothBool*/getLangOpts().AltiVec,
10721         /*AllowBoolConversions*/getLangOpts().ZVector);
10722     if (CompLHSTy) *CompLHSTy = compType;
10723     return compType;
10724   }
10725 
10726   if (LHS.get()->getType()->isConstantMatrixType() ||
10727       RHS.get()->getType()->isConstantMatrixType()) {
10728     QualType compType =
10729         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10730     if (CompLHSTy)
10731       *CompLHSTy = compType;
10732     return compType;
10733   }
10734 
10735   QualType compType = UsualArithmeticConversions(
10736       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10737   if (LHS.isInvalid() || RHS.isInvalid())
10738     return QualType();
10739 
10740   // Diagnose "string literal" '+' int and string '+' "char literal".
10741   if (Opc == BO_Add) {
10742     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10743     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10744   }
10745 
10746   // handle the common case first (both operands are arithmetic).
10747   if (!compType.isNull() && compType->isArithmeticType()) {
10748     if (CompLHSTy) *CompLHSTy = compType;
10749     return compType;
10750   }
10751 
10752   // Type-checking.  Ultimately the pointer's going to be in PExp;
10753   // note that we bias towards the LHS being the pointer.
10754   Expr *PExp = LHS.get(), *IExp = RHS.get();
10755 
10756   bool isObjCPointer;
10757   if (PExp->getType()->isPointerType()) {
10758     isObjCPointer = false;
10759   } else if (PExp->getType()->isObjCObjectPointerType()) {
10760     isObjCPointer = true;
10761   } else {
10762     std::swap(PExp, IExp);
10763     if (PExp->getType()->isPointerType()) {
10764       isObjCPointer = false;
10765     } else if (PExp->getType()->isObjCObjectPointerType()) {
10766       isObjCPointer = true;
10767     } else {
10768       return InvalidOperands(Loc, LHS, RHS);
10769     }
10770   }
10771   assert(PExp->getType()->isAnyPointerType());
10772 
10773   if (!IExp->getType()->isIntegerType())
10774     return InvalidOperands(Loc, LHS, RHS);
10775 
10776   // Adding to a null pointer results in undefined behavior.
10777   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10778           Context, Expr::NPC_ValueDependentIsNotNull)) {
10779     // In C++ adding zero to a null pointer is defined.
10780     Expr::EvalResult KnownVal;
10781     if (!getLangOpts().CPlusPlus ||
10782         (!IExp->isValueDependent() &&
10783          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10784           KnownVal.Val.getInt() != 0))) {
10785       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10786       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10787           Context, BO_Add, PExp, IExp);
10788       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10789     }
10790   }
10791 
10792   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10793     return QualType();
10794 
10795   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10796     return QualType();
10797 
10798   // Check array bounds for pointer arithemtic
10799   CheckArrayAccess(PExp, IExp);
10800 
10801   if (CompLHSTy) {
10802     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10803     if (LHSTy.isNull()) {
10804       LHSTy = LHS.get()->getType();
10805       if (LHSTy->isPromotableIntegerType())
10806         LHSTy = Context.getPromotedIntegerType(LHSTy);
10807     }
10808     *CompLHSTy = LHSTy;
10809   }
10810 
10811   return PExp->getType();
10812 }
10813 
10814 // C99 6.5.6
10815 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10816                                         SourceLocation Loc,
10817                                         QualType* CompLHSTy) {
10818   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10819 
10820   if (LHS.get()->getType()->isVectorType() ||
10821       RHS.get()->getType()->isVectorType()) {
10822     QualType compType = CheckVectorOperands(
10823         LHS, RHS, Loc, CompLHSTy,
10824         /*AllowBothBool*/getLangOpts().AltiVec,
10825         /*AllowBoolConversions*/getLangOpts().ZVector);
10826     if (CompLHSTy) *CompLHSTy = compType;
10827     return compType;
10828   }
10829 
10830   if (LHS.get()->getType()->isConstantMatrixType() ||
10831       RHS.get()->getType()->isConstantMatrixType()) {
10832     QualType compType =
10833         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10834     if (CompLHSTy)
10835       *CompLHSTy = compType;
10836     return compType;
10837   }
10838 
10839   QualType compType = UsualArithmeticConversions(
10840       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10841   if (LHS.isInvalid() || RHS.isInvalid())
10842     return QualType();
10843 
10844   // Enforce type constraints: C99 6.5.6p3.
10845 
10846   // Handle the common case first (both operands are arithmetic).
10847   if (!compType.isNull() && compType->isArithmeticType()) {
10848     if (CompLHSTy) *CompLHSTy = compType;
10849     return compType;
10850   }
10851 
10852   // Either ptr - int   or   ptr - ptr.
10853   if (LHS.get()->getType()->isAnyPointerType()) {
10854     QualType lpointee = LHS.get()->getType()->getPointeeType();
10855 
10856     // Diagnose bad cases where we step over interface counts.
10857     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10858         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10859       return QualType();
10860 
10861     // The result type of a pointer-int computation is the pointer type.
10862     if (RHS.get()->getType()->isIntegerType()) {
10863       // Subtracting from a null pointer should produce a warning.
10864       // The last argument to the diagnose call says this doesn't match the
10865       // GNU int-to-pointer idiom.
10866       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10867                                            Expr::NPC_ValueDependentIsNotNull)) {
10868         // In C++ adding zero to a null pointer is defined.
10869         Expr::EvalResult KnownVal;
10870         if (!getLangOpts().CPlusPlus ||
10871             (!RHS.get()->isValueDependent() &&
10872              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10873               KnownVal.Val.getInt() != 0))) {
10874           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10875         }
10876       }
10877 
10878       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10879         return QualType();
10880 
10881       // Check array bounds for pointer arithemtic
10882       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10883                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10884 
10885       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10886       return LHS.get()->getType();
10887     }
10888 
10889     // Handle pointer-pointer subtractions.
10890     if (const PointerType *RHSPTy
10891           = RHS.get()->getType()->getAs<PointerType>()) {
10892       QualType rpointee = RHSPTy->getPointeeType();
10893 
10894       if (getLangOpts().CPlusPlus) {
10895         // Pointee types must be the same: C++ [expr.add]
10896         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10897           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10898         }
10899       } else {
10900         // Pointee types must be compatible C99 6.5.6p3
10901         if (!Context.typesAreCompatible(
10902                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10903                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10904           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10905           return QualType();
10906         }
10907       }
10908 
10909       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10910                                                LHS.get(), RHS.get()))
10911         return QualType();
10912 
10913       bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
10914           Context, Expr::NPC_ValueDependentIsNotNull);
10915       bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
10916           Context, Expr::NPC_ValueDependentIsNotNull);
10917 
10918       // Subtracting nullptr or from nullptr is suspect
10919       if (LHSIsNullPtr)
10920         diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
10921       if (RHSIsNullPtr)
10922         diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
10923 
10924       // The pointee type may have zero size.  As an extension, a structure or
10925       // union may have zero size or an array may have zero length.  In this
10926       // case subtraction does not make sense.
10927       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10928         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10929         if (ElementSize.isZero()) {
10930           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10931             << rpointee.getUnqualifiedType()
10932             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10933         }
10934       }
10935 
10936       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10937       return Context.getPointerDiffType();
10938     }
10939   }
10940 
10941   return InvalidOperands(Loc, LHS, RHS);
10942 }
10943 
10944 static bool isScopedEnumerationType(QualType T) {
10945   if (const EnumType *ET = T->getAs<EnumType>())
10946     return ET->getDecl()->isScoped();
10947   return false;
10948 }
10949 
10950 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10951                                    SourceLocation Loc, BinaryOperatorKind Opc,
10952                                    QualType LHSType) {
10953   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10954   // so skip remaining warnings as we don't want to modify values within Sema.
10955   if (S.getLangOpts().OpenCL)
10956     return;
10957 
10958   // Check right/shifter operand
10959   Expr::EvalResult RHSResult;
10960   if (RHS.get()->isValueDependent() ||
10961       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10962     return;
10963   llvm::APSInt Right = RHSResult.Val.getInt();
10964 
10965   if (Right.isNegative()) {
10966     S.DiagRuntimeBehavior(Loc, RHS.get(),
10967                           S.PDiag(diag::warn_shift_negative)
10968                             << RHS.get()->getSourceRange());
10969     return;
10970   }
10971 
10972   QualType LHSExprType = LHS.get()->getType();
10973   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
10974   if (LHSExprType->isExtIntType())
10975     LeftSize = S.Context.getIntWidth(LHSExprType);
10976   else if (LHSExprType->isFixedPointType()) {
10977     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
10978     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
10979   }
10980   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10981   if (Right.uge(LeftBits)) {
10982     S.DiagRuntimeBehavior(Loc, RHS.get(),
10983                           S.PDiag(diag::warn_shift_gt_typewidth)
10984                             << RHS.get()->getSourceRange());
10985     return;
10986   }
10987 
10988   // FIXME: We probably need to handle fixed point types specially here.
10989   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
10990     return;
10991 
10992   // When left shifting an ICE which is signed, we can check for overflow which
10993   // according to C++ standards prior to C++2a has undefined behavior
10994   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10995   // more than the maximum value representable in the result type, so never
10996   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10997   // expression is still probably a bug.)
10998   Expr::EvalResult LHSResult;
10999   if (LHS.get()->isValueDependent() ||
11000       LHSType->hasUnsignedIntegerRepresentation() ||
11001       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11002     return;
11003   llvm::APSInt Left = LHSResult.Val.getInt();
11004 
11005   // If LHS does not have a signed type and non-negative value
11006   // then, the behavior is undefined before C++2a. Warn about it.
11007   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
11008       !S.getLangOpts().CPlusPlus20) {
11009     S.DiagRuntimeBehavior(Loc, LHS.get(),
11010                           S.PDiag(diag::warn_shift_lhs_negative)
11011                             << LHS.get()->getSourceRange());
11012     return;
11013   }
11014 
11015   llvm::APInt ResultBits =
11016       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
11017   if (LeftBits.uge(ResultBits))
11018     return;
11019   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11020   Result = Result.shl(Right);
11021 
11022   // Print the bit representation of the signed integer as an unsigned
11023   // hexadecimal number.
11024   SmallString<40> HexResult;
11025   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11026 
11027   // If we are only missing a sign bit, this is less likely to result in actual
11028   // bugs -- if the result is cast back to an unsigned type, it will have the
11029   // expected value. Thus we place this behind a different warning that can be
11030   // turned off separately if needed.
11031   if (LeftBits == ResultBits - 1) {
11032     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11033         << HexResult << LHSType
11034         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11035     return;
11036   }
11037 
11038   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11039     << HexResult.str() << Result.getMinSignedBits() << LHSType
11040     << Left.getBitWidth() << LHS.get()->getSourceRange()
11041     << RHS.get()->getSourceRange();
11042 }
11043 
11044 /// Return the resulting type when a vector is shifted
11045 ///        by a scalar or vector shift amount.
11046 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11047                                  SourceLocation Loc, bool IsCompAssign) {
11048   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11049   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11050       !LHS.get()->getType()->isVectorType()) {
11051     S.Diag(Loc, diag::err_shift_rhs_only_vector)
11052       << RHS.get()->getType() << LHS.get()->getType()
11053       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11054     return QualType();
11055   }
11056 
11057   if (!IsCompAssign) {
11058     LHS = S.UsualUnaryConversions(LHS.get());
11059     if (LHS.isInvalid()) return QualType();
11060   }
11061 
11062   RHS = S.UsualUnaryConversions(RHS.get());
11063   if (RHS.isInvalid()) return QualType();
11064 
11065   QualType LHSType = LHS.get()->getType();
11066   // Note that LHS might be a scalar because the routine calls not only in
11067   // OpenCL case.
11068   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11069   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11070 
11071   // Note that RHS might not be a vector.
11072   QualType RHSType = RHS.get()->getType();
11073   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11074   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11075 
11076   // The operands need to be integers.
11077   if (!LHSEleType->isIntegerType()) {
11078     S.Diag(Loc, diag::err_typecheck_expect_int)
11079       << LHS.get()->getType() << LHS.get()->getSourceRange();
11080     return QualType();
11081   }
11082 
11083   if (!RHSEleType->isIntegerType()) {
11084     S.Diag(Loc, diag::err_typecheck_expect_int)
11085       << RHS.get()->getType() << RHS.get()->getSourceRange();
11086     return QualType();
11087   }
11088 
11089   if (!LHSVecTy) {
11090     assert(RHSVecTy);
11091     if (IsCompAssign)
11092       return RHSType;
11093     if (LHSEleType != RHSEleType) {
11094       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11095       LHSEleType = RHSEleType;
11096     }
11097     QualType VecTy =
11098         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11099     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11100     LHSType = VecTy;
11101   } else if (RHSVecTy) {
11102     // OpenCL v1.1 s6.3.j says that for vector types, the operators
11103     // are applied component-wise. So if RHS is a vector, then ensure
11104     // that the number of elements is the same as LHS...
11105     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11106       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11107         << LHS.get()->getType() << RHS.get()->getType()
11108         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11109       return QualType();
11110     }
11111     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11112       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11113       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11114       if (LHSBT != RHSBT &&
11115           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11116         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11117             << LHS.get()->getType() << RHS.get()->getType()
11118             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11119       }
11120     }
11121   } else {
11122     // ...else expand RHS to match the number of elements in LHS.
11123     QualType VecTy =
11124       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11125     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11126   }
11127 
11128   return LHSType;
11129 }
11130 
11131 // C99 6.5.7
11132 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11133                                   SourceLocation Loc, BinaryOperatorKind Opc,
11134                                   bool IsCompAssign) {
11135   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11136 
11137   // Vector shifts promote their scalar inputs to vector type.
11138   if (LHS.get()->getType()->isVectorType() ||
11139       RHS.get()->getType()->isVectorType()) {
11140     if (LangOpts.ZVector) {
11141       // The shift operators for the z vector extensions work basically
11142       // like general shifts, except that neither the LHS nor the RHS is
11143       // allowed to be a "vector bool".
11144       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11145         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11146           return InvalidOperands(Loc, LHS, RHS);
11147       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11148         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11149           return InvalidOperands(Loc, LHS, RHS);
11150     }
11151     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11152   }
11153 
11154   // Shifts don't perform usual arithmetic conversions, they just do integer
11155   // promotions on each operand. C99 6.5.7p3
11156 
11157   // For the LHS, do usual unary conversions, but then reset them away
11158   // if this is a compound assignment.
11159   ExprResult OldLHS = LHS;
11160   LHS = UsualUnaryConversions(LHS.get());
11161   if (LHS.isInvalid())
11162     return QualType();
11163   QualType LHSType = LHS.get()->getType();
11164   if (IsCompAssign) LHS = OldLHS;
11165 
11166   // The RHS is simpler.
11167   RHS = UsualUnaryConversions(RHS.get());
11168   if (RHS.isInvalid())
11169     return QualType();
11170   QualType RHSType = RHS.get()->getType();
11171 
11172   // C99 6.5.7p2: Each of the operands shall have integer type.
11173   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11174   if ((!LHSType->isFixedPointOrIntegerType() &&
11175        !LHSType->hasIntegerRepresentation()) ||
11176       !RHSType->hasIntegerRepresentation())
11177     return InvalidOperands(Loc, LHS, RHS);
11178 
11179   // C++0x: Don't allow scoped enums. FIXME: Use something better than
11180   // hasIntegerRepresentation() above instead of this.
11181   if (isScopedEnumerationType(LHSType) ||
11182       isScopedEnumerationType(RHSType)) {
11183     return InvalidOperands(Loc, LHS, RHS);
11184   }
11185   // Sanity-check shift operands
11186   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11187 
11188   // "The type of the result is that of the promoted left operand."
11189   return LHSType;
11190 }
11191 
11192 /// Diagnose bad pointer comparisons.
11193 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11194                                               ExprResult &LHS, ExprResult &RHS,
11195                                               bool IsError) {
11196   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11197                       : diag::ext_typecheck_comparison_of_distinct_pointers)
11198     << LHS.get()->getType() << RHS.get()->getType()
11199     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11200 }
11201 
11202 /// Returns false if the pointers are converted to a composite type,
11203 /// true otherwise.
11204 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11205                                            ExprResult &LHS, ExprResult &RHS) {
11206   // C++ [expr.rel]p2:
11207   //   [...] Pointer conversions (4.10) and qualification
11208   //   conversions (4.4) are performed on pointer operands (or on
11209   //   a pointer operand and a null pointer constant) to bring
11210   //   them to their composite pointer type. [...]
11211   //
11212   // C++ [expr.eq]p1 uses the same notion for (in)equality
11213   // comparisons of pointers.
11214 
11215   QualType LHSType = LHS.get()->getType();
11216   QualType RHSType = RHS.get()->getType();
11217   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11218          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11219 
11220   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11221   if (T.isNull()) {
11222     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11223         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11224       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11225     else
11226       S.InvalidOperands(Loc, LHS, RHS);
11227     return true;
11228   }
11229 
11230   return false;
11231 }
11232 
11233 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11234                                                     ExprResult &LHS,
11235                                                     ExprResult &RHS,
11236                                                     bool IsError) {
11237   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11238                       : diag::ext_typecheck_comparison_of_fptr_to_void)
11239     << LHS.get()->getType() << RHS.get()->getType()
11240     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11241 }
11242 
11243 static bool isObjCObjectLiteral(ExprResult &E) {
11244   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11245   case Stmt::ObjCArrayLiteralClass:
11246   case Stmt::ObjCDictionaryLiteralClass:
11247   case Stmt::ObjCStringLiteralClass:
11248   case Stmt::ObjCBoxedExprClass:
11249     return true;
11250   default:
11251     // Note that ObjCBoolLiteral is NOT an object literal!
11252     return false;
11253   }
11254 }
11255 
11256 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11257   const ObjCObjectPointerType *Type =
11258     LHS->getType()->getAs<ObjCObjectPointerType>();
11259 
11260   // If this is not actually an Objective-C object, bail out.
11261   if (!Type)
11262     return false;
11263 
11264   // Get the LHS object's interface type.
11265   QualType InterfaceType = Type->getPointeeType();
11266 
11267   // If the RHS isn't an Objective-C object, bail out.
11268   if (!RHS->getType()->isObjCObjectPointerType())
11269     return false;
11270 
11271   // Try to find the -isEqual: method.
11272   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11273   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11274                                                       InterfaceType,
11275                                                       /*IsInstance=*/true);
11276   if (!Method) {
11277     if (Type->isObjCIdType()) {
11278       // For 'id', just check the global pool.
11279       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11280                                                   /*receiverId=*/true);
11281     } else {
11282       // Check protocols.
11283       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11284                                              /*IsInstance=*/true);
11285     }
11286   }
11287 
11288   if (!Method)
11289     return false;
11290 
11291   QualType T = Method->parameters()[0]->getType();
11292   if (!T->isObjCObjectPointerType())
11293     return false;
11294 
11295   QualType R = Method->getReturnType();
11296   if (!R->isScalarType())
11297     return false;
11298 
11299   return true;
11300 }
11301 
11302 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11303   FromE = FromE->IgnoreParenImpCasts();
11304   switch (FromE->getStmtClass()) {
11305     default:
11306       break;
11307     case Stmt::ObjCStringLiteralClass:
11308       // "string literal"
11309       return LK_String;
11310     case Stmt::ObjCArrayLiteralClass:
11311       // "array literal"
11312       return LK_Array;
11313     case Stmt::ObjCDictionaryLiteralClass:
11314       // "dictionary literal"
11315       return LK_Dictionary;
11316     case Stmt::BlockExprClass:
11317       return LK_Block;
11318     case Stmt::ObjCBoxedExprClass: {
11319       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11320       switch (Inner->getStmtClass()) {
11321         case Stmt::IntegerLiteralClass:
11322         case Stmt::FloatingLiteralClass:
11323         case Stmt::CharacterLiteralClass:
11324         case Stmt::ObjCBoolLiteralExprClass:
11325         case Stmt::CXXBoolLiteralExprClass:
11326           // "numeric literal"
11327           return LK_Numeric;
11328         case Stmt::ImplicitCastExprClass: {
11329           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11330           // Boolean literals can be represented by implicit casts.
11331           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11332             return LK_Numeric;
11333           break;
11334         }
11335         default:
11336           break;
11337       }
11338       return LK_Boxed;
11339     }
11340   }
11341   return LK_None;
11342 }
11343 
11344 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11345                                           ExprResult &LHS, ExprResult &RHS,
11346                                           BinaryOperator::Opcode Opc){
11347   Expr *Literal;
11348   Expr *Other;
11349   if (isObjCObjectLiteral(LHS)) {
11350     Literal = LHS.get();
11351     Other = RHS.get();
11352   } else {
11353     Literal = RHS.get();
11354     Other = LHS.get();
11355   }
11356 
11357   // Don't warn on comparisons against nil.
11358   Other = Other->IgnoreParenCasts();
11359   if (Other->isNullPointerConstant(S.getASTContext(),
11360                                    Expr::NPC_ValueDependentIsNotNull))
11361     return;
11362 
11363   // This should be kept in sync with warn_objc_literal_comparison.
11364   // LK_String should always be after the other literals, since it has its own
11365   // warning flag.
11366   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11367   assert(LiteralKind != Sema::LK_Block);
11368   if (LiteralKind == Sema::LK_None) {
11369     llvm_unreachable("Unknown Objective-C object literal kind");
11370   }
11371 
11372   if (LiteralKind == Sema::LK_String)
11373     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11374       << Literal->getSourceRange();
11375   else
11376     S.Diag(Loc, diag::warn_objc_literal_comparison)
11377       << LiteralKind << Literal->getSourceRange();
11378 
11379   if (BinaryOperator::isEqualityOp(Opc) &&
11380       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11381     SourceLocation Start = LHS.get()->getBeginLoc();
11382     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11383     CharSourceRange OpRange =
11384       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11385 
11386     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11387       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11388       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11389       << FixItHint::CreateInsertion(End, "]");
11390   }
11391 }
11392 
11393 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11394 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11395                                            ExprResult &RHS, SourceLocation Loc,
11396                                            BinaryOperatorKind Opc) {
11397   // Check that left hand side is !something.
11398   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11399   if (!UO || UO->getOpcode() != UO_LNot) return;
11400 
11401   // Only check if the right hand side is non-bool arithmetic type.
11402   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11403 
11404   // Make sure that the something in !something is not bool.
11405   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11406   if (SubExpr->isKnownToHaveBooleanValue()) return;
11407 
11408   // Emit warning.
11409   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11410   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11411       << Loc << IsBitwiseOp;
11412 
11413   // First note suggest !(x < y)
11414   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11415   SourceLocation FirstClose = RHS.get()->getEndLoc();
11416   FirstClose = S.getLocForEndOfToken(FirstClose);
11417   if (FirstClose.isInvalid())
11418     FirstOpen = SourceLocation();
11419   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11420       << IsBitwiseOp
11421       << FixItHint::CreateInsertion(FirstOpen, "(")
11422       << FixItHint::CreateInsertion(FirstClose, ")");
11423 
11424   // Second note suggests (!x) < y
11425   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11426   SourceLocation SecondClose = LHS.get()->getEndLoc();
11427   SecondClose = S.getLocForEndOfToken(SecondClose);
11428   if (SecondClose.isInvalid())
11429     SecondOpen = SourceLocation();
11430   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11431       << FixItHint::CreateInsertion(SecondOpen, "(")
11432       << FixItHint::CreateInsertion(SecondClose, ")");
11433 }
11434 
11435 // Returns true if E refers to a non-weak array.
11436 static bool checkForArray(const Expr *E) {
11437   const ValueDecl *D = nullptr;
11438   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11439     D = DR->getDecl();
11440   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11441     if (Mem->isImplicitAccess())
11442       D = Mem->getMemberDecl();
11443   }
11444   if (!D)
11445     return false;
11446   return D->getType()->isArrayType() && !D->isWeak();
11447 }
11448 
11449 /// Diagnose some forms of syntactically-obvious tautological comparison.
11450 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11451                                            Expr *LHS, Expr *RHS,
11452                                            BinaryOperatorKind Opc) {
11453   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11454   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11455 
11456   QualType LHSType = LHS->getType();
11457   QualType RHSType = RHS->getType();
11458   if (LHSType->hasFloatingRepresentation() ||
11459       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11460       S.inTemplateInstantiation())
11461     return;
11462 
11463   // Comparisons between two array types are ill-formed for operator<=>, so
11464   // we shouldn't emit any additional warnings about it.
11465   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11466     return;
11467 
11468   // For non-floating point types, check for self-comparisons of the form
11469   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11470   // often indicate logic errors in the program.
11471   //
11472   // NOTE: Don't warn about comparison expressions resulting from macro
11473   // expansion. Also don't warn about comparisons which are only self
11474   // comparisons within a template instantiation. The warnings should catch
11475   // obvious cases in the definition of the template anyways. The idea is to
11476   // warn when the typed comparison operator will always evaluate to the same
11477   // result.
11478 
11479   // Used for indexing into %select in warn_comparison_always
11480   enum {
11481     AlwaysConstant,
11482     AlwaysTrue,
11483     AlwaysFalse,
11484     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11485   };
11486 
11487   // C++2a [depr.array.comp]:
11488   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11489   //   operands of array type are deprecated.
11490   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11491       RHSStripped->getType()->isArrayType()) {
11492     S.Diag(Loc, diag::warn_depr_array_comparison)
11493         << LHS->getSourceRange() << RHS->getSourceRange()
11494         << LHSStripped->getType() << RHSStripped->getType();
11495     // Carry on to produce the tautological comparison warning, if this
11496     // expression is potentially-evaluated, we can resolve the array to a
11497     // non-weak declaration, and so on.
11498   }
11499 
11500   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11501     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11502       unsigned Result;
11503       switch (Opc) {
11504       case BO_EQ:
11505       case BO_LE:
11506       case BO_GE:
11507         Result = AlwaysTrue;
11508         break;
11509       case BO_NE:
11510       case BO_LT:
11511       case BO_GT:
11512         Result = AlwaysFalse;
11513         break;
11514       case BO_Cmp:
11515         Result = AlwaysEqual;
11516         break;
11517       default:
11518         Result = AlwaysConstant;
11519         break;
11520       }
11521       S.DiagRuntimeBehavior(Loc, nullptr,
11522                             S.PDiag(diag::warn_comparison_always)
11523                                 << 0 /*self-comparison*/
11524                                 << Result);
11525     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11526       // What is it always going to evaluate to?
11527       unsigned Result;
11528       switch (Opc) {
11529       case BO_EQ: // e.g. array1 == array2
11530         Result = AlwaysFalse;
11531         break;
11532       case BO_NE: // e.g. array1 != array2
11533         Result = AlwaysTrue;
11534         break;
11535       default: // e.g. array1 <= array2
11536         // The best we can say is 'a constant'
11537         Result = AlwaysConstant;
11538         break;
11539       }
11540       S.DiagRuntimeBehavior(Loc, nullptr,
11541                             S.PDiag(diag::warn_comparison_always)
11542                                 << 1 /*array comparison*/
11543                                 << Result);
11544     }
11545   }
11546 
11547   if (isa<CastExpr>(LHSStripped))
11548     LHSStripped = LHSStripped->IgnoreParenCasts();
11549   if (isa<CastExpr>(RHSStripped))
11550     RHSStripped = RHSStripped->IgnoreParenCasts();
11551 
11552   // Warn about comparisons against a string constant (unless the other
11553   // operand is null); the user probably wants string comparison function.
11554   Expr *LiteralString = nullptr;
11555   Expr *LiteralStringStripped = nullptr;
11556   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11557       !RHSStripped->isNullPointerConstant(S.Context,
11558                                           Expr::NPC_ValueDependentIsNull)) {
11559     LiteralString = LHS;
11560     LiteralStringStripped = LHSStripped;
11561   } else if ((isa<StringLiteral>(RHSStripped) ||
11562               isa<ObjCEncodeExpr>(RHSStripped)) &&
11563              !LHSStripped->isNullPointerConstant(S.Context,
11564                                           Expr::NPC_ValueDependentIsNull)) {
11565     LiteralString = RHS;
11566     LiteralStringStripped = RHSStripped;
11567   }
11568 
11569   if (LiteralString) {
11570     S.DiagRuntimeBehavior(Loc, nullptr,
11571                           S.PDiag(diag::warn_stringcompare)
11572                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11573                               << LiteralString->getSourceRange());
11574   }
11575 }
11576 
11577 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11578   switch (CK) {
11579   default: {
11580 #ifndef NDEBUG
11581     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11582                  << "\n";
11583 #endif
11584     llvm_unreachable("unhandled cast kind");
11585   }
11586   case CK_UserDefinedConversion:
11587     return ICK_Identity;
11588   case CK_LValueToRValue:
11589     return ICK_Lvalue_To_Rvalue;
11590   case CK_ArrayToPointerDecay:
11591     return ICK_Array_To_Pointer;
11592   case CK_FunctionToPointerDecay:
11593     return ICK_Function_To_Pointer;
11594   case CK_IntegralCast:
11595     return ICK_Integral_Conversion;
11596   case CK_FloatingCast:
11597     return ICK_Floating_Conversion;
11598   case CK_IntegralToFloating:
11599   case CK_FloatingToIntegral:
11600     return ICK_Floating_Integral;
11601   case CK_IntegralComplexCast:
11602   case CK_FloatingComplexCast:
11603   case CK_FloatingComplexToIntegralComplex:
11604   case CK_IntegralComplexToFloatingComplex:
11605     return ICK_Complex_Conversion;
11606   case CK_FloatingComplexToReal:
11607   case CK_FloatingRealToComplex:
11608   case CK_IntegralComplexToReal:
11609   case CK_IntegralRealToComplex:
11610     return ICK_Complex_Real;
11611   }
11612 }
11613 
11614 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11615                                              QualType FromType,
11616                                              SourceLocation Loc) {
11617   // Check for a narrowing implicit conversion.
11618   StandardConversionSequence SCS;
11619   SCS.setAsIdentityConversion();
11620   SCS.setToType(0, FromType);
11621   SCS.setToType(1, ToType);
11622   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11623     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11624 
11625   APValue PreNarrowingValue;
11626   QualType PreNarrowingType;
11627   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11628                                PreNarrowingType,
11629                                /*IgnoreFloatToIntegralConversion*/ true)) {
11630   case NK_Dependent_Narrowing:
11631     // Implicit conversion to a narrower type, but the expression is
11632     // value-dependent so we can't tell whether it's actually narrowing.
11633   case NK_Not_Narrowing:
11634     return false;
11635 
11636   case NK_Constant_Narrowing:
11637     // Implicit conversion to a narrower type, and the value is not a constant
11638     // expression.
11639     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11640         << /*Constant*/ 1
11641         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11642     return true;
11643 
11644   case NK_Variable_Narrowing:
11645     // Implicit conversion to a narrower type, and the value is not a constant
11646     // expression.
11647   case NK_Type_Narrowing:
11648     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11649         << /*Constant*/ 0 << FromType << ToType;
11650     // TODO: It's not a constant expression, but what if the user intended it
11651     // to be? Can we produce notes to help them figure out why it isn't?
11652     return true;
11653   }
11654   llvm_unreachable("unhandled case in switch");
11655 }
11656 
11657 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11658                                                          ExprResult &LHS,
11659                                                          ExprResult &RHS,
11660                                                          SourceLocation Loc) {
11661   QualType LHSType = LHS.get()->getType();
11662   QualType RHSType = RHS.get()->getType();
11663   // Dig out the original argument type and expression before implicit casts
11664   // were applied. These are the types/expressions we need to check the
11665   // [expr.spaceship] requirements against.
11666   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11667   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11668   QualType LHSStrippedType = LHSStripped.get()->getType();
11669   QualType RHSStrippedType = RHSStripped.get()->getType();
11670 
11671   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11672   // other is not, the program is ill-formed.
11673   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11674     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11675     return QualType();
11676   }
11677 
11678   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11679   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11680                     RHSStrippedType->isEnumeralType();
11681   if (NumEnumArgs == 1) {
11682     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11683     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11684     if (OtherTy->hasFloatingRepresentation()) {
11685       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11686       return QualType();
11687     }
11688   }
11689   if (NumEnumArgs == 2) {
11690     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11691     // type E, the operator yields the result of converting the operands
11692     // to the underlying type of E and applying <=> to the converted operands.
11693     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11694       S.InvalidOperands(Loc, LHS, RHS);
11695       return QualType();
11696     }
11697     QualType IntType =
11698         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11699     assert(IntType->isArithmeticType());
11700 
11701     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11702     // promote the boolean type, and all other promotable integer types, to
11703     // avoid this.
11704     if (IntType->isPromotableIntegerType())
11705       IntType = S.Context.getPromotedIntegerType(IntType);
11706 
11707     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11708     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11709     LHSType = RHSType = IntType;
11710   }
11711 
11712   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11713   // usual arithmetic conversions are applied to the operands.
11714   QualType Type =
11715       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11716   if (LHS.isInvalid() || RHS.isInvalid())
11717     return QualType();
11718   if (Type.isNull())
11719     return S.InvalidOperands(Loc, LHS, RHS);
11720 
11721   Optional<ComparisonCategoryType> CCT =
11722       getComparisonCategoryForBuiltinCmp(Type);
11723   if (!CCT)
11724     return S.InvalidOperands(Loc, LHS, RHS);
11725 
11726   bool HasNarrowing = checkThreeWayNarrowingConversion(
11727       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11728   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11729                                                    RHS.get()->getBeginLoc());
11730   if (HasNarrowing)
11731     return QualType();
11732 
11733   assert(!Type.isNull() && "composite type for <=> has not been set");
11734 
11735   return S.CheckComparisonCategoryType(
11736       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11737 }
11738 
11739 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11740                                                  ExprResult &RHS,
11741                                                  SourceLocation Loc,
11742                                                  BinaryOperatorKind Opc) {
11743   if (Opc == BO_Cmp)
11744     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11745 
11746   // C99 6.5.8p3 / C99 6.5.9p4
11747   QualType Type =
11748       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11749   if (LHS.isInvalid() || RHS.isInvalid())
11750     return QualType();
11751   if (Type.isNull())
11752     return S.InvalidOperands(Loc, LHS, RHS);
11753   assert(Type->isArithmeticType() || Type->isEnumeralType());
11754 
11755   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11756     return S.InvalidOperands(Loc, LHS, RHS);
11757 
11758   // Check for comparisons of floating point operands using != and ==.
11759   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11760     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11761 
11762   // The result of comparisons is 'bool' in C++, 'int' in C.
11763   return S.Context.getLogicalOperationType();
11764 }
11765 
11766 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11767   if (!NullE.get()->getType()->isAnyPointerType())
11768     return;
11769   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11770   if (!E.get()->getType()->isAnyPointerType() &&
11771       E.get()->isNullPointerConstant(Context,
11772                                      Expr::NPC_ValueDependentIsNotNull) ==
11773         Expr::NPCK_ZeroExpression) {
11774     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11775       if (CL->getValue() == 0)
11776         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11777             << NullValue
11778             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11779                                             NullValue ? "NULL" : "(void *)0");
11780     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11781         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11782         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11783         if (T == Context.CharTy)
11784           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11785               << NullValue
11786               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11787                                               NullValue ? "NULL" : "(void *)0");
11788       }
11789   }
11790 }
11791 
11792 // C99 6.5.8, C++ [expr.rel]
11793 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11794                                     SourceLocation Loc,
11795                                     BinaryOperatorKind Opc) {
11796   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11797   bool IsThreeWay = Opc == BO_Cmp;
11798   bool IsOrdered = IsRelational || IsThreeWay;
11799   auto IsAnyPointerType = [](ExprResult E) {
11800     QualType Ty = E.get()->getType();
11801     return Ty->isPointerType() || Ty->isMemberPointerType();
11802   };
11803 
11804   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11805   // type, array-to-pointer, ..., conversions are performed on both operands to
11806   // bring them to their composite type.
11807   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11808   // any type-related checks.
11809   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11810     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11811     if (LHS.isInvalid())
11812       return QualType();
11813     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11814     if (RHS.isInvalid())
11815       return QualType();
11816   } else {
11817     LHS = DefaultLvalueConversion(LHS.get());
11818     if (LHS.isInvalid())
11819       return QualType();
11820     RHS = DefaultLvalueConversion(RHS.get());
11821     if (RHS.isInvalid())
11822       return QualType();
11823   }
11824 
11825   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11826   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11827     CheckPtrComparisonWithNullChar(LHS, RHS);
11828     CheckPtrComparisonWithNullChar(RHS, LHS);
11829   }
11830 
11831   // Handle vector comparisons separately.
11832   if (LHS.get()->getType()->isVectorType() ||
11833       RHS.get()->getType()->isVectorType())
11834     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11835 
11836   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11837   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11838 
11839   QualType LHSType = LHS.get()->getType();
11840   QualType RHSType = RHS.get()->getType();
11841   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11842       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11843     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11844 
11845   const Expr::NullPointerConstantKind LHSNullKind =
11846       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11847   const Expr::NullPointerConstantKind RHSNullKind =
11848       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11849   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11850   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11851 
11852   auto computeResultTy = [&]() {
11853     if (Opc != BO_Cmp)
11854       return Context.getLogicalOperationType();
11855     assert(getLangOpts().CPlusPlus);
11856     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11857 
11858     QualType CompositeTy = LHS.get()->getType();
11859     assert(!CompositeTy->isReferenceType());
11860 
11861     Optional<ComparisonCategoryType> CCT =
11862         getComparisonCategoryForBuiltinCmp(CompositeTy);
11863     if (!CCT)
11864       return InvalidOperands(Loc, LHS, RHS);
11865 
11866     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11867       // P0946R0: Comparisons between a null pointer constant and an object
11868       // pointer result in std::strong_equality, which is ill-formed under
11869       // P1959R0.
11870       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11871           << (LHSIsNull ? LHS.get()->getSourceRange()
11872                         : RHS.get()->getSourceRange());
11873       return QualType();
11874     }
11875 
11876     return CheckComparisonCategoryType(
11877         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11878   };
11879 
11880   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11881     bool IsEquality = Opc == BO_EQ;
11882     if (RHSIsNull)
11883       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11884                                    RHS.get()->getSourceRange());
11885     else
11886       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11887                                    LHS.get()->getSourceRange());
11888   }
11889 
11890   if (IsOrdered && LHSType->isFunctionPointerType() &&
11891       RHSType->isFunctionPointerType()) {
11892     // Valid unless a relational comparison of function pointers
11893     bool IsError = Opc == BO_Cmp;
11894     auto DiagID =
11895         IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
11896         : getLangOpts().CPlusPlus
11897             ? diag::warn_typecheck_ordered_comparison_of_function_pointers
11898             : diag::ext_typecheck_ordered_comparison_of_function_pointers;
11899     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11900                       << RHS.get()->getSourceRange();
11901     if (IsError)
11902       return QualType();
11903   }
11904 
11905   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11906       (RHSType->isIntegerType() && !RHSIsNull)) {
11907     // Skip normal pointer conversion checks in this case; we have better
11908     // diagnostics for this below.
11909   } else if (getLangOpts().CPlusPlus) {
11910     // Equality comparison of a function pointer to a void pointer is invalid,
11911     // but we allow it as an extension.
11912     // FIXME: If we really want to allow this, should it be part of composite
11913     // pointer type computation so it works in conditionals too?
11914     if (!IsOrdered &&
11915         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11916          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11917       // This is a gcc extension compatibility comparison.
11918       // In a SFINAE context, we treat this as a hard error to maintain
11919       // conformance with the C++ standard.
11920       diagnoseFunctionPointerToVoidComparison(
11921           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11922 
11923       if (isSFINAEContext())
11924         return QualType();
11925 
11926       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11927       return computeResultTy();
11928     }
11929 
11930     // C++ [expr.eq]p2:
11931     //   If at least one operand is a pointer [...] bring them to their
11932     //   composite pointer type.
11933     // C++ [expr.spaceship]p6
11934     //  If at least one of the operands is of pointer type, [...] bring them
11935     //  to their composite pointer type.
11936     // C++ [expr.rel]p2:
11937     //   If both operands are pointers, [...] bring them to their composite
11938     //   pointer type.
11939     // For <=>, the only valid non-pointer types are arrays and functions, and
11940     // we already decayed those, so this is really the same as the relational
11941     // comparison rule.
11942     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11943             (IsOrdered ? 2 : 1) &&
11944         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11945                                          RHSType->isObjCObjectPointerType()))) {
11946       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11947         return QualType();
11948       return computeResultTy();
11949     }
11950   } else if (LHSType->isPointerType() &&
11951              RHSType->isPointerType()) { // C99 6.5.8p2
11952     // All of the following pointer-related warnings are GCC extensions, except
11953     // when handling null pointer constants.
11954     QualType LCanPointeeTy =
11955       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11956     QualType RCanPointeeTy =
11957       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11958 
11959     // C99 6.5.9p2 and C99 6.5.8p2
11960     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11961                                    RCanPointeeTy.getUnqualifiedType())) {
11962       if (IsRelational) {
11963         // Pointers both need to point to complete or incomplete types
11964         if ((LCanPointeeTy->isIncompleteType() !=
11965              RCanPointeeTy->isIncompleteType()) &&
11966             !getLangOpts().C11) {
11967           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11968               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11969               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11970               << RCanPointeeTy->isIncompleteType();
11971         }
11972       }
11973     } else if (!IsRelational &&
11974                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11975       // Valid unless comparison between non-null pointer and function pointer
11976       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11977           && !LHSIsNull && !RHSIsNull)
11978         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11979                                                 /*isError*/false);
11980     } else {
11981       // Invalid
11982       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11983     }
11984     if (LCanPointeeTy != RCanPointeeTy) {
11985       // Treat NULL constant as a special case in OpenCL.
11986       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11987         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11988           Diag(Loc,
11989                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11990               << LHSType << RHSType << 0 /* comparison */
11991               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11992         }
11993       }
11994       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11995       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11996       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11997                                                : CK_BitCast;
11998       if (LHSIsNull && !RHSIsNull)
11999         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12000       else
12001         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12002     }
12003     return computeResultTy();
12004   }
12005 
12006   if (getLangOpts().CPlusPlus) {
12007     // C++ [expr.eq]p4:
12008     //   Two operands of type std::nullptr_t or one operand of type
12009     //   std::nullptr_t and the other a null pointer constant compare equal.
12010     if (!IsOrdered && LHSIsNull && RHSIsNull) {
12011       if (LHSType->isNullPtrType()) {
12012         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12013         return computeResultTy();
12014       }
12015       if (RHSType->isNullPtrType()) {
12016         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12017         return computeResultTy();
12018       }
12019     }
12020 
12021     // Comparison of Objective-C pointers and block pointers against nullptr_t.
12022     // These aren't covered by the composite pointer type rules.
12023     if (!IsOrdered && RHSType->isNullPtrType() &&
12024         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12025       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12026       return computeResultTy();
12027     }
12028     if (!IsOrdered && LHSType->isNullPtrType() &&
12029         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12030       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12031       return computeResultTy();
12032     }
12033 
12034     if (IsRelational &&
12035         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12036          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12037       // HACK: Relational comparison of nullptr_t against a pointer type is
12038       // invalid per DR583, but we allow it within std::less<> and friends,
12039       // since otherwise common uses of it break.
12040       // FIXME: Consider removing this hack once LWG fixes std::less<> and
12041       // friends to have std::nullptr_t overload candidates.
12042       DeclContext *DC = CurContext;
12043       if (isa<FunctionDecl>(DC))
12044         DC = DC->getParent();
12045       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12046         if (CTSD->isInStdNamespace() &&
12047             llvm::StringSwitch<bool>(CTSD->getName())
12048                 .Cases("less", "less_equal", "greater", "greater_equal", true)
12049                 .Default(false)) {
12050           if (RHSType->isNullPtrType())
12051             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12052           else
12053             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12054           return computeResultTy();
12055         }
12056       }
12057     }
12058 
12059     // C++ [expr.eq]p2:
12060     //   If at least one operand is a pointer to member, [...] bring them to
12061     //   their composite pointer type.
12062     if (!IsOrdered &&
12063         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12064       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12065         return QualType();
12066       else
12067         return computeResultTy();
12068     }
12069   }
12070 
12071   // Handle block pointer types.
12072   if (!IsOrdered && LHSType->isBlockPointerType() &&
12073       RHSType->isBlockPointerType()) {
12074     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12075     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12076 
12077     if (!LHSIsNull && !RHSIsNull &&
12078         !Context.typesAreCompatible(lpointee, rpointee)) {
12079       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12080         << LHSType << RHSType << LHS.get()->getSourceRange()
12081         << RHS.get()->getSourceRange();
12082     }
12083     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12084     return computeResultTy();
12085   }
12086 
12087   // Allow block pointers to be compared with null pointer constants.
12088   if (!IsOrdered
12089       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12090           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12091     if (!LHSIsNull && !RHSIsNull) {
12092       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12093              ->getPointeeType()->isVoidType())
12094             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12095                 ->getPointeeType()->isVoidType())))
12096         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12097           << LHSType << RHSType << LHS.get()->getSourceRange()
12098           << RHS.get()->getSourceRange();
12099     }
12100     if (LHSIsNull && !RHSIsNull)
12101       LHS = ImpCastExprToType(LHS.get(), RHSType,
12102                               RHSType->isPointerType() ? CK_BitCast
12103                                 : CK_AnyPointerToBlockPointerCast);
12104     else
12105       RHS = ImpCastExprToType(RHS.get(), LHSType,
12106                               LHSType->isPointerType() ? CK_BitCast
12107                                 : CK_AnyPointerToBlockPointerCast);
12108     return computeResultTy();
12109   }
12110 
12111   if (LHSType->isObjCObjectPointerType() ||
12112       RHSType->isObjCObjectPointerType()) {
12113     const PointerType *LPT = LHSType->getAs<PointerType>();
12114     const PointerType *RPT = RHSType->getAs<PointerType>();
12115     if (LPT || RPT) {
12116       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12117       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12118 
12119       if (!LPtrToVoid && !RPtrToVoid &&
12120           !Context.typesAreCompatible(LHSType, RHSType)) {
12121         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12122                                           /*isError*/false);
12123       }
12124       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12125       // the RHS, but we have test coverage for this behavior.
12126       // FIXME: Consider using convertPointersToCompositeType in C++.
12127       if (LHSIsNull && !RHSIsNull) {
12128         Expr *E = LHS.get();
12129         if (getLangOpts().ObjCAutoRefCount)
12130           CheckObjCConversion(SourceRange(), RHSType, E,
12131                               CCK_ImplicitConversion);
12132         LHS = ImpCastExprToType(E, RHSType,
12133                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12134       }
12135       else {
12136         Expr *E = RHS.get();
12137         if (getLangOpts().ObjCAutoRefCount)
12138           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12139                               /*Diagnose=*/true,
12140                               /*DiagnoseCFAudited=*/false, Opc);
12141         RHS = ImpCastExprToType(E, LHSType,
12142                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12143       }
12144       return computeResultTy();
12145     }
12146     if (LHSType->isObjCObjectPointerType() &&
12147         RHSType->isObjCObjectPointerType()) {
12148       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12149         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12150                                           /*isError*/false);
12151       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12152         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12153 
12154       if (LHSIsNull && !RHSIsNull)
12155         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12156       else
12157         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12158       return computeResultTy();
12159     }
12160 
12161     if (!IsOrdered && LHSType->isBlockPointerType() &&
12162         RHSType->isBlockCompatibleObjCPointerType(Context)) {
12163       LHS = ImpCastExprToType(LHS.get(), RHSType,
12164                               CK_BlockPointerToObjCPointerCast);
12165       return computeResultTy();
12166     } else if (!IsOrdered &&
12167                LHSType->isBlockCompatibleObjCPointerType(Context) &&
12168                RHSType->isBlockPointerType()) {
12169       RHS = ImpCastExprToType(RHS.get(), LHSType,
12170                               CK_BlockPointerToObjCPointerCast);
12171       return computeResultTy();
12172     }
12173   }
12174   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12175       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12176     unsigned DiagID = 0;
12177     bool isError = false;
12178     if (LangOpts.DebuggerSupport) {
12179       // Under a debugger, allow the comparison of pointers to integers,
12180       // since users tend to want to compare addresses.
12181     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12182                (RHSIsNull && RHSType->isIntegerType())) {
12183       if (IsOrdered) {
12184         isError = getLangOpts().CPlusPlus;
12185         DiagID =
12186           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12187                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12188       }
12189     } else if (getLangOpts().CPlusPlus) {
12190       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12191       isError = true;
12192     } else if (IsOrdered)
12193       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12194     else
12195       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12196 
12197     if (DiagID) {
12198       Diag(Loc, DiagID)
12199         << LHSType << RHSType << LHS.get()->getSourceRange()
12200         << RHS.get()->getSourceRange();
12201       if (isError)
12202         return QualType();
12203     }
12204 
12205     if (LHSType->isIntegerType())
12206       LHS = ImpCastExprToType(LHS.get(), RHSType,
12207                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12208     else
12209       RHS = ImpCastExprToType(RHS.get(), LHSType,
12210                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12211     return computeResultTy();
12212   }
12213 
12214   // Handle block pointers.
12215   if (!IsOrdered && RHSIsNull
12216       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12217     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12218     return computeResultTy();
12219   }
12220   if (!IsOrdered && LHSIsNull
12221       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12222     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12223     return computeResultTy();
12224   }
12225 
12226   if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12227     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12228       return computeResultTy();
12229     }
12230 
12231     if (LHSType->isQueueT() && RHSType->isQueueT()) {
12232       return computeResultTy();
12233     }
12234 
12235     if (LHSIsNull && RHSType->isQueueT()) {
12236       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12237       return computeResultTy();
12238     }
12239 
12240     if (LHSType->isQueueT() && RHSIsNull) {
12241       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12242       return computeResultTy();
12243     }
12244   }
12245 
12246   return InvalidOperands(Loc, LHS, RHS);
12247 }
12248 
12249 // Return a signed ext_vector_type that is of identical size and number of
12250 // elements. For floating point vectors, return an integer type of identical
12251 // size and number of elements. In the non ext_vector_type case, search from
12252 // the largest type to the smallest type to avoid cases where long long == long,
12253 // where long gets picked over long long.
12254 QualType Sema::GetSignedVectorType(QualType V) {
12255   const VectorType *VTy = V->castAs<VectorType>();
12256   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12257 
12258   if (isa<ExtVectorType>(VTy)) {
12259     if (TypeSize == Context.getTypeSize(Context.CharTy))
12260       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12261     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12262       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12263     else if (TypeSize == Context.getTypeSize(Context.IntTy))
12264       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12265     else if (TypeSize == Context.getTypeSize(Context.LongTy))
12266       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12267     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12268            "Unhandled vector element size in vector compare");
12269     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12270   }
12271 
12272   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12273     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12274                                  VectorType::GenericVector);
12275   else if (TypeSize == Context.getTypeSize(Context.LongTy))
12276     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12277                                  VectorType::GenericVector);
12278   else if (TypeSize == Context.getTypeSize(Context.IntTy))
12279     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12280                                  VectorType::GenericVector);
12281   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12282     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12283                                  VectorType::GenericVector);
12284   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12285          "Unhandled vector element size in vector compare");
12286   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12287                                VectorType::GenericVector);
12288 }
12289 
12290 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12291 /// operates on extended vector types.  Instead of producing an IntTy result,
12292 /// like a scalar comparison, a vector comparison produces a vector of integer
12293 /// types.
12294 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12295                                           SourceLocation Loc,
12296                                           BinaryOperatorKind Opc) {
12297   if (Opc == BO_Cmp) {
12298     Diag(Loc, diag::err_three_way_vector_comparison);
12299     return QualType();
12300   }
12301 
12302   // Check to make sure we're operating on vectors of the same type and width,
12303   // Allowing one side to be a scalar of element type.
12304   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
12305                               /*AllowBothBool*/true,
12306                               /*AllowBoolConversions*/getLangOpts().ZVector);
12307   if (vType.isNull())
12308     return vType;
12309 
12310   QualType LHSType = LHS.get()->getType();
12311 
12312   // Determine the return type of a vector compare. By default clang will return
12313   // a scalar for all vector compares except vector bool and vector pixel.
12314   // With the gcc compiler we will always return a vector type and with the xl
12315   // compiler we will always return a scalar type. This switch allows choosing
12316   // which behavior is prefered.
12317   if (getLangOpts().AltiVec) {
12318     switch (getLangOpts().getAltivecSrcCompat()) {
12319     case LangOptions::AltivecSrcCompatKind::Mixed:
12320       // If AltiVec, the comparison results in a numeric type, i.e.
12321       // bool for C++, int for C
12322       if (vType->castAs<VectorType>()->getVectorKind() ==
12323           VectorType::AltiVecVector)
12324         return Context.getLogicalOperationType();
12325       else
12326         Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12327       break;
12328     case LangOptions::AltivecSrcCompatKind::GCC:
12329       // For GCC we always return the vector type.
12330       break;
12331     case LangOptions::AltivecSrcCompatKind::XL:
12332       return Context.getLogicalOperationType();
12333       break;
12334     }
12335   }
12336 
12337   // For non-floating point types, check for self-comparisons of the form
12338   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12339   // often indicate logic errors in the program.
12340   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12341 
12342   // Check for comparisons of floating point operands using != and ==.
12343   if (BinaryOperator::isEqualityOp(Opc) &&
12344       LHSType->hasFloatingRepresentation()) {
12345     assert(RHS.get()->getType()->hasFloatingRepresentation());
12346     CheckFloatComparison(Loc, LHS.get(), RHS.get());
12347   }
12348 
12349   // Return a signed type for the vector.
12350   return GetSignedVectorType(vType);
12351 }
12352 
12353 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12354                                     const ExprResult &XorRHS,
12355                                     const SourceLocation Loc) {
12356   // Do not diagnose macros.
12357   if (Loc.isMacroID())
12358     return;
12359 
12360   // Do not diagnose if both LHS and RHS are macros.
12361   if (XorLHS.get()->getExprLoc().isMacroID() &&
12362       XorRHS.get()->getExprLoc().isMacroID())
12363     return;
12364 
12365   bool Negative = false;
12366   bool ExplicitPlus = false;
12367   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12368   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12369 
12370   if (!LHSInt)
12371     return;
12372   if (!RHSInt) {
12373     // Check negative literals.
12374     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12375       UnaryOperatorKind Opc = UO->getOpcode();
12376       if (Opc != UO_Minus && Opc != UO_Plus)
12377         return;
12378       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12379       if (!RHSInt)
12380         return;
12381       Negative = (Opc == UO_Minus);
12382       ExplicitPlus = !Negative;
12383     } else {
12384       return;
12385     }
12386   }
12387 
12388   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12389   llvm::APInt RightSideValue = RHSInt->getValue();
12390   if (LeftSideValue != 2 && LeftSideValue != 10)
12391     return;
12392 
12393   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12394     return;
12395 
12396   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12397       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12398   llvm::StringRef ExprStr =
12399       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12400 
12401   CharSourceRange XorRange =
12402       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12403   llvm::StringRef XorStr =
12404       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12405   // Do not diagnose if xor keyword/macro is used.
12406   if (XorStr == "xor")
12407     return;
12408 
12409   std::string LHSStr = std::string(Lexer::getSourceText(
12410       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12411       S.getSourceManager(), S.getLangOpts()));
12412   std::string RHSStr = std::string(Lexer::getSourceText(
12413       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12414       S.getSourceManager(), S.getLangOpts()));
12415 
12416   if (Negative) {
12417     RightSideValue = -RightSideValue;
12418     RHSStr = "-" + RHSStr;
12419   } else if (ExplicitPlus) {
12420     RHSStr = "+" + RHSStr;
12421   }
12422 
12423   StringRef LHSStrRef = LHSStr;
12424   StringRef RHSStrRef = RHSStr;
12425   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12426   // literals.
12427   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12428       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12429       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12430       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12431       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12432       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12433       LHSStrRef.find('\'') != StringRef::npos ||
12434       RHSStrRef.find('\'') != StringRef::npos)
12435     return;
12436 
12437   bool SuggestXor =
12438       S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12439   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12440   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12441   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12442     std::string SuggestedExpr = "1 << " + RHSStr;
12443     bool Overflow = false;
12444     llvm::APInt One = (LeftSideValue - 1);
12445     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12446     if (Overflow) {
12447       if (RightSideIntValue < 64)
12448         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12449             << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12450             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12451       else if (RightSideIntValue == 64)
12452         S.Diag(Loc, diag::warn_xor_used_as_pow)
12453             << ExprStr << toString(XorValue, 10, true);
12454       else
12455         return;
12456     } else {
12457       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12458           << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12459           << toString(PowValue, 10, true)
12460           << FixItHint::CreateReplacement(
12461                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12462     }
12463 
12464     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12465         << ("0x2 ^ " + RHSStr) << SuggestXor;
12466   } else if (LeftSideValue == 10) {
12467     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12468     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12469         << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12470         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12471     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12472         << ("0xA ^ " + RHSStr) << SuggestXor;
12473   }
12474 }
12475 
12476 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12477                                           SourceLocation Loc) {
12478   // Ensure that either both operands are of the same vector type, or
12479   // one operand is of a vector type and the other is of its element type.
12480   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12481                                        /*AllowBothBool*/true,
12482                                        /*AllowBoolConversions*/false);
12483   if (vType.isNull())
12484     return InvalidOperands(Loc, LHS, RHS);
12485   if (getLangOpts().OpenCL &&
12486       getLangOpts().getOpenCLCompatibleVersion() < 120 &&
12487       vType->hasFloatingRepresentation())
12488     return InvalidOperands(Loc, LHS, RHS);
12489   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12490   //        usage of the logical operators && and || with vectors in C. This
12491   //        check could be notionally dropped.
12492   if (!getLangOpts().CPlusPlus &&
12493       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12494     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12495 
12496   return GetSignedVectorType(LHS.get()->getType());
12497 }
12498 
12499 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12500                                               SourceLocation Loc,
12501                                               bool IsCompAssign) {
12502   if (!IsCompAssign) {
12503     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12504     if (LHS.isInvalid())
12505       return QualType();
12506   }
12507   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12508   if (RHS.isInvalid())
12509     return QualType();
12510 
12511   // For conversion purposes, we ignore any qualifiers.
12512   // For example, "const float" and "float" are equivalent.
12513   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12514   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12515 
12516   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12517   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12518   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12519 
12520   if (Context.hasSameType(LHSType, RHSType))
12521     return LHSType;
12522 
12523   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12524   // case we have to return InvalidOperands.
12525   ExprResult OriginalLHS = LHS;
12526   ExprResult OriginalRHS = RHS;
12527   if (LHSMatType && !RHSMatType) {
12528     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12529     if (!RHS.isInvalid())
12530       return LHSType;
12531 
12532     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12533   }
12534 
12535   if (!LHSMatType && RHSMatType) {
12536     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12537     if (!LHS.isInvalid())
12538       return RHSType;
12539     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12540   }
12541 
12542   return InvalidOperands(Loc, LHS, RHS);
12543 }
12544 
12545 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12546                                            SourceLocation Loc,
12547                                            bool IsCompAssign) {
12548   if (!IsCompAssign) {
12549     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12550     if (LHS.isInvalid())
12551       return QualType();
12552   }
12553   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12554   if (RHS.isInvalid())
12555     return QualType();
12556 
12557   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12558   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12559   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12560 
12561   if (LHSMatType && RHSMatType) {
12562     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12563       return InvalidOperands(Loc, LHS, RHS);
12564 
12565     if (!Context.hasSameType(LHSMatType->getElementType(),
12566                              RHSMatType->getElementType()))
12567       return InvalidOperands(Loc, LHS, RHS);
12568 
12569     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12570                                          LHSMatType->getNumRows(),
12571                                          RHSMatType->getNumColumns());
12572   }
12573   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12574 }
12575 
12576 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12577                                            SourceLocation Loc,
12578                                            BinaryOperatorKind Opc) {
12579   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12580 
12581   bool IsCompAssign =
12582       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12583 
12584   if (LHS.get()->getType()->isVectorType() ||
12585       RHS.get()->getType()->isVectorType()) {
12586     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12587         RHS.get()->getType()->hasIntegerRepresentation())
12588       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12589                         /*AllowBothBool*/true,
12590                         /*AllowBoolConversions*/getLangOpts().ZVector);
12591     return InvalidOperands(Loc, LHS, RHS);
12592   }
12593 
12594   if (Opc == BO_And)
12595     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12596 
12597   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12598       RHS.get()->getType()->hasFloatingRepresentation())
12599     return InvalidOperands(Loc, LHS, RHS);
12600 
12601   ExprResult LHSResult = LHS, RHSResult = RHS;
12602   QualType compType = UsualArithmeticConversions(
12603       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12604   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12605     return QualType();
12606   LHS = LHSResult.get();
12607   RHS = RHSResult.get();
12608 
12609   if (Opc == BO_Xor)
12610     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12611 
12612   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12613     return compType;
12614   return InvalidOperands(Loc, LHS, RHS);
12615 }
12616 
12617 // C99 6.5.[13,14]
12618 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12619                                            SourceLocation Loc,
12620                                            BinaryOperatorKind Opc) {
12621   // Check vector operands differently.
12622   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12623     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12624 
12625   bool EnumConstantInBoolContext = false;
12626   for (const ExprResult &HS : {LHS, RHS}) {
12627     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12628       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12629       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12630         EnumConstantInBoolContext = true;
12631     }
12632   }
12633 
12634   if (EnumConstantInBoolContext)
12635     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12636 
12637   // Diagnose cases where the user write a logical and/or but probably meant a
12638   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12639   // is a constant.
12640   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12641       !LHS.get()->getType()->isBooleanType() &&
12642       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12643       // Don't warn in macros or template instantiations.
12644       !Loc.isMacroID() && !inTemplateInstantiation()) {
12645     // If the RHS can be constant folded, and if it constant folds to something
12646     // that isn't 0 or 1 (which indicate a potential logical operation that
12647     // happened to fold to true/false) then warn.
12648     // Parens on the RHS are ignored.
12649     Expr::EvalResult EVResult;
12650     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12651       llvm::APSInt Result = EVResult.Val.getInt();
12652       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12653            !RHS.get()->getExprLoc().isMacroID()) ||
12654           (Result != 0 && Result != 1)) {
12655         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12656           << RHS.get()->getSourceRange()
12657           << (Opc == BO_LAnd ? "&&" : "||");
12658         // Suggest replacing the logical operator with the bitwise version
12659         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12660             << (Opc == BO_LAnd ? "&" : "|")
12661             << FixItHint::CreateReplacement(SourceRange(
12662                                                  Loc, getLocForEndOfToken(Loc)),
12663                                             Opc == BO_LAnd ? "&" : "|");
12664         if (Opc == BO_LAnd)
12665           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12666           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12667               << FixItHint::CreateRemoval(
12668                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12669                                  RHS.get()->getEndLoc()));
12670       }
12671     }
12672   }
12673 
12674   if (!Context.getLangOpts().CPlusPlus) {
12675     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12676     // not operate on the built-in scalar and vector float types.
12677     if (Context.getLangOpts().OpenCL &&
12678         Context.getLangOpts().OpenCLVersion < 120) {
12679       if (LHS.get()->getType()->isFloatingType() ||
12680           RHS.get()->getType()->isFloatingType())
12681         return InvalidOperands(Loc, LHS, RHS);
12682     }
12683 
12684     LHS = UsualUnaryConversions(LHS.get());
12685     if (LHS.isInvalid())
12686       return QualType();
12687 
12688     RHS = UsualUnaryConversions(RHS.get());
12689     if (RHS.isInvalid())
12690       return QualType();
12691 
12692     if (!LHS.get()->getType()->isScalarType() ||
12693         !RHS.get()->getType()->isScalarType())
12694       return InvalidOperands(Loc, LHS, RHS);
12695 
12696     return Context.IntTy;
12697   }
12698 
12699   // The following is safe because we only use this method for
12700   // non-overloadable operands.
12701 
12702   // C++ [expr.log.and]p1
12703   // C++ [expr.log.or]p1
12704   // The operands are both contextually converted to type bool.
12705   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12706   if (LHSRes.isInvalid())
12707     return InvalidOperands(Loc, LHS, RHS);
12708   LHS = LHSRes;
12709 
12710   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12711   if (RHSRes.isInvalid())
12712     return InvalidOperands(Loc, LHS, RHS);
12713   RHS = RHSRes;
12714 
12715   // C++ [expr.log.and]p2
12716   // C++ [expr.log.or]p2
12717   // The result is a bool.
12718   return Context.BoolTy;
12719 }
12720 
12721 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12722   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12723   if (!ME) return false;
12724   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12725   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12726       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12727   if (!Base) return false;
12728   return Base->getMethodDecl() != nullptr;
12729 }
12730 
12731 /// Is the given expression (which must be 'const') a reference to a
12732 /// variable which was originally non-const, but which has become
12733 /// 'const' due to being captured within a block?
12734 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12735 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12736   assert(E->isLValue() && E->getType().isConstQualified());
12737   E = E->IgnoreParens();
12738 
12739   // Must be a reference to a declaration from an enclosing scope.
12740   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12741   if (!DRE) return NCCK_None;
12742   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12743 
12744   // The declaration must be a variable which is not declared 'const'.
12745   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12746   if (!var) return NCCK_None;
12747   if (var->getType().isConstQualified()) return NCCK_None;
12748   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12749 
12750   // Decide whether the first capture was for a block or a lambda.
12751   DeclContext *DC = S.CurContext, *Prev = nullptr;
12752   // Decide whether the first capture was for a block or a lambda.
12753   while (DC) {
12754     // For init-capture, it is possible that the variable belongs to the
12755     // template pattern of the current context.
12756     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12757       if (var->isInitCapture() &&
12758           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12759         break;
12760     if (DC == var->getDeclContext())
12761       break;
12762     Prev = DC;
12763     DC = DC->getParent();
12764   }
12765   // Unless we have an init-capture, we've gone one step too far.
12766   if (!var->isInitCapture())
12767     DC = Prev;
12768   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12769 }
12770 
12771 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12772   Ty = Ty.getNonReferenceType();
12773   if (IsDereference && Ty->isPointerType())
12774     Ty = Ty->getPointeeType();
12775   return !Ty.isConstQualified();
12776 }
12777 
12778 // Update err_typecheck_assign_const and note_typecheck_assign_const
12779 // when this enum is changed.
12780 enum {
12781   ConstFunction,
12782   ConstVariable,
12783   ConstMember,
12784   ConstMethod,
12785   NestedConstMember,
12786   ConstUnknown,  // Keep as last element
12787 };
12788 
12789 /// Emit the "read-only variable not assignable" error and print notes to give
12790 /// more information about why the variable is not assignable, such as pointing
12791 /// to the declaration of a const variable, showing that a method is const, or
12792 /// that the function is returning a const reference.
12793 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12794                                     SourceLocation Loc) {
12795   SourceRange ExprRange = E->getSourceRange();
12796 
12797   // Only emit one error on the first const found.  All other consts will emit
12798   // a note to the error.
12799   bool DiagnosticEmitted = false;
12800 
12801   // Track if the current expression is the result of a dereference, and if the
12802   // next checked expression is the result of a dereference.
12803   bool IsDereference = false;
12804   bool NextIsDereference = false;
12805 
12806   // Loop to process MemberExpr chains.
12807   while (true) {
12808     IsDereference = NextIsDereference;
12809 
12810     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12811     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12812       NextIsDereference = ME->isArrow();
12813       const ValueDecl *VD = ME->getMemberDecl();
12814       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12815         // Mutable fields can be modified even if the class is const.
12816         if (Field->isMutable()) {
12817           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12818           break;
12819         }
12820 
12821         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12822           if (!DiagnosticEmitted) {
12823             S.Diag(Loc, diag::err_typecheck_assign_const)
12824                 << ExprRange << ConstMember << false /*static*/ << Field
12825                 << Field->getType();
12826             DiagnosticEmitted = true;
12827           }
12828           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12829               << ConstMember << false /*static*/ << Field << Field->getType()
12830               << Field->getSourceRange();
12831         }
12832         E = ME->getBase();
12833         continue;
12834       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12835         if (VDecl->getType().isConstQualified()) {
12836           if (!DiagnosticEmitted) {
12837             S.Diag(Loc, diag::err_typecheck_assign_const)
12838                 << ExprRange << ConstMember << true /*static*/ << VDecl
12839                 << VDecl->getType();
12840             DiagnosticEmitted = true;
12841           }
12842           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12843               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12844               << VDecl->getSourceRange();
12845         }
12846         // Static fields do not inherit constness from parents.
12847         break;
12848       }
12849       break; // End MemberExpr
12850     } else if (const ArraySubscriptExpr *ASE =
12851                    dyn_cast<ArraySubscriptExpr>(E)) {
12852       E = ASE->getBase()->IgnoreParenImpCasts();
12853       continue;
12854     } else if (const ExtVectorElementExpr *EVE =
12855                    dyn_cast<ExtVectorElementExpr>(E)) {
12856       E = EVE->getBase()->IgnoreParenImpCasts();
12857       continue;
12858     }
12859     break;
12860   }
12861 
12862   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12863     // Function calls
12864     const FunctionDecl *FD = CE->getDirectCallee();
12865     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12866       if (!DiagnosticEmitted) {
12867         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12868                                                       << ConstFunction << FD;
12869         DiagnosticEmitted = true;
12870       }
12871       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12872              diag::note_typecheck_assign_const)
12873           << ConstFunction << FD << FD->getReturnType()
12874           << FD->getReturnTypeSourceRange();
12875     }
12876   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12877     // Point to variable declaration.
12878     if (const ValueDecl *VD = DRE->getDecl()) {
12879       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12880         if (!DiagnosticEmitted) {
12881           S.Diag(Loc, diag::err_typecheck_assign_const)
12882               << ExprRange << ConstVariable << VD << VD->getType();
12883           DiagnosticEmitted = true;
12884         }
12885         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12886             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12887       }
12888     }
12889   } else if (isa<CXXThisExpr>(E)) {
12890     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12891       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12892         if (MD->isConst()) {
12893           if (!DiagnosticEmitted) {
12894             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12895                                                           << ConstMethod << MD;
12896             DiagnosticEmitted = true;
12897           }
12898           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12899               << ConstMethod << MD << MD->getSourceRange();
12900         }
12901       }
12902     }
12903   }
12904 
12905   if (DiagnosticEmitted)
12906     return;
12907 
12908   // Can't determine a more specific message, so display the generic error.
12909   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12910 }
12911 
12912 enum OriginalExprKind {
12913   OEK_Variable,
12914   OEK_Member,
12915   OEK_LValue
12916 };
12917 
12918 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12919                                          const RecordType *Ty,
12920                                          SourceLocation Loc, SourceRange Range,
12921                                          OriginalExprKind OEK,
12922                                          bool &DiagnosticEmitted) {
12923   std::vector<const RecordType *> RecordTypeList;
12924   RecordTypeList.push_back(Ty);
12925   unsigned NextToCheckIndex = 0;
12926   // We walk the record hierarchy breadth-first to ensure that we print
12927   // diagnostics in field nesting order.
12928   while (RecordTypeList.size() > NextToCheckIndex) {
12929     bool IsNested = NextToCheckIndex > 0;
12930     for (const FieldDecl *Field :
12931          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12932       // First, check every field for constness.
12933       QualType FieldTy = Field->getType();
12934       if (FieldTy.isConstQualified()) {
12935         if (!DiagnosticEmitted) {
12936           S.Diag(Loc, diag::err_typecheck_assign_const)
12937               << Range << NestedConstMember << OEK << VD
12938               << IsNested << Field;
12939           DiagnosticEmitted = true;
12940         }
12941         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12942             << NestedConstMember << IsNested << Field
12943             << FieldTy << Field->getSourceRange();
12944       }
12945 
12946       // Then we append it to the list to check next in order.
12947       FieldTy = FieldTy.getCanonicalType();
12948       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12949         if (!llvm::is_contained(RecordTypeList, FieldRecTy))
12950           RecordTypeList.push_back(FieldRecTy);
12951       }
12952     }
12953     ++NextToCheckIndex;
12954   }
12955 }
12956 
12957 /// Emit an error for the case where a record we are trying to assign to has a
12958 /// const-qualified field somewhere in its hierarchy.
12959 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12960                                          SourceLocation Loc) {
12961   QualType Ty = E->getType();
12962   assert(Ty->isRecordType() && "lvalue was not record?");
12963   SourceRange Range = E->getSourceRange();
12964   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12965   bool DiagEmitted = false;
12966 
12967   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12968     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12969             Range, OEK_Member, DiagEmitted);
12970   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12971     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12972             Range, OEK_Variable, DiagEmitted);
12973   else
12974     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12975             Range, OEK_LValue, DiagEmitted);
12976   if (!DiagEmitted)
12977     DiagnoseConstAssignment(S, E, Loc);
12978 }
12979 
12980 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12981 /// emit an error and return true.  If so, return false.
12982 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12983   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12984 
12985   S.CheckShadowingDeclModification(E, Loc);
12986 
12987   SourceLocation OrigLoc = Loc;
12988   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12989                                                               &Loc);
12990   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12991     IsLV = Expr::MLV_InvalidMessageExpression;
12992   if (IsLV == Expr::MLV_Valid)
12993     return false;
12994 
12995   unsigned DiagID = 0;
12996   bool NeedType = false;
12997   switch (IsLV) { // C99 6.5.16p2
12998   case Expr::MLV_ConstQualified:
12999     // Use a specialized diagnostic when we're assigning to an object
13000     // from an enclosing function or block.
13001     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
13002       if (NCCK == NCCK_Block)
13003         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13004       else
13005         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13006       break;
13007     }
13008 
13009     // In ARC, use some specialized diagnostics for occasions where we
13010     // infer 'const'.  These are always pseudo-strong variables.
13011     if (S.getLangOpts().ObjCAutoRefCount) {
13012       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13013       if (declRef && isa<VarDecl>(declRef->getDecl())) {
13014         VarDecl *var = cast<VarDecl>(declRef->getDecl());
13015 
13016         // Use the normal diagnostic if it's pseudo-__strong but the
13017         // user actually wrote 'const'.
13018         if (var->isARCPseudoStrong() &&
13019             (!var->getTypeSourceInfo() ||
13020              !var->getTypeSourceInfo()->getType().isConstQualified())) {
13021           // There are three pseudo-strong cases:
13022           //  - self
13023           ObjCMethodDecl *method = S.getCurMethodDecl();
13024           if (method && var == method->getSelfDecl()) {
13025             DiagID = method->isClassMethod()
13026               ? diag::err_typecheck_arc_assign_self_class_method
13027               : diag::err_typecheck_arc_assign_self;
13028 
13029           //  - Objective-C externally_retained attribute.
13030           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13031                      isa<ParmVarDecl>(var)) {
13032             DiagID = diag::err_typecheck_arc_assign_externally_retained;
13033 
13034           //  - fast enumeration variables
13035           } else {
13036             DiagID = diag::err_typecheck_arr_assign_enumeration;
13037           }
13038 
13039           SourceRange Assign;
13040           if (Loc != OrigLoc)
13041             Assign = SourceRange(OrigLoc, OrigLoc);
13042           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13043           // We need to preserve the AST regardless, so migration tool
13044           // can do its job.
13045           return false;
13046         }
13047       }
13048     }
13049 
13050     // If none of the special cases above are triggered, then this is a
13051     // simple const assignment.
13052     if (DiagID == 0) {
13053       DiagnoseConstAssignment(S, E, Loc);
13054       return true;
13055     }
13056 
13057     break;
13058   case Expr::MLV_ConstAddrSpace:
13059     DiagnoseConstAssignment(S, E, Loc);
13060     return true;
13061   case Expr::MLV_ConstQualifiedField:
13062     DiagnoseRecursiveConstFields(S, E, Loc);
13063     return true;
13064   case Expr::MLV_ArrayType:
13065   case Expr::MLV_ArrayTemporary:
13066     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13067     NeedType = true;
13068     break;
13069   case Expr::MLV_NotObjectType:
13070     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13071     NeedType = true;
13072     break;
13073   case Expr::MLV_LValueCast:
13074     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13075     break;
13076   case Expr::MLV_Valid:
13077     llvm_unreachable("did not take early return for MLV_Valid");
13078   case Expr::MLV_InvalidExpression:
13079   case Expr::MLV_MemberFunction:
13080   case Expr::MLV_ClassTemporary:
13081     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13082     break;
13083   case Expr::MLV_IncompleteType:
13084   case Expr::MLV_IncompleteVoidType:
13085     return S.RequireCompleteType(Loc, E->getType(),
13086              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13087   case Expr::MLV_DuplicateVectorComponents:
13088     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13089     break;
13090   case Expr::MLV_NoSetterProperty:
13091     llvm_unreachable("readonly properties should be processed differently");
13092   case Expr::MLV_InvalidMessageExpression:
13093     DiagID = diag::err_readonly_message_assignment;
13094     break;
13095   case Expr::MLV_SubObjCPropertySetting:
13096     DiagID = diag::err_no_subobject_property_setting;
13097     break;
13098   }
13099 
13100   SourceRange Assign;
13101   if (Loc != OrigLoc)
13102     Assign = SourceRange(OrigLoc, OrigLoc);
13103   if (NeedType)
13104     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13105   else
13106     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13107   return true;
13108 }
13109 
13110 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13111                                          SourceLocation Loc,
13112                                          Sema &Sema) {
13113   if (Sema.inTemplateInstantiation())
13114     return;
13115   if (Sema.isUnevaluatedContext())
13116     return;
13117   if (Loc.isInvalid() || Loc.isMacroID())
13118     return;
13119   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13120     return;
13121 
13122   // C / C++ fields
13123   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13124   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13125   if (ML && MR) {
13126     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13127       return;
13128     const ValueDecl *LHSDecl =
13129         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13130     const ValueDecl *RHSDecl =
13131         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13132     if (LHSDecl != RHSDecl)
13133       return;
13134     if (LHSDecl->getType().isVolatileQualified())
13135       return;
13136     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13137       if (RefTy->getPointeeType().isVolatileQualified())
13138         return;
13139 
13140     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13141   }
13142 
13143   // Objective-C instance variables
13144   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13145   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13146   if (OL && OR && OL->getDecl() == OR->getDecl()) {
13147     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13148     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13149     if (RL && RR && RL->getDecl() == RR->getDecl())
13150       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13151   }
13152 }
13153 
13154 // C99 6.5.16.1
13155 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13156                                        SourceLocation Loc,
13157                                        QualType CompoundType) {
13158   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13159 
13160   // Verify that LHS is a modifiable lvalue, and emit error if not.
13161   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13162     return QualType();
13163 
13164   QualType LHSType = LHSExpr->getType();
13165   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13166                                              CompoundType;
13167   // OpenCL v1.2 s6.1.1.1 p2:
13168   // The half data type can only be used to declare a pointer to a buffer that
13169   // contains half values
13170   if (getLangOpts().OpenCL &&
13171       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13172       LHSType->isHalfType()) {
13173     Diag(Loc, diag::err_opencl_half_load_store) << 1
13174         << LHSType.getUnqualifiedType();
13175     return QualType();
13176   }
13177 
13178   AssignConvertType ConvTy;
13179   if (CompoundType.isNull()) {
13180     Expr *RHSCheck = RHS.get();
13181 
13182     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13183 
13184     QualType LHSTy(LHSType);
13185     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13186     if (RHS.isInvalid())
13187       return QualType();
13188     // Special case of NSObject attributes on c-style pointer types.
13189     if (ConvTy == IncompatiblePointer &&
13190         ((Context.isObjCNSObjectType(LHSType) &&
13191           RHSType->isObjCObjectPointerType()) ||
13192          (Context.isObjCNSObjectType(RHSType) &&
13193           LHSType->isObjCObjectPointerType())))
13194       ConvTy = Compatible;
13195 
13196     if (ConvTy == Compatible &&
13197         LHSType->isObjCObjectType())
13198         Diag(Loc, diag::err_objc_object_assignment)
13199           << LHSType;
13200 
13201     // If the RHS is a unary plus or minus, check to see if they = and + are
13202     // right next to each other.  If so, the user may have typo'd "x =+ 4"
13203     // instead of "x += 4".
13204     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13205       RHSCheck = ICE->getSubExpr();
13206     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13207       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13208           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13209           // Only if the two operators are exactly adjacent.
13210           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13211           // And there is a space or other character before the subexpr of the
13212           // unary +/-.  We don't want to warn on "x=-1".
13213           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13214           UO->getSubExpr()->getBeginLoc().isFileID()) {
13215         Diag(Loc, diag::warn_not_compound_assign)
13216           << (UO->getOpcode() == UO_Plus ? "+" : "-")
13217           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13218       }
13219     }
13220 
13221     if (ConvTy == Compatible) {
13222       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13223         // Warn about retain cycles where a block captures the LHS, but
13224         // not if the LHS is a simple variable into which the block is
13225         // being stored...unless that variable can be captured by reference!
13226         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13227         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13228         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13229           checkRetainCycles(LHSExpr, RHS.get());
13230       }
13231 
13232       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13233           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13234         // It is safe to assign a weak reference into a strong variable.
13235         // Although this code can still have problems:
13236         //   id x = self.weakProp;
13237         //   id y = self.weakProp;
13238         // we do not warn to warn spuriously when 'x' and 'y' are on separate
13239         // paths through the function. This should be revisited if
13240         // -Wrepeated-use-of-weak is made flow-sensitive.
13241         // For ObjCWeak only, we do not warn if the assign is to a non-weak
13242         // variable, which will be valid for the current autorelease scope.
13243         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13244                              RHS.get()->getBeginLoc()))
13245           getCurFunction()->markSafeWeakUse(RHS.get());
13246 
13247       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13248         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13249       }
13250     }
13251   } else {
13252     // Compound assignment "x += y"
13253     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13254   }
13255 
13256   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13257                                RHS.get(), AA_Assigning))
13258     return QualType();
13259 
13260   CheckForNullPointerDereference(*this, LHSExpr);
13261 
13262   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13263     if (CompoundType.isNull()) {
13264       // C++2a [expr.ass]p5:
13265       //   A simple-assignment whose left operand is of a volatile-qualified
13266       //   type is deprecated unless the assignment is either a discarded-value
13267       //   expression or an unevaluated operand
13268       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13269     } else {
13270       // C++2a [expr.ass]p6:
13271       //   [Compound-assignment] expressions are deprecated if E1 has
13272       //   volatile-qualified type
13273       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13274     }
13275   }
13276 
13277   // C99 6.5.16p3: The type of an assignment expression is the type of the
13278   // left operand unless the left operand has qualified type, in which case
13279   // it is the unqualified version of the type of the left operand.
13280   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
13281   // is converted to the type of the assignment expression (above).
13282   // C++ 5.17p1: the type of the assignment expression is that of its left
13283   // operand.
13284   return (getLangOpts().CPlusPlus
13285           ? LHSType : LHSType.getUnqualifiedType());
13286 }
13287 
13288 // Only ignore explicit casts to void.
13289 static bool IgnoreCommaOperand(const Expr *E) {
13290   E = E->IgnoreParens();
13291 
13292   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13293     if (CE->getCastKind() == CK_ToVoid) {
13294       return true;
13295     }
13296 
13297     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13298     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13299         CE->getSubExpr()->getType()->isDependentType()) {
13300       return true;
13301     }
13302   }
13303 
13304   return false;
13305 }
13306 
13307 // Look for instances where it is likely the comma operator is confused with
13308 // another operator.  There is an explicit list of acceptable expressions for
13309 // the left hand side of the comma operator, otherwise emit a warning.
13310 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13311   // No warnings in macros
13312   if (Loc.isMacroID())
13313     return;
13314 
13315   // Don't warn in template instantiations.
13316   if (inTemplateInstantiation())
13317     return;
13318 
13319   // Scope isn't fine-grained enough to explicitly list the specific cases, so
13320   // instead, skip more than needed, then call back into here with the
13321   // CommaVisitor in SemaStmt.cpp.
13322   // The listed locations are the initialization and increment portions
13323   // of a for loop.  The additional checks are on the condition of
13324   // if statements, do/while loops, and for loops.
13325   // Differences in scope flags for C89 mode requires the extra logic.
13326   const unsigned ForIncrementFlags =
13327       getLangOpts().C99 || getLangOpts().CPlusPlus
13328           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13329           : Scope::ContinueScope | Scope::BreakScope;
13330   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13331   const unsigned ScopeFlags = getCurScope()->getFlags();
13332   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13333       (ScopeFlags & ForInitFlags) == ForInitFlags)
13334     return;
13335 
13336   // If there are multiple comma operators used together, get the RHS of the
13337   // of the comma operator as the LHS.
13338   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13339     if (BO->getOpcode() != BO_Comma)
13340       break;
13341     LHS = BO->getRHS();
13342   }
13343 
13344   // Only allow some expressions on LHS to not warn.
13345   if (IgnoreCommaOperand(LHS))
13346     return;
13347 
13348   Diag(Loc, diag::warn_comma_operator);
13349   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13350       << LHS->getSourceRange()
13351       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13352                                     LangOpts.CPlusPlus ? "static_cast<void>("
13353                                                        : "(void)(")
13354       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13355                                     ")");
13356 }
13357 
13358 // C99 6.5.17
13359 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13360                                    SourceLocation Loc) {
13361   LHS = S.CheckPlaceholderExpr(LHS.get());
13362   RHS = S.CheckPlaceholderExpr(RHS.get());
13363   if (LHS.isInvalid() || RHS.isInvalid())
13364     return QualType();
13365 
13366   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13367   // operands, but not unary promotions.
13368   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13369 
13370   // So we treat the LHS as a ignored value, and in C++ we allow the
13371   // containing site to determine what should be done with the RHS.
13372   LHS = S.IgnoredValueConversions(LHS.get());
13373   if (LHS.isInvalid())
13374     return QualType();
13375 
13376   S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13377 
13378   if (!S.getLangOpts().CPlusPlus) {
13379     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13380     if (RHS.isInvalid())
13381       return QualType();
13382     if (!RHS.get()->getType()->isVoidType())
13383       S.RequireCompleteType(Loc, RHS.get()->getType(),
13384                             diag::err_incomplete_type);
13385   }
13386 
13387   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13388     S.DiagnoseCommaOperator(LHS.get(), Loc);
13389 
13390   return RHS.get()->getType();
13391 }
13392 
13393 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13394 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13395 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13396                                                ExprValueKind &VK,
13397                                                ExprObjectKind &OK,
13398                                                SourceLocation OpLoc,
13399                                                bool IsInc, bool IsPrefix) {
13400   if (Op->isTypeDependent())
13401     return S.Context.DependentTy;
13402 
13403   QualType ResType = Op->getType();
13404   // Atomic types can be used for increment / decrement where the non-atomic
13405   // versions can, so ignore the _Atomic() specifier for the purpose of
13406   // checking.
13407   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13408     ResType = ResAtomicType->getValueType();
13409 
13410   assert(!ResType.isNull() && "no type for increment/decrement expression");
13411 
13412   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13413     // Decrement of bool is not allowed.
13414     if (!IsInc) {
13415       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13416       return QualType();
13417     }
13418     // Increment of bool sets it to true, but is deprecated.
13419     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13420                                               : diag::warn_increment_bool)
13421       << Op->getSourceRange();
13422   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13423     // Error on enum increments and decrements in C++ mode
13424     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13425     return QualType();
13426   } else if (ResType->isRealType()) {
13427     // OK!
13428   } else if (ResType->isPointerType()) {
13429     // C99 6.5.2.4p2, 6.5.6p2
13430     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13431       return QualType();
13432   } else if (ResType->isObjCObjectPointerType()) {
13433     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13434     // Otherwise, we just need a complete type.
13435     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13436         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13437       return QualType();
13438   } else if (ResType->isAnyComplexType()) {
13439     // C99 does not support ++/-- on complex types, we allow as an extension.
13440     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13441       << ResType << Op->getSourceRange();
13442   } else if (ResType->isPlaceholderType()) {
13443     ExprResult PR = S.CheckPlaceholderExpr(Op);
13444     if (PR.isInvalid()) return QualType();
13445     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13446                                           IsInc, IsPrefix);
13447   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13448     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13449   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13450              (ResType->castAs<VectorType>()->getVectorKind() !=
13451               VectorType::AltiVecBool)) {
13452     // The z vector extensions allow ++ and -- for non-bool vectors.
13453   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13454             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13455     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13456   } else {
13457     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13458       << ResType << int(IsInc) << Op->getSourceRange();
13459     return QualType();
13460   }
13461   // At this point, we know we have a real, complex or pointer type.
13462   // Now make sure the operand is a modifiable lvalue.
13463   if (CheckForModifiableLvalue(Op, OpLoc, S))
13464     return QualType();
13465   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13466     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13467     //   An operand with volatile-qualified type is deprecated
13468     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13469         << IsInc << ResType;
13470   }
13471   // In C++, a prefix increment is the same type as the operand. Otherwise
13472   // (in C or with postfix), the increment is the unqualified type of the
13473   // operand.
13474   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13475     VK = VK_LValue;
13476     OK = Op->getObjectKind();
13477     return ResType;
13478   } else {
13479     VK = VK_PRValue;
13480     return ResType.getUnqualifiedType();
13481   }
13482 }
13483 
13484 
13485 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13486 /// This routine allows us to typecheck complex/recursive expressions
13487 /// where the declaration is needed for type checking. We only need to
13488 /// handle cases when the expression references a function designator
13489 /// or is an lvalue. Here are some examples:
13490 ///  - &(x) => x
13491 ///  - &*****f => f for f a function designator.
13492 ///  - &s.xx => s
13493 ///  - &s.zz[1].yy -> s, if zz is an array
13494 ///  - *(x + 1) -> x, if x is an array
13495 ///  - &"123"[2] -> 0
13496 ///  - & __real__ x -> x
13497 ///
13498 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13499 /// members.
13500 static ValueDecl *getPrimaryDecl(Expr *E) {
13501   switch (E->getStmtClass()) {
13502   case Stmt::DeclRefExprClass:
13503     return cast<DeclRefExpr>(E)->getDecl();
13504   case Stmt::MemberExprClass:
13505     // If this is an arrow operator, the address is an offset from
13506     // the base's value, so the object the base refers to is
13507     // irrelevant.
13508     if (cast<MemberExpr>(E)->isArrow())
13509       return nullptr;
13510     // Otherwise, the expression refers to a part of the base
13511     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13512   case Stmt::ArraySubscriptExprClass: {
13513     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13514     // promotion of register arrays earlier.
13515     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13516     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13517       if (ICE->getSubExpr()->getType()->isArrayType())
13518         return getPrimaryDecl(ICE->getSubExpr());
13519     }
13520     return nullptr;
13521   }
13522   case Stmt::UnaryOperatorClass: {
13523     UnaryOperator *UO = cast<UnaryOperator>(E);
13524 
13525     switch(UO->getOpcode()) {
13526     case UO_Real:
13527     case UO_Imag:
13528     case UO_Extension:
13529       return getPrimaryDecl(UO->getSubExpr());
13530     default:
13531       return nullptr;
13532     }
13533   }
13534   case Stmt::ParenExprClass:
13535     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13536   case Stmt::ImplicitCastExprClass:
13537     // If the result of an implicit cast is an l-value, we care about
13538     // the sub-expression; otherwise, the result here doesn't matter.
13539     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13540   case Stmt::CXXUuidofExprClass:
13541     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13542   default:
13543     return nullptr;
13544   }
13545 }
13546 
13547 namespace {
13548 enum {
13549   AO_Bit_Field = 0,
13550   AO_Vector_Element = 1,
13551   AO_Property_Expansion = 2,
13552   AO_Register_Variable = 3,
13553   AO_Matrix_Element = 4,
13554   AO_No_Error = 5
13555 };
13556 }
13557 /// Diagnose invalid operand for address of operations.
13558 ///
13559 /// \param Type The type of operand which cannot have its address taken.
13560 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13561                                          Expr *E, unsigned Type) {
13562   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13563 }
13564 
13565 /// CheckAddressOfOperand - The operand of & must be either a function
13566 /// designator or an lvalue designating an object. If it is an lvalue, the
13567 /// object cannot be declared with storage class register or be a bit field.
13568 /// Note: The usual conversions are *not* applied to the operand of the &
13569 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13570 /// In C++, the operand might be an overloaded function name, in which case
13571 /// we allow the '&' but retain the overloaded-function type.
13572 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13573   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13574     if (PTy->getKind() == BuiltinType::Overload) {
13575       Expr *E = OrigOp.get()->IgnoreParens();
13576       if (!isa<OverloadExpr>(E)) {
13577         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13578         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13579           << OrigOp.get()->getSourceRange();
13580         return QualType();
13581       }
13582 
13583       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13584       if (isa<UnresolvedMemberExpr>(Ovl))
13585         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13586           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13587             << OrigOp.get()->getSourceRange();
13588           return QualType();
13589         }
13590 
13591       return Context.OverloadTy;
13592     }
13593 
13594     if (PTy->getKind() == BuiltinType::UnknownAny)
13595       return Context.UnknownAnyTy;
13596 
13597     if (PTy->getKind() == BuiltinType::BoundMember) {
13598       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13599         << OrigOp.get()->getSourceRange();
13600       return QualType();
13601     }
13602 
13603     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13604     if (OrigOp.isInvalid()) return QualType();
13605   }
13606 
13607   if (OrigOp.get()->isTypeDependent())
13608     return Context.DependentTy;
13609 
13610   assert(!OrigOp.get()->getType()->isPlaceholderType());
13611 
13612   // Make sure to ignore parentheses in subsequent checks
13613   Expr *op = OrigOp.get()->IgnoreParens();
13614 
13615   // In OpenCL captures for blocks called as lambda functions
13616   // are located in the private address space. Blocks used in
13617   // enqueue_kernel can be located in a different address space
13618   // depending on a vendor implementation. Thus preventing
13619   // taking an address of the capture to avoid invalid AS casts.
13620   if (LangOpts.OpenCL) {
13621     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13622     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13623       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13624       return QualType();
13625     }
13626   }
13627 
13628   if (getLangOpts().C99) {
13629     // Implement C99-only parts of addressof rules.
13630     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13631       if (uOp->getOpcode() == UO_Deref)
13632         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13633         // (assuming the deref expression is valid).
13634         return uOp->getSubExpr()->getType();
13635     }
13636     // Technically, there should be a check for array subscript
13637     // expressions here, but the result of one is always an lvalue anyway.
13638   }
13639   ValueDecl *dcl = getPrimaryDecl(op);
13640 
13641   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13642     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13643                                            op->getBeginLoc()))
13644       return QualType();
13645 
13646   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13647   unsigned AddressOfError = AO_No_Error;
13648 
13649   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13650     bool sfinae = (bool)isSFINAEContext();
13651     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13652                                   : diag::ext_typecheck_addrof_temporary)
13653       << op->getType() << op->getSourceRange();
13654     if (sfinae)
13655       return QualType();
13656     // Materialize the temporary as an lvalue so that we can take its address.
13657     OrigOp = op =
13658         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13659   } else if (isa<ObjCSelectorExpr>(op)) {
13660     return Context.getPointerType(op->getType());
13661   } else if (lval == Expr::LV_MemberFunction) {
13662     // If it's an instance method, make a member pointer.
13663     // The expression must have exactly the form &A::foo.
13664 
13665     // If the underlying expression isn't a decl ref, give up.
13666     if (!isa<DeclRefExpr>(op)) {
13667       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13668         << OrigOp.get()->getSourceRange();
13669       return QualType();
13670     }
13671     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13672     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13673 
13674     // The id-expression was parenthesized.
13675     if (OrigOp.get() != DRE) {
13676       Diag(OpLoc, diag::err_parens_pointer_member_function)
13677         << OrigOp.get()->getSourceRange();
13678 
13679     // The method was named without a qualifier.
13680     } else if (!DRE->getQualifier()) {
13681       if (MD->getParent()->getName().empty())
13682         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13683           << op->getSourceRange();
13684       else {
13685         SmallString<32> Str;
13686         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13687         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13688           << op->getSourceRange()
13689           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13690       }
13691     }
13692 
13693     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13694     if (isa<CXXDestructorDecl>(MD))
13695       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13696 
13697     QualType MPTy = Context.getMemberPointerType(
13698         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13699     // Under the MS ABI, lock down the inheritance model now.
13700     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13701       (void)isCompleteType(OpLoc, MPTy);
13702     return MPTy;
13703   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13704     // C99 6.5.3.2p1
13705     // The operand must be either an l-value or a function designator
13706     if (!op->getType()->isFunctionType()) {
13707       // Use a special diagnostic for loads from property references.
13708       if (isa<PseudoObjectExpr>(op)) {
13709         AddressOfError = AO_Property_Expansion;
13710       } else {
13711         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13712           << op->getType() << op->getSourceRange();
13713         return QualType();
13714       }
13715     }
13716   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13717     // The operand cannot be a bit-field
13718     AddressOfError = AO_Bit_Field;
13719   } else if (op->getObjectKind() == OK_VectorComponent) {
13720     // The operand cannot be an element of a vector
13721     AddressOfError = AO_Vector_Element;
13722   } else if (op->getObjectKind() == OK_MatrixComponent) {
13723     // The operand cannot be an element of a matrix.
13724     AddressOfError = AO_Matrix_Element;
13725   } else if (dcl) { // C99 6.5.3.2p1
13726     // We have an lvalue with a decl. Make sure the decl is not declared
13727     // with the register storage-class specifier.
13728     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13729       // in C++ it is not error to take address of a register
13730       // variable (c++03 7.1.1P3)
13731       if (vd->getStorageClass() == SC_Register &&
13732           !getLangOpts().CPlusPlus) {
13733         AddressOfError = AO_Register_Variable;
13734       }
13735     } else if (isa<MSPropertyDecl>(dcl)) {
13736       AddressOfError = AO_Property_Expansion;
13737     } else if (isa<FunctionTemplateDecl>(dcl)) {
13738       return Context.OverloadTy;
13739     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13740       // Okay: we can take the address of a field.
13741       // Could be a pointer to member, though, if there is an explicit
13742       // scope qualifier for the class.
13743       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13744         DeclContext *Ctx = dcl->getDeclContext();
13745         if (Ctx && Ctx->isRecord()) {
13746           if (dcl->getType()->isReferenceType()) {
13747             Diag(OpLoc,
13748                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13749               << dcl->getDeclName() << dcl->getType();
13750             return QualType();
13751           }
13752 
13753           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13754             Ctx = Ctx->getParent();
13755 
13756           QualType MPTy = Context.getMemberPointerType(
13757               op->getType(),
13758               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13759           // Under the MS ABI, lock down the inheritance model now.
13760           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13761             (void)isCompleteType(OpLoc, MPTy);
13762           return MPTy;
13763         }
13764       }
13765     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13766                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13767       llvm_unreachable("Unknown/unexpected decl type");
13768   }
13769 
13770   if (AddressOfError != AO_No_Error) {
13771     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13772     return QualType();
13773   }
13774 
13775   if (lval == Expr::LV_IncompleteVoidType) {
13776     // Taking the address of a void variable is technically illegal, but we
13777     // allow it in cases which are otherwise valid.
13778     // Example: "extern void x; void* y = &x;".
13779     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13780   }
13781 
13782   // If the operand has type "type", the result has type "pointer to type".
13783   if (op->getType()->isObjCObjectType())
13784     return Context.getObjCObjectPointerType(op->getType());
13785 
13786   CheckAddressOfPackedMember(op);
13787 
13788   return Context.getPointerType(op->getType());
13789 }
13790 
13791 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13792   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13793   if (!DRE)
13794     return;
13795   const Decl *D = DRE->getDecl();
13796   if (!D)
13797     return;
13798   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13799   if (!Param)
13800     return;
13801   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13802     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13803       return;
13804   if (FunctionScopeInfo *FD = S.getCurFunction())
13805     if (!FD->ModifiedNonNullParams.count(Param))
13806       FD->ModifiedNonNullParams.insert(Param);
13807 }
13808 
13809 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13810 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13811                                         SourceLocation OpLoc) {
13812   if (Op->isTypeDependent())
13813     return S.Context.DependentTy;
13814 
13815   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13816   if (ConvResult.isInvalid())
13817     return QualType();
13818   Op = ConvResult.get();
13819   QualType OpTy = Op->getType();
13820   QualType Result;
13821 
13822   if (isa<CXXReinterpretCastExpr>(Op)) {
13823     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13824     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13825                                      Op->getSourceRange());
13826   }
13827 
13828   if (const PointerType *PT = OpTy->getAs<PointerType>())
13829   {
13830     Result = PT->getPointeeType();
13831   }
13832   else if (const ObjCObjectPointerType *OPT =
13833              OpTy->getAs<ObjCObjectPointerType>())
13834     Result = OPT->getPointeeType();
13835   else {
13836     ExprResult PR = S.CheckPlaceholderExpr(Op);
13837     if (PR.isInvalid()) return QualType();
13838     if (PR.get() != Op)
13839       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13840   }
13841 
13842   if (Result.isNull()) {
13843     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13844       << OpTy << Op->getSourceRange();
13845     return QualType();
13846   }
13847 
13848   // Note that per both C89 and C99, indirection is always legal, even if Result
13849   // is an incomplete type or void.  It would be possible to warn about
13850   // dereferencing a void pointer, but it's completely well-defined, and such a
13851   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13852   // for pointers to 'void' but is fine for any other pointer type:
13853   //
13854   // C++ [expr.unary.op]p1:
13855   //   [...] the expression to which [the unary * operator] is applied shall
13856   //   be a pointer to an object type, or a pointer to a function type
13857   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13858     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13859       << OpTy << Op->getSourceRange();
13860 
13861   // Dereferences are usually l-values...
13862   VK = VK_LValue;
13863 
13864   // ...except that certain expressions are never l-values in C.
13865   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13866     VK = VK_PRValue;
13867 
13868   return Result;
13869 }
13870 
13871 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13872   BinaryOperatorKind Opc;
13873   switch (Kind) {
13874   default: llvm_unreachable("Unknown binop!");
13875   case tok::periodstar:           Opc = BO_PtrMemD; break;
13876   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13877   case tok::star:                 Opc = BO_Mul; break;
13878   case tok::slash:                Opc = BO_Div; break;
13879   case tok::percent:              Opc = BO_Rem; break;
13880   case tok::plus:                 Opc = BO_Add; break;
13881   case tok::minus:                Opc = BO_Sub; break;
13882   case tok::lessless:             Opc = BO_Shl; break;
13883   case tok::greatergreater:       Opc = BO_Shr; break;
13884   case tok::lessequal:            Opc = BO_LE; break;
13885   case tok::less:                 Opc = BO_LT; break;
13886   case tok::greaterequal:         Opc = BO_GE; break;
13887   case tok::greater:              Opc = BO_GT; break;
13888   case tok::exclaimequal:         Opc = BO_NE; break;
13889   case tok::equalequal:           Opc = BO_EQ; break;
13890   case tok::spaceship:            Opc = BO_Cmp; break;
13891   case tok::amp:                  Opc = BO_And; break;
13892   case tok::caret:                Opc = BO_Xor; break;
13893   case tok::pipe:                 Opc = BO_Or; break;
13894   case tok::ampamp:               Opc = BO_LAnd; break;
13895   case tok::pipepipe:             Opc = BO_LOr; break;
13896   case tok::equal:                Opc = BO_Assign; break;
13897   case tok::starequal:            Opc = BO_MulAssign; break;
13898   case tok::slashequal:           Opc = BO_DivAssign; break;
13899   case tok::percentequal:         Opc = BO_RemAssign; break;
13900   case tok::plusequal:            Opc = BO_AddAssign; break;
13901   case tok::minusequal:           Opc = BO_SubAssign; break;
13902   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13903   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13904   case tok::ampequal:             Opc = BO_AndAssign; break;
13905   case tok::caretequal:           Opc = BO_XorAssign; break;
13906   case tok::pipeequal:            Opc = BO_OrAssign; break;
13907   case tok::comma:                Opc = BO_Comma; break;
13908   }
13909   return Opc;
13910 }
13911 
13912 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13913   tok::TokenKind Kind) {
13914   UnaryOperatorKind Opc;
13915   switch (Kind) {
13916   default: llvm_unreachable("Unknown unary op!");
13917   case tok::plusplus:     Opc = UO_PreInc; break;
13918   case tok::minusminus:   Opc = UO_PreDec; break;
13919   case tok::amp:          Opc = UO_AddrOf; break;
13920   case tok::star:         Opc = UO_Deref; break;
13921   case tok::plus:         Opc = UO_Plus; break;
13922   case tok::minus:        Opc = UO_Minus; break;
13923   case tok::tilde:        Opc = UO_Not; break;
13924   case tok::exclaim:      Opc = UO_LNot; break;
13925   case tok::kw___real:    Opc = UO_Real; break;
13926   case tok::kw___imag:    Opc = UO_Imag; break;
13927   case tok::kw___extension__: Opc = UO_Extension; break;
13928   }
13929   return Opc;
13930 }
13931 
13932 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13933 /// This warning suppressed in the event of macro expansions.
13934 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13935                                    SourceLocation OpLoc, bool IsBuiltin) {
13936   if (S.inTemplateInstantiation())
13937     return;
13938   if (S.isUnevaluatedContext())
13939     return;
13940   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13941     return;
13942   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13943   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13944   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13945   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13946   if (!LHSDeclRef || !RHSDeclRef ||
13947       LHSDeclRef->getLocation().isMacroID() ||
13948       RHSDeclRef->getLocation().isMacroID())
13949     return;
13950   const ValueDecl *LHSDecl =
13951     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13952   const ValueDecl *RHSDecl =
13953     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13954   if (LHSDecl != RHSDecl)
13955     return;
13956   if (LHSDecl->getType().isVolatileQualified())
13957     return;
13958   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13959     if (RefTy->getPointeeType().isVolatileQualified())
13960       return;
13961 
13962   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13963                           : diag::warn_self_assignment_overloaded)
13964       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13965       << RHSExpr->getSourceRange();
13966 }
13967 
13968 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13969 /// is usually indicative of introspection within the Objective-C pointer.
13970 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13971                                           SourceLocation OpLoc) {
13972   if (!S.getLangOpts().ObjC)
13973     return;
13974 
13975   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13976   const Expr *LHS = L.get();
13977   const Expr *RHS = R.get();
13978 
13979   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13980     ObjCPointerExpr = LHS;
13981     OtherExpr = RHS;
13982   }
13983   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13984     ObjCPointerExpr = RHS;
13985     OtherExpr = LHS;
13986   }
13987 
13988   // This warning is deliberately made very specific to reduce false
13989   // positives with logic that uses '&' for hashing.  This logic mainly
13990   // looks for code trying to introspect into tagged pointers, which
13991   // code should generally never do.
13992   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13993     unsigned Diag = diag::warn_objc_pointer_masking;
13994     // Determine if we are introspecting the result of performSelectorXXX.
13995     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13996     // Special case messages to -performSelector and friends, which
13997     // can return non-pointer values boxed in a pointer value.
13998     // Some clients may wish to silence warnings in this subcase.
13999     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14000       Selector S = ME->getSelector();
14001       StringRef SelArg0 = S.getNameForSlot(0);
14002       if (SelArg0.startswith("performSelector"))
14003         Diag = diag::warn_objc_pointer_masking_performSelector;
14004     }
14005 
14006     S.Diag(OpLoc, Diag)
14007       << ObjCPointerExpr->getSourceRange();
14008   }
14009 }
14010 
14011 static NamedDecl *getDeclFromExpr(Expr *E) {
14012   if (!E)
14013     return nullptr;
14014   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14015     return DRE->getDecl();
14016   if (auto *ME = dyn_cast<MemberExpr>(E))
14017     return ME->getMemberDecl();
14018   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14019     return IRE->getDecl();
14020   return nullptr;
14021 }
14022 
14023 // This helper function promotes a binary operator's operands (which are of a
14024 // half vector type) to a vector of floats and then truncates the result to
14025 // a vector of either half or short.
14026 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
14027                                       BinaryOperatorKind Opc, QualType ResultTy,
14028                                       ExprValueKind VK, ExprObjectKind OK,
14029                                       bool IsCompAssign, SourceLocation OpLoc,
14030                                       FPOptionsOverride FPFeatures) {
14031   auto &Context = S.getASTContext();
14032   assert((isVector(ResultTy, Context.HalfTy) ||
14033           isVector(ResultTy, Context.ShortTy)) &&
14034          "Result must be a vector of half or short");
14035   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14036          isVector(RHS.get()->getType(), Context.HalfTy) &&
14037          "both operands expected to be a half vector");
14038 
14039   RHS = convertVector(RHS.get(), Context.FloatTy, S);
14040   QualType BinOpResTy = RHS.get()->getType();
14041 
14042   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14043   // change BinOpResTy to a vector of ints.
14044   if (isVector(ResultTy, Context.ShortTy))
14045     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14046 
14047   if (IsCompAssign)
14048     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14049                                           ResultTy, VK, OK, OpLoc, FPFeatures,
14050                                           BinOpResTy, BinOpResTy);
14051 
14052   LHS = convertVector(LHS.get(), Context.FloatTy, S);
14053   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14054                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
14055   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14056 }
14057 
14058 static std::pair<ExprResult, ExprResult>
14059 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14060                            Expr *RHSExpr) {
14061   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14062   if (!S.Context.isDependenceAllowed()) {
14063     // C cannot handle TypoExpr nodes on either side of a binop because it
14064     // doesn't handle dependent types properly, so make sure any TypoExprs have
14065     // been dealt with before checking the operands.
14066     LHS = S.CorrectDelayedTyposInExpr(LHS);
14067     RHS = S.CorrectDelayedTyposInExpr(
14068         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14069         [Opc, LHS](Expr *E) {
14070           if (Opc != BO_Assign)
14071             return ExprResult(E);
14072           // Avoid correcting the RHS to the same Expr as the LHS.
14073           Decl *D = getDeclFromExpr(E);
14074           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14075         });
14076   }
14077   return std::make_pair(LHS, RHS);
14078 }
14079 
14080 /// Returns true if conversion between vectors of halfs and vectors of floats
14081 /// is needed.
14082 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14083                                      Expr *E0, Expr *E1 = nullptr) {
14084   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14085       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14086     return false;
14087 
14088   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14089     QualType Ty = E->IgnoreImplicit()->getType();
14090 
14091     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14092     // to vectors of floats. Although the element type of the vectors is __fp16,
14093     // the vectors shouldn't be treated as storage-only types. See the
14094     // discussion here: https://reviews.llvm.org/rG825235c140e7
14095     if (const VectorType *VT = Ty->getAs<VectorType>()) {
14096       if (VT->getVectorKind() == VectorType::NeonVector)
14097         return false;
14098       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14099     }
14100     return false;
14101   };
14102 
14103   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14104 }
14105 
14106 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
14107 /// operator @p Opc at location @c TokLoc. This routine only supports
14108 /// built-in operations; ActOnBinOp handles overloaded operators.
14109 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14110                                     BinaryOperatorKind Opc,
14111                                     Expr *LHSExpr, Expr *RHSExpr) {
14112   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14113     // The syntax only allows initializer lists on the RHS of assignment,
14114     // so we don't need to worry about accepting invalid code for
14115     // non-assignment operators.
14116     // C++11 5.17p9:
14117     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14118     //   of x = {} is x = T().
14119     InitializationKind Kind = InitializationKind::CreateDirectList(
14120         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14121     InitializedEntity Entity =
14122         InitializedEntity::InitializeTemporary(LHSExpr->getType());
14123     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14124     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14125     if (Init.isInvalid())
14126       return Init;
14127     RHSExpr = Init.get();
14128   }
14129 
14130   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14131   QualType ResultTy;     // Result type of the binary operator.
14132   // The following two variables are used for compound assignment operators
14133   QualType CompLHSTy;    // Type of LHS after promotions for computation
14134   QualType CompResultTy; // Type of computation result
14135   ExprValueKind VK = VK_PRValue;
14136   ExprObjectKind OK = OK_Ordinary;
14137   bool ConvertHalfVec = false;
14138 
14139   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14140   if (!LHS.isUsable() || !RHS.isUsable())
14141     return ExprError();
14142 
14143   if (getLangOpts().OpenCL) {
14144     QualType LHSTy = LHSExpr->getType();
14145     QualType RHSTy = RHSExpr->getType();
14146     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14147     // the ATOMIC_VAR_INIT macro.
14148     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14149       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14150       if (BO_Assign == Opc)
14151         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14152       else
14153         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14154       return ExprError();
14155     }
14156 
14157     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14158     // only with a builtin functions and therefore should be disallowed here.
14159     if (LHSTy->isImageType() || RHSTy->isImageType() ||
14160         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14161         LHSTy->isPipeType() || RHSTy->isPipeType() ||
14162         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14163       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14164       return ExprError();
14165     }
14166   }
14167 
14168   switch (Opc) {
14169   case BO_Assign:
14170     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14171     if (getLangOpts().CPlusPlus &&
14172         LHS.get()->getObjectKind() != OK_ObjCProperty) {
14173       VK = LHS.get()->getValueKind();
14174       OK = LHS.get()->getObjectKind();
14175     }
14176     if (!ResultTy.isNull()) {
14177       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14178       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14179 
14180       // Avoid copying a block to the heap if the block is assigned to a local
14181       // auto variable that is declared in the same scope as the block. This
14182       // optimization is unsafe if the local variable is declared in an outer
14183       // scope. For example:
14184       //
14185       // BlockTy b;
14186       // {
14187       //   b = ^{...};
14188       // }
14189       // // It is unsafe to invoke the block here if it wasn't copied to the
14190       // // heap.
14191       // b();
14192 
14193       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14194         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14195           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14196             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14197               BE->getBlockDecl()->setCanAvoidCopyToHeap();
14198 
14199       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14200         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14201                               NTCUC_Assignment, NTCUK_Copy);
14202     }
14203     RecordModifiableNonNullParam(*this, LHS.get());
14204     break;
14205   case BO_PtrMemD:
14206   case BO_PtrMemI:
14207     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14208                                             Opc == BO_PtrMemI);
14209     break;
14210   case BO_Mul:
14211   case BO_Div:
14212     ConvertHalfVec = true;
14213     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14214                                            Opc == BO_Div);
14215     break;
14216   case BO_Rem:
14217     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14218     break;
14219   case BO_Add:
14220     ConvertHalfVec = true;
14221     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14222     break;
14223   case BO_Sub:
14224     ConvertHalfVec = true;
14225     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14226     break;
14227   case BO_Shl:
14228   case BO_Shr:
14229     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14230     break;
14231   case BO_LE:
14232   case BO_LT:
14233   case BO_GE:
14234   case BO_GT:
14235     ConvertHalfVec = true;
14236     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14237     break;
14238   case BO_EQ:
14239   case BO_NE:
14240     ConvertHalfVec = true;
14241     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14242     break;
14243   case BO_Cmp:
14244     ConvertHalfVec = true;
14245     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14246     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14247     break;
14248   case BO_And:
14249     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14250     LLVM_FALLTHROUGH;
14251   case BO_Xor:
14252   case BO_Or:
14253     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14254     break;
14255   case BO_LAnd:
14256   case BO_LOr:
14257     ConvertHalfVec = true;
14258     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14259     break;
14260   case BO_MulAssign:
14261   case BO_DivAssign:
14262     ConvertHalfVec = true;
14263     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14264                                                Opc == BO_DivAssign);
14265     CompLHSTy = CompResultTy;
14266     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14267       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14268     break;
14269   case BO_RemAssign:
14270     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14271     CompLHSTy = CompResultTy;
14272     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14273       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14274     break;
14275   case BO_AddAssign:
14276     ConvertHalfVec = true;
14277     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14278     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14279       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14280     break;
14281   case BO_SubAssign:
14282     ConvertHalfVec = true;
14283     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14284     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14285       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14286     break;
14287   case BO_ShlAssign:
14288   case BO_ShrAssign:
14289     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14290     CompLHSTy = CompResultTy;
14291     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14292       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14293     break;
14294   case BO_AndAssign:
14295   case BO_OrAssign: // fallthrough
14296     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14297     LLVM_FALLTHROUGH;
14298   case BO_XorAssign:
14299     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14300     CompLHSTy = CompResultTy;
14301     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14302       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14303     break;
14304   case BO_Comma:
14305     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14306     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14307       VK = RHS.get()->getValueKind();
14308       OK = RHS.get()->getObjectKind();
14309     }
14310     break;
14311   }
14312   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14313     return ExprError();
14314 
14315   // Some of the binary operations require promoting operands of half vector to
14316   // float vectors and truncating the result back to half vector. For now, we do
14317   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14318   // arm64).
14319   assert(
14320       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14321                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
14322       "both sides are half vectors or neither sides are");
14323   ConvertHalfVec =
14324       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14325 
14326   // Check for array bounds violations for both sides of the BinaryOperator
14327   CheckArrayAccess(LHS.get());
14328   CheckArrayAccess(RHS.get());
14329 
14330   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14331     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14332                                                  &Context.Idents.get("object_setClass"),
14333                                                  SourceLocation(), LookupOrdinaryName);
14334     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14335       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14336       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14337           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14338                                         "object_setClass(")
14339           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14340                                           ",")
14341           << FixItHint::CreateInsertion(RHSLocEnd, ")");
14342     }
14343     else
14344       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14345   }
14346   else if (const ObjCIvarRefExpr *OIRE =
14347            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14348     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14349 
14350   // Opc is not a compound assignment if CompResultTy is null.
14351   if (CompResultTy.isNull()) {
14352     if (ConvertHalfVec)
14353       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14354                                  OpLoc, CurFPFeatureOverrides());
14355     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14356                                   VK, OK, OpLoc, CurFPFeatureOverrides());
14357   }
14358 
14359   // Handle compound assignments.
14360   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14361       OK_ObjCProperty) {
14362     VK = VK_LValue;
14363     OK = LHS.get()->getObjectKind();
14364   }
14365 
14366   // The LHS is not converted to the result type for fixed-point compound
14367   // assignment as the common type is computed on demand. Reset the CompLHSTy
14368   // to the LHS type we would have gotten after unary conversions.
14369   if (CompResultTy->isFixedPointType())
14370     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14371 
14372   if (ConvertHalfVec)
14373     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14374                                OpLoc, CurFPFeatureOverrides());
14375 
14376   return CompoundAssignOperator::Create(
14377       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14378       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14379 }
14380 
14381 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14382 /// operators are mixed in a way that suggests that the programmer forgot that
14383 /// comparison operators have higher precedence. The most typical example of
14384 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14385 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14386                                       SourceLocation OpLoc, Expr *LHSExpr,
14387                                       Expr *RHSExpr) {
14388   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14389   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14390 
14391   // Check that one of the sides is a comparison operator and the other isn't.
14392   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14393   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14394   if (isLeftComp == isRightComp)
14395     return;
14396 
14397   // Bitwise operations are sometimes used as eager logical ops.
14398   // Don't diagnose this.
14399   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14400   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14401   if (isLeftBitwise || isRightBitwise)
14402     return;
14403 
14404   SourceRange DiagRange = isLeftComp
14405                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14406                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14407   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14408   SourceRange ParensRange =
14409       isLeftComp
14410           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14411           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14412 
14413   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14414     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14415   SuggestParentheses(Self, OpLoc,
14416     Self.PDiag(diag::note_precedence_silence) << OpStr,
14417     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14418   SuggestParentheses(Self, OpLoc,
14419     Self.PDiag(diag::note_precedence_bitwise_first)
14420       << BinaryOperator::getOpcodeStr(Opc),
14421     ParensRange);
14422 }
14423 
14424 /// It accepts a '&&' expr that is inside a '||' one.
14425 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14426 /// in parentheses.
14427 static void
14428 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14429                                        BinaryOperator *Bop) {
14430   assert(Bop->getOpcode() == BO_LAnd);
14431   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14432       << Bop->getSourceRange() << OpLoc;
14433   SuggestParentheses(Self, Bop->getOperatorLoc(),
14434     Self.PDiag(diag::note_precedence_silence)
14435       << Bop->getOpcodeStr(),
14436     Bop->getSourceRange());
14437 }
14438 
14439 /// Returns true if the given expression can be evaluated as a constant
14440 /// 'true'.
14441 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14442   bool Res;
14443   return !E->isValueDependent() &&
14444          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14445 }
14446 
14447 /// Returns true if the given expression can be evaluated as a constant
14448 /// 'false'.
14449 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14450   bool Res;
14451   return !E->isValueDependent() &&
14452          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14453 }
14454 
14455 /// Look for '&&' in the left hand of a '||' expr.
14456 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14457                                              Expr *LHSExpr, Expr *RHSExpr) {
14458   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14459     if (Bop->getOpcode() == BO_LAnd) {
14460       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14461       if (EvaluatesAsFalse(S, RHSExpr))
14462         return;
14463       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14464       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14465         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14466     } else if (Bop->getOpcode() == BO_LOr) {
14467       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14468         // If it's "a || b && 1 || c" we didn't warn earlier for
14469         // "a || b && 1", but warn now.
14470         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14471           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14472       }
14473     }
14474   }
14475 }
14476 
14477 /// Look for '&&' in the right hand of a '||' expr.
14478 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14479                                              Expr *LHSExpr, Expr *RHSExpr) {
14480   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14481     if (Bop->getOpcode() == BO_LAnd) {
14482       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14483       if (EvaluatesAsFalse(S, LHSExpr))
14484         return;
14485       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14486       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14487         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14488     }
14489   }
14490 }
14491 
14492 /// Look for bitwise op in the left or right hand of a bitwise op with
14493 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14494 /// the '&' expression in parentheses.
14495 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14496                                          SourceLocation OpLoc, Expr *SubExpr) {
14497   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14498     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14499       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14500         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14501         << Bop->getSourceRange() << OpLoc;
14502       SuggestParentheses(S, Bop->getOperatorLoc(),
14503         S.PDiag(diag::note_precedence_silence)
14504           << Bop->getOpcodeStr(),
14505         Bop->getSourceRange());
14506     }
14507   }
14508 }
14509 
14510 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14511                                     Expr *SubExpr, StringRef Shift) {
14512   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14513     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14514       StringRef Op = Bop->getOpcodeStr();
14515       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14516           << Bop->getSourceRange() << OpLoc << Shift << Op;
14517       SuggestParentheses(S, Bop->getOperatorLoc(),
14518           S.PDiag(diag::note_precedence_silence) << Op,
14519           Bop->getSourceRange());
14520     }
14521   }
14522 }
14523 
14524 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14525                                  Expr *LHSExpr, Expr *RHSExpr) {
14526   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14527   if (!OCE)
14528     return;
14529 
14530   FunctionDecl *FD = OCE->getDirectCallee();
14531   if (!FD || !FD->isOverloadedOperator())
14532     return;
14533 
14534   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14535   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14536     return;
14537 
14538   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14539       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14540       << (Kind == OO_LessLess);
14541   SuggestParentheses(S, OCE->getOperatorLoc(),
14542                      S.PDiag(diag::note_precedence_silence)
14543                          << (Kind == OO_LessLess ? "<<" : ">>"),
14544                      OCE->getSourceRange());
14545   SuggestParentheses(
14546       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14547       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14548 }
14549 
14550 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14551 /// precedence.
14552 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14553                                     SourceLocation OpLoc, Expr *LHSExpr,
14554                                     Expr *RHSExpr){
14555   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14556   if (BinaryOperator::isBitwiseOp(Opc))
14557     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14558 
14559   // Diagnose "arg1 & arg2 | arg3"
14560   if ((Opc == BO_Or || Opc == BO_Xor) &&
14561       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14562     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14563     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14564   }
14565 
14566   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14567   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14568   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14569     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14570     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14571   }
14572 
14573   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14574       || Opc == BO_Shr) {
14575     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14576     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14577     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14578   }
14579 
14580   // Warn on overloaded shift operators and comparisons, such as:
14581   // cout << 5 == 4;
14582   if (BinaryOperator::isComparisonOp(Opc))
14583     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14584 }
14585 
14586 // Binary Operators.  'Tok' is the token for the operator.
14587 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14588                             tok::TokenKind Kind,
14589                             Expr *LHSExpr, Expr *RHSExpr) {
14590   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14591   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14592   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14593 
14594   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14595   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14596 
14597   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14598 }
14599 
14600 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14601                        UnresolvedSetImpl &Functions) {
14602   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14603   if (OverOp != OO_None && OverOp != OO_Equal)
14604     LookupOverloadedOperatorName(OverOp, S, Functions);
14605 
14606   // In C++20 onwards, we may have a second operator to look up.
14607   if (getLangOpts().CPlusPlus20) {
14608     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14609       LookupOverloadedOperatorName(ExtraOp, S, Functions);
14610   }
14611 }
14612 
14613 /// Build an overloaded binary operator expression in the given scope.
14614 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14615                                        BinaryOperatorKind Opc,
14616                                        Expr *LHS, Expr *RHS) {
14617   switch (Opc) {
14618   case BO_Assign:
14619   case BO_DivAssign:
14620   case BO_RemAssign:
14621   case BO_SubAssign:
14622   case BO_AndAssign:
14623   case BO_OrAssign:
14624   case BO_XorAssign:
14625     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14626     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14627     break;
14628   default:
14629     break;
14630   }
14631 
14632   // Find all of the overloaded operators visible from this point.
14633   UnresolvedSet<16> Functions;
14634   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14635 
14636   // Build the (potentially-overloaded, potentially-dependent)
14637   // binary operation.
14638   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14639 }
14640 
14641 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14642                             BinaryOperatorKind Opc,
14643                             Expr *LHSExpr, Expr *RHSExpr) {
14644   ExprResult LHS, RHS;
14645   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14646   if (!LHS.isUsable() || !RHS.isUsable())
14647     return ExprError();
14648   LHSExpr = LHS.get();
14649   RHSExpr = RHS.get();
14650 
14651   // We want to end up calling one of checkPseudoObjectAssignment
14652   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14653   // both expressions are overloadable or either is type-dependent),
14654   // or CreateBuiltinBinOp (in any other case).  We also want to get
14655   // any placeholder types out of the way.
14656 
14657   // Handle pseudo-objects in the LHS.
14658   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14659     // Assignments with a pseudo-object l-value need special analysis.
14660     if (pty->getKind() == BuiltinType::PseudoObject &&
14661         BinaryOperator::isAssignmentOp(Opc))
14662       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14663 
14664     // Don't resolve overloads if the other type is overloadable.
14665     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14666       // We can't actually test that if we still have a placeholder,
14667       // though.  Fortunately, none of the exceptions we see in that
14668       // code below are valid when the LHS is an overload set.  Note
14669       // that an overload set can be dependently-typed, but it never
14670       // instantiates to having an overloadable type.
14671       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14672       if (resolvedRHS.isInvalid()) return ExprError();
14673       RHSExpr = resolvedRHS.get();
14674 
14675       if (RHSExpr->isTypeDependent() ||
14676           RHSExpr->getType()->isOverloadableType())
14677         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14678     }
14679 
14680     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14681     // template, diagnose the missing 'template' keyword instead of diagnosing
14682     // an invalid use of a bound member function.
14683     //
14684     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14685     // to C++1z [over.over]/1.4, but we already checked for that case above.
14686     if (Opc == BO_LT && inTemplateInstantiation() &&
14687         (pty->getKind() == BuiltinType::BoundMember ||
14688          pty->getKind() == BuiltinType::Overload)) {
14689       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14690       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14691           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14692             return isa<FunctionTemplateDecl>(ND);
14693           })) {
14694         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14695                                 : OE->getNameLoc(),
14696              diag::err_template_kw_missing)
14697           << OE->getName().getAsString() << "";
14698         return ExprError();
14699       }
14700     }
14701 
14702     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14703     if (LHS.isInvalid()) return ExprError();
14704     LHSExpr = LHS.get();
14705   }
14706 
14707   // Handle pseudo-objects in the RHS.
14708   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14709     // An overload in the RHS can potentially be resolved by the type
14710     // being assigned to.
14711     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14712       if (getLangOpts().CPlusPlus &&
14713           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14714            LHSExpr->getType()->isOverloadableType()))
14715         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14716 
14717       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14718     }
14719 
14720     // Don't resolve overloads if the other type is overloadable.
14721     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14722         LHSExpr->getType()->isOverloadableType())
14723       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14724 
14725     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14726     if (!resolvedRHS.isUsable()) return ExprError();
14727     RHSExpr = resolvedRHS.get();
14728   }
14729 
14730   if (getLangOpts().CPlusPlus) {
14731     // If either expression is type-dependent, always build an
14732     // overloaded op.
14733     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14734       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14735 
14736     // Otherwise, build an overloaded op if either expression has an
14737     // overloadable type.
14738     if (LHSExpr->getType()->isOverloadableType() ||
14739         RHSExpr->getType()->isOverloadableType())
14740       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14741   }
14742 
14743   if (getLangOpts().RecoveryAST &&
14744       (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
14745     assert(!getLangOpts().CPlusPlus);
14746     assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
14747            "Should only occur in error-recovery path.");
14748     if (BinaryOperator::isCompoundAssignmentOp(Opc))
14749       // C [6.15.16] p3:
14750       // An assignment expression has the value of the left operand after the
14751       // assignment, but is not an lvalue.
14752       return CompoundAssignOperator::Create(
14753           Context, LHSExpr, RHSExpr, Opc,
14754           LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
14755           OpLoc, CurFPFeatureOverrides());
14756     QualType ResultType;
14757     switch (Opc) {
14758     case BO_Assign:
14759       ResultType = LHSExpr->getType().getUnqualifiedType();
14760       break;
14761     case BO_LT:
14762     case BO_GT:
14763     case BO_LE:
14764     case BO_GE:
14765     case BO_EQ:
14766     case BO_NE:
14767     case BO_LAnd:
14768     case BO_LOr:
14769       // These operators have a fixed result type regardless of operands.
14770       ResultType = Context.IntTy;
14771       break;
14772     case BO_Comma:
14773       ResultType = RHSExpr->getType();
14774       break;
14775     default:
14776       ResultType = Context.DependentTy;
14777       break;
14778     }
14779     return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
14780                                   VK_PRValue, OK_Ordinary, OpLoc,
14781                                   CurFPFeatureOverrides());
14782   }
14783 
14784   // Build a built-in binary operation.
14785   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14786 }
14787 
14788 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14789   if (T.isNull() || T->isDependentType())
14790     return false;
14791 
14792   if (!T->isPromotableIntegerType())
14793     return true;
14794 
14795   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14796 }
14797 
14798 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14799                                       UnaryOperatorKind Opc,
14800                                       Expr *InputExpr) {
14801   ExprResult Input = InputExpr;
14802   ExprValueKind VK = VK_PRValue;
14803   ExprObjectKind OK = OK_Ordinary;
14804   QualType resultType;
14805   bool CanOverflow = false;
14806 
14807   bool ConvertHalfVec = false;
14808   if (getLangOpts().OpenCL) {
14809     QualType Ty = InputExpr->getType();
14810     // The only legal unary operation for atomics is '&'.
14811     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14812     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14813     // only with a builtin functions and therefore should be disallowed here.
14814         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14815         || Ty->isBlockPointerType())) {
14816       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14817                        << InputExpr->getType()
14818                        << Input.get()->getSourceRange());
14819     }
14820   }
14821 
14822   switch (Opc) {
14823   case UO_PreInc:
14824   case UO_PreDec:
14825   case UO_PostInc:
14826   case UO_PostDec:
14827     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14828                                                 OpLoc,
14829                                                 Opc == UO_PreInc ||
14830                                                 Opc == UO_PostInc,
14831                                                 Opc == UO_PreInc ||
14832                                                 Opc == UO_PreDec);
14833     CanOverflow = isOverflowingIntegerType(Context, resultType);
14834     break;
14835   case UO_AddrOf:
14836     resultType = CheckAddressOfOperand(Input, OpLoc);
14837     CheckAddressOfNoDeref(InputExpr);
14838     RecordModifiableNonNullParam(*this, InputExpr);
14839     break;
14840   case UO_Deref: {
14841     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14842     if (Input.isInvalid()) return ExprError();
14843     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14844     break;
14845   }
14846   case UO_Plus:
14847   case UO_Minus:
14848     CanOverflow = Opc == UO_Minus &&
14849                   isOverflowingIntegerType(Context, Input.get()->getType());
14850     Input = UsualUnaryConversions(Input.get());
14851     if (Input.isInvalid()) return ExprError();
14852     // Unary plus and minus require promoting an operand of half vector to a
14853     // float vector and truncating the result back to a half vector. For now, we
14854     // do this only when HalfArgsAndReturns is set (that is, when the target is
14855     // arm or arm64).
14856     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14857 
14858     // If the operand is a half vector, promote it to a float vector.
14859     if (ConvertHalfVec)
14860       Input = convertVector(Input.get(), Context.FloatTy, *this);
14861     resultType = Input.get()->getType();
14862     if (resultType->isDependentType())
14863       break;
14864     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14865       break;
14866     else if (resultType->isVectorType() &&
14867              // The z vector extensions don't allow + or - with bool vectors.
14868              (!Context.getLangOpts().ZVector ||
14869               resultType->castAs<VectorType>()->getVectorKind() !=
14870               VectorType::AltiVecBool))
14871       break;
14872     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14873              Opc == UO_Plus &&
14874              resultType->isPointerType())
14875       break;
14876 
14877     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14878       << resultType << Input.get()->getSourceRange());
14879 
14880   case UO_Not: // bitwise complement
14881     Input = UsualUnaryConversions(Input.get());
14882     if (Input.isInvalid())
14883       return ExprError();
14884     resultType = Input.get()->getType();
14885     if (resultType->isDependentType())
14886       break;
14887     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14888     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14889       // C99 does not support '~' for complex conjugation.
14890       Diag(OpLoc, diag::ext_integer_complement_complex)
14891           << resultType << Input.get()->getSourceRange();
14892     else if (resultType->hasIntegerRepresentation())
14893       break;
14894     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14895       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14896       // on vector float types.
14897       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14898       if (!T->isIntegerType())
14899         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14900                           << resultType << Input.get()->getSourceRange());
14901     } else {
14902       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14903                        << resultType << Input.get()->getSourceRange());
14904     }
14905     break;
14906 
14907   case UO_LNot: // logical negation
14908     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14909     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14910     if (Input.isInvalid()) return ExprError();
14911     resultType = Input.get()->getType();
14912 
14913     // Though we still have to promote half FP to float...
14914     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14915       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14916       resultType = Context.FloatTy;
14917     }
14918 
14919     if (resultType->isDependentType())
14920       break;
14921     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14922       // C99 6.5.3.3p1: ok, fallthrough;
14923       if (Context.getLangOpts().CPlusPlus) {
14924         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14925         // operand contextually converted to bool.
14926         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14927                                   ScalarTypeToBooleanCastKind(resultType));
14928       } else if (Context.getLangOpts().OpenCL &&
14929                  Context.getLangOpts().OpenCLVersion < 120) {
14930         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14931         // operate on scalar float types.
14932         if (!resultType->isIntegerType() && !resultType->isPointerType())
14933           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14934                            << resultType << Input.get()->getSourceRange());
14935       }
14936     } else if (resultType->isExtVectorType()) {
14937       if (Context.getLangOpts().OpenCL &&
14938           Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
14939         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14940         // operate on vector float types.
14941         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14942         if (!T->isIntegerType())
14943           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14944                            << resultType << Input.get()->getSourceRange());
14945       }
14946       // Vector logical not returns the signed variant of the operand type.
14947       resultType = GetSignedVectorType(resultType);
14948       break;
14949     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14950       const VectorType *VTy = resultType->castAs<VectorType>();
14951       if (VTy->getVectorKind() != VectorType::GenericVector)
14952         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14953                          << resultType << Input.get()->getSourceRange());
14954 
14955       // Vector logical not returns the signed variant of the operand type.
14956       resultType = GetSignedVectorType(resultType);
14957       break;
14958     } else {
14959       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14960         << resultType << Input.get()->getSourceRange());
14961     }
14962 
14963     // LNot always has type int. C99 6.5.3.3p5.
14964     // In C++, it's bool. C++ 5.3.1p8
14965     resultType = Context.getLogicalOperationType();
14966     break;
14967   case UO_Real:
14968   case UO_Imag:
14969     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14970     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14971     // complex l-values to ordinary l-values and all other values to r-values.
14972     if (Input.isInvalid()) return ExprError();
14973     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14974       if (Input.get()->isGLValue() &&
14975           Input.get()->getObjectKind() == OK_Ordinary)
14976         VK = Input.get()->getValueKind();
14977     } else if (!getLangOpts().CPlusPlus) {
14978       // In C, a volatile scalar is read by __imag. In C++, it is not.
14979       Input = DefaultLvalueConversion(Input.get());
14980     }
14981     break;
14982   case UO_Extension:
14983     resultType = Input.get()->getType();
14984     VK = Input.get()->getValueKind();
14985     OK = Input.get()->getObjectKind();
14986     break;
14987   case UO_Coawait:
14988     // It's unnecessary to represent the pass-through operator co_await in the
14989     // AST; just return the input expression instead.
14990     assert(!Input.get()->getType()->isDependentType() &&
14991                    "the co_await expression must be non-dependant before "
14992                    "building operator co_await");
14993     return Input;
14994   }
14995   if (resultType.isNull() || Input.isInvalid())
14996     return ExprError();
14997 
14998   // Check for array bounds violations in the operand of the UnaryOperator,
14999   // except for the '*' and '&' operators that have to be handled specially
15000   // by CheckArrayAccess (as there are special cases like &array[arraysize]
15001   // that are explicitly defined as valid by the standard).
15002   if (Opc != UO_AddrOf && Opc != UO_Deref)
15003     CheckArrayAccess(Input.get());
15004 
15005   auto *UO =
15006       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15007                             OpLoc, CanOverflow, CurFPFeatureOverrides());
15008 
15009   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15010       !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15011       !isUnevaluatedContext())
15012     ExprEvalContexts.back().PossibleDerefs.insert(UO);
15013 
15014   // Convert the result back to a half vector.
15015   if (ConvertHalfVec)
15016     return convertVector(UO, Context.HalfTy, *this);
15017   return UO;
15018 }
15019 
15020 /// Determine whether the given expression is a qualified member
15021 /// access expression, of a form that could be turned into a pointer to member
15022 /// with the address-of operator.
15023 bool Sema::isQualifiedMemberAccess(Expr *E) {
15024   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15025     if (!DRE->getQualifier())
15026       return false;
15027 
15028     ValueDecl *VD = DRE->getDecl();
15029     if (!VD->isCXXClassMember())
15030       return false;
15031 
15032     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15033       return true;
15034     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15035       return Method->isInstance();
15036 
15037     return false;
15038   }
15039 
15040   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15041     if (!ULE->getQualifier())
15042       return false;
15043 
15044     for (NamedDecl *D : ULE->decls()) {
15045       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15046         if (Method->isInstance())
15047           return true;
15048       } else {
15049         // Overload set does not contain methods.
15050         break;
15051       }
15052     }
15053 
15054     return false;
15055   }
15056 
15057   return false;
15058 }
15059 
15060 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15061                               UnaryOperatorKind Opc, Expr *Input) {
15062   // First things first: handle placeholders so that the
15063   // overloaded-operator check considers the right type.
15064   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15065     // Increment and decrement of pseudo-object references.
15066     if (pty->getKind() == BuiltinType::PseudoObject &&
15067         UnaryOperator::isIncrementDecrementOp(Opc))
15068       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15069 
15070     // extension is always a builtin operator.
15071     if (Opc == UO_Extension)
15072       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15073 
15074     // & gets special logic for several kinds of placeholder.
15075     // The builtin code knows what to do.
15076     if (Opc == UO_AddrOf &&
15077         (pty->getKind() == BuiltinType::Overload ||
15078          pty->getKind() == BuiltinType::UnknownAny ||
15079          pty->getKind() == BuiltinType::BoundMember))
15080       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15081 
15082     // Anything else needs to be handled now.
15083     ExprResult Result = CheckPlaceholderExpr(Input);
15084     if (Result.isInvalid()) return ExprError();
15085     Input = Result.get();
15086   }
15087 
15088   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15089       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15090       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15091     // Find all of the overloaded operators visible from this point.
15092     UnresolvedSet<16> Functions;
15093     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15094     if (S && OverOp != OO_None)
15095       LookupOverloadedOperatorName(OverOp, S, Functions);
15096 
15097     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15098   }
15099 
15100   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15101 }
15102 
15103 // Unary Operators.  'Tok' is the token for the operator.
15104 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
15105                               tok::TokenKind Op, Expr *Input) {
15106   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
15107 }
15108 
15109 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15110 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15111                                 LabelDecl *TheDecl) {
15112   TheDecl->markUsed(Context);
15113   // Create the AST node.  The address of a label always has type 'void*'.
15114   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
15115                                      Context.getPointerType(Context.VoidTy));
15116 }
15117 
15118 void Sema::ActOnStartStmtExpr() {
15119   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15120 }
15121 
15122 void Sema::ActOnStmtExprError() {
15123   // Note that function is also called by TreeTransform when leaving a
15124   // StmtExpr scope without rebuilding anything.
15125 
15126   DiscardCleanupsInEvaluationContext();
15127   PopExpressionEvaluationContext();
15128 }
15129 
15130 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15131                                SourceLocation RPLoc) {
15132   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15133 }
15134 
15135 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15136                                SourceLocation RPLoc, unsigned TemplateDepth) {
15137   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15138   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15139 
15140   if (hasAnyUnrecoverableErrorsInThisFunction())
15141     DiscardCleanupsInEvaluationContext();
15142   assert(!Cleanup.exprNeedsCleanups() &&
15143          "cleanups within StmtExpr not correctly bound!");
15144   PopExpressionEvaluationContext();
15145 
15146   // FIXME: there are a variety of strange constraints to enforce here, for
15147   // example, it is not possible to goto into a stmt expression apparently.
15148   // More semantic analysis is needed.
15149 
15150   // If there are sub-stmts in the compound stmt, take the type of the last one
15151   // as the type of the stmtexpr.
15152   QualType Ty = Context.VoidTy;
15153   bool StmtExprMayBindToTemp = false;
15154   if (!Compound->body_empty()) {
15155     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15156     if (const auto *LastStmt =
15157             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15158       if (const Expr *Value = LastStmt->getExprStmt()) {
15159         StmtExprMayBindToTemp = true;
15160         Ty = Value->getType();
15161       }
15162     }
15163   }
15164 
15165   // FIXME: Check that expression type is complete/non-abstract; statement
15166   // expressions are not lvalues.
15167   Expr *ResStmtExpr =
15168       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15169   if (StmtExprMayBindToTemp)
15170     return MaybeBindToTemporary(ResStmtExpr);
15171   return ResStmtExpr;
15172 }
15173 
15174 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15175   if (ER.isInvalid())
15176     return ExprError();
15177 
15178   // Do function/array conversion on the last expression, but not
15179   // lvalue-to-rvalue.  However, initialize an unqualified type.
15180   ER = DefaultFunctionArrayConversion(ER.get());
15181   if (ER.isInvalid())
15182     return ExprError();
15183   Expr *E = ER.get();
15184 
15185   if (E->isTypeDependent())
15186     return E;
15187 
15188   // In ARC, if the final expression ends in a consume, splice
15189   // the consume out and bind it later.  In the alternate case
15190   // (when dealing with a retainable type), the result
15191   // initialization will create a produce.  In both cases the
15192   // result will be +1, and we'll need to balance that out with
15193   // a bind.
15194   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15195   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15196     return Cast->getSubExpr();
15197 
15198   // FIXME: Provide a better location for the initialization.
15199   return PerformCopyInitialization(
15200       InitializedEntity::InitializeStmtExprResult(
15201           E->getBeginLoc(), E->getType().getUnqualifiedType()),
15202       SourceLocation(), E);
15203 }
15204 
15205 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15206                                       TypeSourceInfo *TInfo,
15207                                       ArrayRef<OffsetOfComponent> Components,
15208                                       SourceLocation RParenLoc) {
15209   QualType ArgTy = TInfo->getType();
15210   bool Dependent = ArgTy->isDependentType();
15211   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15212 
15213   // We must have at least one component that refers to the type, and the first
15214   // one is known to be a field designator.  Verify that the ArgTy represents
15215   // a struct/union/class.
15216   if (!Dependent && !ArgTy->isRecordType())
15217     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15218                        << ArgTy << TypeRange);
15219 
15220   // Type must be complete per C99 7.17p3 because a declaring a variable
15221   // with an incomplete type would be ill-formed.
15222   if (!Dependent
15223       && RequireCompleteType(BuiltinLoc, ArgTy,
15224                              diag::err_offsetof_incomplete_type, TypeRange))
15225     return ExprError();
15226 
15227   bool DidWarnAboutNonPOD = false;
15228   QualType CurrentType = ArgTy;
15229   SmallVector<OffsetOfNode, 4> Comps;
15230   SmallVector<Expr*, 4> Exprs;
15231   for (const OffsetOfComponent &OC : Components) {
15232     if (OC.isBrackets) {
15233       // Offset of an array sub-field.  TODO: Should we allow vector elements?
15234       if (!CurrentType->isDependentType()) {
15235         const ArrayType *AT = Context.getAsArrayType(CurrentType);
15236         if(!AT)
15237           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15238                            << CurrentType);
15239         CurrentType = AT->getElementType();
15240       } else
15241         CurrentType = Context.DependentTy;
15242 
15243       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15244       if (IdxRval.isInvalid())
15245         return ExprError();
15246       Expr *Idx = IdxRval.get();
15247 
15248       // The expression must be an integral expression.
15249       // FIXME: An integral constant expression?
15250       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15251           !Idx->getType()->isIntegerType())
15252         return ExprError(
15253             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15254             << Idx->getSourceRange());
15255 
15256       // Record this array index.
15257       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15258       Exprs.push_back(Idx);
15259       continue;
15260     }
15261 
15262     // Offset of a field.
15263     if (CurrentType->isDependentType()) {
15264       // We have the offset of a field, but we can't look into the dependent
15265       // type. Just record the identifier of the field.
15266       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15267       CurrentType = Context.DependentTy;
15268       continue;
15269     }
15270 
15271     // We need to have a complete type to look into.
15272     if (RequireCompleteType(OC.LocStart, CurrentType,
15273                             diag::err_offsetof_incomplete_type))
15274       return ExprError();
15275 
15276     // Look for the designated field.
15277     const RecordType *RC = CurrentType->getAs<RecordType>();
15278     if (!RC)
15279       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15280                        << CurrentType);
15281     RecordDecl *RD = RC->getDecl();
15282 
15283     // C++ [lib.support.types]p5:
15284     //   The macro offsetof accepts a restricted set of type arguments in this
15285     //   International Standard. type shall be a POD structure or a POD union
15286     //   (clause 9).
15287     // C++11 [support.types]p4:
15288     //   If type is not a standard-layout class (Clause 9), the results are
15289     //   undefined.
15290     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15291       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15292       unsigned DiagID =
15293         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15294                             : diag::ext_offsetof_non_pod_type;
15295 
15296       if (!IsSafe && !DidWarnAboutNonPOD &&
15297           DiagRuntimeBehavior(BuiltinLoc, nullptr,
15298                               PDiag(DiagID)
15299                               << SourceRange(Components[0].LocStart, OC.LocEnd)
15300                               << CurrentType))
15301         DidWarnAboutNonPOD = true;
15302     }
15303 
15304     // Look for the field.
15305     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15306     LookupQualifiedName(R, RD);
15307     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15308     IndirectFieldDecl *IndirectMemberDecl = nullptr;
15309     if (!MemberDecl) {
15310       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15311         MemberDecl = IndirectMemberDecl->getAnonField();
15312     }
15313 
15314     if (!MemberDecl)
15315       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15316                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15317                                                               OC.LocEnd));
15318 
15319     // C99 7.17p3:
15320     //   (If the specified member is a bit-field, the behavior is undefined.)
15321     //
15322     // We diagnose this as an error.
15323     if (MemberDecl->isBitField()) {
15324       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15325         << MemberDecl->getDeclName()
15326         << SourceRange(BuiltinLoc, RParenLoc);
15327       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15328       return ExprError();
15329     }
15330 
15331     RecordDecl *Parent = MemberDecl->getParent();
15332     if (IndirectMemberDecl)
15333       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15334 
15335     // If the member was found in a base class, introduce OffsetOfNodes for
15336     // the base class indirections.
15337     CXXBasePaths Paths;
15338     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15339                       Paths)) {
15340       if (Paths.getDetectedVirtual()) {
15341         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15342           << MemberDecl->getDeclName()
15343           << SourceRange(BuiltinLoc, RParenLoc);
15344         return ExprError();
15345       }
15346 
15347       CXXBasePath &Path = Paths.front();
15348       for (const CXXBasePathElement &B : Path)
15349         Comps.push_back(OffsetOfNode(B.Base));
15350     }
15351 
15352     if (IndirectMemberDecl) {
15353       for (auto *FI : IndirectMemberDecl->chain()) {
15354         assert(isa<FieldDecl>(FI));
15355         Comps.push_back(OffsetOfNode(OC.LocStart,
15356                                      cast<FieldDecl>(FI), OC.LocEnd));
15357       }
15358     } else
15359       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15360 
15361     CurrentType = MemberDecl->getType().getNonReferenceType();
15362   }
15363 
15364   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15365                               Comps, Exprs, RParenLoc);
15366 }
15367 
15368 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15369                                       SourceLocation BuiltinLoc,
15370                                       SourceLocation TypeLoc,
15371                                       ParsedType ParsedArgTy,
15372                                       ArrayRef<OffsetOfComponent> Components,
15373                                       SourceLocation RParenLoc) {
15374 
15375   TypeSourceInfo *ArgTInfo;
15376   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15377   if (ArgTy.isNull())
15378     return ExprError();
15379 
15380   if (!ArgTInfo)
15381     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15382 
15383   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15384 }
15385 
15386 
15387 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15388                                  Expr *CondExpr,
15389                                  Expr *LHSExpr, Expr *RHSExpr,
15390                                  SourceLocation RPLoc) {
15391   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15392 
15393   ExprValueKind VK = VK_PRValue;
15394   ExprObjectKind OK = OK_Ordinary;
15395   QualType resType;
15396   bool CondIsTrue = false;
15397   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15398     resType = Context.DependentTy;
15399   } else {
15400     // The conditional expression is required to be a constant expression.
15401     llvm::APSInt condEval(32);
15402     ExprResult CondICE = VerifyIntegerConstantExpression(
15403         CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15404     if (CondICE.isInvalid())
15405       return ExprError();
15406     CondExpr = CondICE.get();
15407     CondIsTrue = condEval.getZExtValue();
15408 
15409     // If the condition is > zero, then the AST type is the same as the LHSExpr.
15410     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15411 
15412     resType = ActiveExpr->getType();
15413     VK = ActiveExpr->getValueKind();
15414     OK = ActiveExpr->getObjectKind();
15415   }
15416 
15417   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15418                                   resType, VK, OK, RPLoc, CondIsTrue);
15419 }
15420 
15421 //===----------------------------------------------------------------------===//
15422 // Clang Extensions.
15423 //===----------------------------------------------------------------------===//
15424 
15425 /// ActOnBlockStart - This callback is invoked when a block literal is started.
15426 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15427   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15428 
15429   if (LangOpts.CPlusPlus) {
15430     MangleNumberingContext *MCtx;
15431     Decl *ManglingContextDecl;
15432     std::tie(MCtx, ManglingContextDecl) =
15433         getCurrentMangleNumberContext(Block->getDeclContext());
15434     if (MCtx) {
15435       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15436       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15437     }
15438   }
15439 
15440   PushBlockScope(CurScope, Block);
15441   CurContext->addDecl(Block);
15442   if (CurScope)
15443     PushDeclContext(CurScope, Block);
15444   else
15445     CurContext = Block;
15446 
15447   getCurBlock()->HasImplicitReturnType = true;
15448 
15449   // Enter a new evaluation context to insulate the block from any
15450   // cleanups from the enclosing full-expression.
15451   PushExpressionEvaluationContext(
15452       ExpressionEvaluationContext::PotentiallyEvaluated);
15453 }
15454 
15455 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15456                                Scope *CurScope) {
15457   assert(ParamInfo.getIdentifier() == nullptr &&
15458          "block-id should have no identifier!");
15459   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15460   BlockScopeInfo *CurBlock = getCurBlock();
15461 
15462   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15463   QualType T = Sig->getType();
15464 
15465   // FIXME: We should allow unexpanded parameter packs here, but that would,
15466   // in turn, make the block expression contain unexpanded parameter packs.
15467   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15468     // Drop the parameters.
15469     FunctionProtoType::ExtProtoInfo EPI;
15470     EPI.HasTrailingReturn = false;
15471     EPI.TypeQuals.addConst();
15472     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15473     Sig = Context.getTrivialTypeSourceInfo(T);
15474   }
15475 
15476   // GetTypeForDeclarator always produces a function type for a block
15477   // literal signature.  Furthermore, it is always a FunctionProtoType
15478   // unless the function was written with a typedef.
15479   assert(T->isFunctionType() &&
15480          "GetTypeForDeclarator made a non-function block signature");
15481 
15482   // Look for an explicit signature in that function type.
15483   FunctionProtoTypeLoc ExplicitSignature;
15484 
15485   if ((ExplicitSignature = Sig->getTypeLoc()
15486                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15487 
15488     // Check whether that explicit signature was synthesized by
15489     // GetTypeForDeclarator.  If so, don't save that as part of the
15490     // written signature.
15491     if (ExplicitSignature.getLocalRangeBegin() ==
15492         ExplicitSignature.getLocalRangeEnd()) {
15493       // This would be much cheaper if we stored TypeLocs instead of
15494       // TypeSourceInfos.
15495       TypeLoc Result = ExplicitSignature.getReturnLoc();
15496       unsigned Size = Result.getFullDataSize();
15497       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15498       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15499 
15500       ExplicitSignature = FunctionProtoTypeLoc();
15501     }
15502   }
15503 
15504   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15505   CurBlock->FunctionType = T;
15506 
15507   const auto *Fn = T->castAs<FunctionType>();
15508   QualType RetTy = Fn->getReturnType();
15509   bool isVariadic =
15510       (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15511 
15512   CurBlock->TheDecl->setIsVariadic(isVariadic);
15513 
15514   // Context.DependentTy is used as a placeholder for a missing block
15515   // return type.  TODO:  what should we do with declarators like:
15516   //   ^ * { ... }
15517   // If the answer is "apply template argument deduction"....
15518   if (RetTy != Context.DependentTy) {
15519     CurBlock->ReturnType = RetTy;
15520     CurBlock->TheDecl->setBlockMissingReturnType(false);
15521     CurBlock->HasImplicitReturnType = false;
15522   }
15523 
15524   // Push block parameters from the declarator if we had them.
15525   SmallVector<ParmVarDecl*, 8> Params;
15526   if (ExplicitSignature) {
15527     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15528       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15529       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15530           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15531         // Diagnose this as an extension in C17 and earlier.
15532         if (!getLangOpts().C2x)
15533           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15534       }
15535       Params.push_back(Param);
15536     }
15537 
15538   // Fake up parameter variables if we have a typedef, like
15539   //   ^ fntype { ... }
15540   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15541     for (const auto &I : Fn->param_types()) {
15542       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15543           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15544       Params.push_back(Param);
15545     }
15546   }
15547 
15548   // Set the parameters on the block decl.
15549   if (!Params.empty()) {
15550     CurBlock->TheDecl->setParams(Params);
15551     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15552                              /*CheckParameterNames=*/false);
15553   }
15554 
15555   // Finally we can process decl attributes.
15556   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15557 
15558   // Put the parameter variables in scope.
15559   for (auto AI : CurBlock->TheDecl->parameters()) {
15560     AI->setOwningFunction(CurBlock->TheDecl);
15561 
15562     // If this has an identifier, add it to the scope stack.
15563     if (AI->getIdentifier()) {
15564       CheckShadow(CurBlock->TheScope, AI);
15565 
15566       PushOnScopeChains(AI, CurBlock->TheScope);
15567     }
15568   }
15569 }
15570 
15571 /// ActOnBlockError - If there is an error parsing a block, this callback
15572 /// is invoked to pop the information about the block from the action impl.
15573 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15574   // Leave the expression-evaluation context.
15575   DiscardCleanupsInEvaluationContext();
15576   PopExpressionEvaluationContext();
15577 
15578   // Pop off CurBlock, handle nested blocks.
15579   PopDeclContext();
15580   PopFunctionScopeInfo();
15581 }
15582 
15583 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15584 /// literal was successfully completed.  ^(int x){...}
15585 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15586                                     Stmt *Body, Scope *CurScope) {
15587   // If blocks are disabled, emit an error.
15588   if (!LangOpts.Blocks)
15589     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15590 
15591   // Leave the expression-evaluation context.
15592   if (hasAnyUnrecoverableErrorsInThisFunction())
15593     DiscardCleanupsInEvaluationContext();
15594   assert(!Cleanup.exprNeedsCleanups() &&
15595          "cleanups within block not correctly bound!");
15596   PopExpressionEvaluationContext();
15597 
15598   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15599   BlockDecl *BD = BSI->TheDecl;
15600 
15601   if (BSI->HasImplicitReturnType)
15602     deduceClosureReturnType(*BSI);
15603 
15604   QualType RetTy = Context.VoidTy;
15605   if (!BSI->ReturnType.isNull())
15606     RetTy = BSI->ReturnType;
15607 
15608   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15609   QualType BlockTy;
15610 
15611   // If the user wrote a function type in some form, try to use that.
15612   if (!BSI->FunctionType.isNull()) {
15613     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15614 
15615     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15616     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15617 
15618     // Turn protoless block types into nullary block types.
15619     if (isa<FunctionNoProtoType>(FTy)) {
15620       FunctionProtoType::ExtProtoInfo EPI;
15621       EPI.ExtInfo = Ext;
15622       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15623 
15624     // Otherwise, if we don't need to change anything about the function type,
15625     // preserve its sugar structure.
15626     } else if (FTy->getReturnType() == RetTy &&
15627                (!NoReturn || FTy->getNoReturnAttr())) {
15628       BlockTy = BSI->FunctionType;
15629 
15630     // Otherwise, make the minimal modifications to the function type.
15631     } else {
15632       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15633       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15634       EPI.TypeQuals = Qualifiers();
15635       EPI.ExtInfo = Ext;
15636       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15637     }
15638 
15639   // If we don't have a function type, just build one from nothing.
15640   } else {
15641     FunctionProtoType::ExtProtoInfo EPI;
15642     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15643     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15644   }
15645 
15646   DiagnoseUnusedParameters(BD->parameters());
15647   BlockTy = Context.getBlockPointerType(BlockTy);
15648 
15649   // If needed, diagnose invalid gotos and switches in the block.
15650   if (getCurFunction()->NeedsScopeChecking() &&
15651       !PP.isCodeCompletionEnabled())
15652     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15653 
15654   BD->setBody(cast<CompoundStmt>(Body));
15655 
15656   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15657     DiagnoseUnguardedAvailabilityViolations(BD);
15658 
15659   // Try to apply the named return value optimization. We have to check again
15660   // if we can do this, though, because blocks keep return statements around
15661   // to deduce an implicit return type.
15662   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15663       !BD->isDependentContext())
15664     computeNRVO(Body, BSI);
15665 
15666   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15667       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15668     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15669                           NTCUK_Destruct|NTCUK_Copy);
15670 
15671   PopDeclContext();
15672 
15673   // Set the captured variables on the block.
15674   SmallVector<BlockDecl::Capture, 4> Captures;
15675   for (Capture &Cap : BSI->Captures) {
15676     if (Cap.isInvalid() || Cap.isThisCapture())
15677       continue;
15678 
15679     VarDecl *Var = Cap.getVariable();
15680     Expr *CopyExpr = nullptr;
15681     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15682       if (const RecordType *Record =
15683               Cap.getCaptureType()->getAs<RecordType>()) {
15684         // The capture logic needs the destructor, so make sure we mark it.
15685         // Usually this is unnecessary because most local variables have
15686         // their destructors marked at declaration time, but parameters are
15687         // an exception because it's technically only the call site that
15688         // actually requires the destructor.
15689         if (isa<ParmVarDecl>(Var))
15690           FinalizeVarWithDestructor(Var, Record);
15691 
15692         // Enter a separate potentially-evaluated context while building block
15693         // initializers to isolate their cleanups from those of the block
15694         // itself.
15695         // FIXME: Is this appropriate even when the block itself occurs in an
15696         // unevaluated operand?
15697         EnterExpressionEvaluationContext EvalContext(
15698             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15699 
15700         SourceLocation Loc = Cap.getLocation();
15701 
15702         ExprResult Result = BuildDeclarationNameExpr(
15703             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15704 
15705         // According to the blocks spec, the capture of a variable from
15706         // the stack requires a const copy constructor.  This is not true
15707         // of the copy/move done to move a __block variable to the heap.
15708         if (!Result.isInvalid() &&
15709             !Result.get()->getType().isConstQualified()) {
15710           Result = ImpCastExprToType(Result.get(),
15711                                      Result.get()->getType().withConst(),
15712                                      CK_NoOp, VK_LValue);
15713         }
15714 
15715         if (!Result.isInvalid()) {
15716           Result = PerformCopyInitialization(
15717               InitializedEntity::InitializeBlock(Var->getLocation(),
15718                                                  Cap.getCaptureType()),
15719               Loc, Result.get());
15720         }
15721 
15722         // Build a full-expression copy expression if initialization
15723         // succeeded and used a non-trivial constructor.  Recover from
15724         // errors by pretending that the copy isn't necessary.
15725         if (!Result.isInvalid() &&
15726             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15727                 ->isTrivial()) {
15728           Result = MaybeCreateExprWithCleanups(Result);
15729           CopyExpr = Result.get();
15730         }
15731       }
15732     }
15733 
15734     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15735                               CopyExpr);
15736     Captures.push_back(NewCap);
15737   }
15738   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15739 
15740   // Pop the block scope now but keep it alive to the end of this function.
15741   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15742   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15743 
15744   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15745 
15746   // If the block isn't obviously global, i.e. it captures anything at
15747   // all, then we need to do a few things in the surrounding context:
15748   if (Result->getBlockDecl()->hasCaptures()) {
15749     // First, this expression has a new cleanup object.
15750     ExprCleanupObjects.push_back(Result->getBlockDecl());
15751     Cleanup.setExprNeedsCleanups(true);
15752 
15753     // It also gets a branch-protected scope if any of the captured
15754     // variables needs destruction.
15755     for (const auto &CI : Result->getBlockDecl()->captures()) {
15756       const VarDecl *var = CI.getVariable();
15757       if (var->getType().isDestructedType() != QualType::DK_none) {
15758         setFunctionHasBranchProtectedScope();
15759         break;
15760       }
15761     }
15762   }
15763 
15764   if (getCurFunction())
15765     getCurFunction()->addBlock(BD);
15766 
15767   return Result;
15768 }
15769 
15770 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15771                             SourceLocation RPLoc) {
15772   TypeSourceInfo *TInfo;
15773   GetTypeFromParser(Ty, &TInfo);
15774   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15775 }
15776 
15777 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15778                                 Expr *E, TypeSourceInfo *TInfo,
15779                                 SourceLocation RPLoc) {
15780   Expr *OrigExpr = E;
15781   bool IsMS = false;
15782 
15783   // CUDA device code does not support varargs.
15784   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15785     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15786       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15787       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15788         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15789     }
15790   }
15791 
15792   // NVPTX does not support va_arg expression.
15793   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15794       Context.getTargetInfo().getTriple().isNVPTX())
15795     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15796 
15797   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15798   // as Microsoft ABI on an actual Microsoft platform, where
15799   // __builtin_ms_va_list and __builtin_va_list are the same.)
15800   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15801       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15802     QualType MSVaListType = Context.getBuiltinMSVaListType();
15803     if (Context.hasSameType(MSVaListType, E->getType())) {
15804       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15805         return ExprError();
15806       IsMS = true;
15807     }
15808   }
15809 
15810   // Get the va_list type
15811   QualType VaListType = Context.getBuiltinVaListType();
15812   if (!IsMS) {
15813     if (VaListType->isArrayType()) {
15814       // Deal with implicit array decay; for example, on x86-64,
15815       // va_list is an array, but it's supposed to decay to
15816       // a pointer for va_arg.
15817       VaListType = Context.getArrayDecayedType(VaListType);
15818       // Make sure the input expression also decays appropriately.
15819       ExprResult Result = UsualUnaryConversions(E);
15820       if (Result.isInvalid())
15821         return ExprError();
15822       E = Result.get();
15823     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15824       // If va_list is a record type and we are compiling in C++ mode,
15825       // check the argument using reference binding.
15826       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15827           Context, Context.getLValueReferenceType(VaListType), false);
15828       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15829       if (Init.isInvalid())
15830         return ExprError();
15831       E = Init.getAs<Expr>();
15832     } else {
15833       // Otherwise, the va_list argument must be an l-value because
15834       // it is modified by va_arg.
15835       if (!E->isTypeDependent() &&
15836           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15837         return ExprError();
15838     }
15839   }
15840 
15841   if (!IsMS && !E->isTypeDependent() &&
15842       !Context.hasSameType(VaListType, E->getType()))
15843     return ExprError(
15844         Diag(E->getBeginLoc(),
15845              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15846         << OrigExpr->getType() << E->getSourceRange());
15847 
15848   if (!TInfo->getType()->isDependentType()) {
15849     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15850                             diag::err_second_parameter_to_va_arg_incomplete,
15851                             TInfo->getTypeLoc()))
15852       return ExprError();
15853 
15854     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15855                                TInfo->getType(),
15856                                diag::err_second_parameter_to_va_arg_abstract,
15857                                TInfo->getTypeLoc()))
15858       return ExprError();
15859 
15860     if (!TInfo->getType().isPODType(Context)) {
15861       Diag(TInfo->getTypeLoc().getBeginLoc(),
15862            TInfo->getType()->isObjCLifetimeType()
15863              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15864              : diag::warn_second_parameter_to_va_arg_not_pod)
15865         << TInfo->getType()
15866         << TInfo->getTypeLoc().getSourceRange();
15867     }
15868 
15869     // Check for va_arg where arguments of the given type will be promoted
15870     // (i.e. this va_arg is guaranteed to have undefined behavior).
15871     QualType PromoteType;
15872     if (TInfo->getType()->isPromotableIntegerType()) {
15873       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15874       // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
15875       // and C2x 7.16.1.1p2 says, in part:
15876       //   If type is not compatible with the type of the actual next argument
15877       //   (as promoted according to the default argument promotions), the
15878       //   behavior is undefined, except for the following cases:
15879       //     - both types are pointers to qualified or unqualified versions of
15880       //       compatible types;
15881       //     - one type is a signed integer type, the other type is the
15882       //       corresponding unsigned integer type, and the value is
15883       //       representable in both types;
15884       //     - one type is pointer to qualified or unqualified void and the
15885       //       other is a pointer to a qualified or unqualified character type.
15886       // Given that type compatibility is the primary requirement (ignoring
15887       // qualifications), you would think we could call typesAreCompatible()
15888       // directly to test this. However, in C++, that checks for *same type*,
15889       // which causes false positives when passing an enumeration type to
15890       // va_arg. Instead, get the underlying type of the enumeration and pass
15891       // that.
15892       QualType UnderlyingType = TInfo->getType();
15893       if (const auto *ET = UnderlyingType->getAs<EnumType>())
15894         UnderlyingType = ET->getDecl()->getIntegerType();
15895       if (Context.typesAreCompatible(PromoteType, UnderlyingType,
15896                                      /*CompareUnqualified*/ true))
15897         PromoteType = QualType();
15898 
15899       // If the types are still not compatible, we need to test whether the
15900       // promoted type and the underlying type are the same except for
15901       // signedness. Ask the AST for the correctly corresponding type and see
15902       // if that's compatible.
15903       if (!PromoteType.isNull() &&
15904           PromoteType->isUnsignedIntegerType() !=
15905               UnderlyingType->isUnsignedIntegerType()) {
15906         UnderlyingType =
15907             UnderlyingType->isUnsignedIntegerType()
15908                 ? Context.getCorrespondingSignedType(UnderlyingType)
15909                 : Context.getCorrespondingUnsignedType(UnderlyingType);
15910         if (Context.typesAreCompatible(PromoteType, UnderlyingType,
15911                                        /*CompareUnqualified*/ true))
15912           PromoteType = QualType();
15913       }
15914     }
15915     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15916       PromoteType = Context.DoubleTy;
15917     if (!PromoteType.isNull())
15918       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15919                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15920                           << TInfo->getType()
15921                           << PromoteType
15922                           << TInfo->getTypeLoc().getSourceRange());
15923   }
15924 
15925   QualType T = TInfo->getType().getNonLValueExprType(Context);
15926   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15927 }
15928 
15929 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15930   // The type of __null will be int or long, depending on the size of
15931   // pointers on the target.
15932   QualType Ty;
15933   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15934   if (pw == Context.getTargetInfo().getIntWidth())
15935     Ty = Context.IntTy;
15936   else if (pw == Context.getTargetInfo().getLongWidth())
15937     Ty = Context.LongTy;
15938   else if (pw == Context.getTargetInfo().getLongLongWidth())
15939     Ty = Context.LongLongTy;
15940   else {
15941     llvm_unreachable("I don't know size of pointer!");
15942   }
15943 
15944   return new (Context) GNUNullExpr(Ty, TokenLoc);
15945 }
15946 
15947 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15948                                     SourceLocation BuiltinLoc,
15949                                     SourceLocation RPLoc) {
15950   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15951 }
15952 
15953 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15954                                     SourceLocation BuiltinLoc,
15955                                     SourceLocation RPLoc,
15956                                     DeclContext *ParentContext) {
15957   return new (Context)
15958       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15959 }
15960 
15961 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15962                                         bool Diagnose) {
15963   if (!getLangOpts().ObjC)
15964     return false;
15965 
15966   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15967   if (!PT)
15968     return false;
15969   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15970 
15971   // Ignore any parens, implicit casts (should only be
15972   // array-to-pointer decays), and not-so-opaque values.  The last is
15973   // important for making this trigger for property assignments.
15974   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15975   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15976     if (OV->getSourceExpr())
15977       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15978 
15979   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15980     if (!PT->isObjCIdType() &&
15981         !(ID && ID->getIdentifier()->isStr("NSString")))
15982       return false;
15983     if (!SL->isAscii())
15984       return false;
15985 
15986     if (Diagnose) {
15987       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15988           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15989       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15990     }
15991     return true;
15992   }
15993 
15994   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15995       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15996       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15997       !SrcExpr->isNullPointerConstant(
15998           getASTContext(), Expr::NPC_NeverValueDependent)) {
15999     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
16000       return false;
16001     if (Diagnose) {
16002       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
16003           << /*number*/1
16004           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
16005       Expr *NumLit =
16006           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
16007       if (NumLit)
16008         Exp = NumLit;
16009     }
16010     return true;
16011   }
16012 
16013   return false;
16014 }
16015 
16016 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
16017                                               const Expr *SrcExpr) {
16018   if (!DstType->isFunctionPointerType() ||
16019       !SrcExpr->getType()->isFunctionType())
16020     return false;
16021 
16022   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16023   if (!DRE)
16024     return false;
16025 
16026   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16027   if (!FD)
16028     return false;
16029 
16030   return !S.checkAddressOfFunctionIsAvailable(FD,
16031                                               /*Complain=*/true,
16032                                               SrcExpr->getBeginLoc());
16033 }
16034 
16035 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16036                                     SourceLocation Loc,
16037                                     QualType DstType, QualType SrcType,
16038                                     Expr *SrcExpr, AssignmentAction Action,
16039                                     bool *Complained) {
16040   if (Complained)
16041     *Complained = false;
16042 
16043   // Decode the result (notice that AST's are still created for extensions).
16044   bool CheckInferredResultType = false;
16045   bool isInvalid = false;
16046   unsigned DiagKind = 0;
16047   ConversionFixItGenerator ConvHints;
16048   bool MayHaveConvFixit = false;
16049   bool MayHaveFunctionDiff = false;
16050   const ObjCInterfaceDecl *IFace = nullptr;
16051   const ObjCProtocolDecl *PDecl = nullptr;
16052 
16053   switch (ConvTy) {
16054   case Compatible:
16055       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16056       return false;
16057 
16058   case PointerToInt:
16059     if (getLangOpts().CPlusPlus) {
16060       DiagKind = diag::err_typecheck_convert_pointer_int;
16061       isInvalid = true;
16062     } else {
16063       DiagKind = diag::ext_typecheck_convert_pointer_int;
16064     }
16065     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16066     MayHaveConvFixit = true;
16067     break;
16068   case IntToPointer:
16069     if (getLangOpts().CPlusPlus) {
16070       DiagKind = diag::err_typecheck_convert_int_pointer;
16071       isInvalid = true;
16072     } else {
16073       DiagKind = diag::ext_typecheck_convert_int_pointer;
16074     }
16075     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16076     MayHaveConvFixit = true;
16077     break;
16078   case IncompatibleFunctionPointer:
16079     if (getLangOpts().CPlusPlus) {
16080       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16081       isInvalid = true;
16082     } else {
16083       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16084     }
16085     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16086     MayHaveConvFixit = true;
16087     break;
16088   case IncompatiblePointer:
16089     if (Action == AA_Passing_CFAudited) {
16090       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16091     } else if (getLangOpts().CPlusPlus) {
16092       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16093       isInvalid = true;
16094     } else {
16095       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16096     }
16097     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16098       SrcType->isObjCObjectPointerType();
16099     if (!CheckInferredResultType) {
16100       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16101     } else if (CheckInferredResultType) {
16102       SrcType = SrcType.getUnqualifiedType();
16103       DstType = DstType.getUnqualifiedType();
16104     }
16105     MayHaveConvFixit = true;
16106     break;
16107   case IncompatiblePointerSign:
16108     if (getLangOpts().CPlusPlus) {
16109       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16110       isInvalid = true;
16111     } else {
16112       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16113     }
16114     break;
16115   case FunctionVoidPointer:
16116     if (getLangOpts().CPlusPlus) {
16117       DiagKind = diag::err_typecheck_convert_pointer_void_func;
16118       isInvalid = true;
16119     } else {
16120       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16121     }
16122     break;
16123   case IncompatiblePointerDiscardsQualifiers: {
16124     // Perform array-to-pointer decay if necessary.
16125     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16126 
16127     isInvalid = true;
16128 
16129     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16130     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16131     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16132       DiagKind = diag::err_typecheck_incompatible_address_space;
16133       break;
16134 
16135     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16136       DiagKind = diag::err_typecheck_incompatible_ownership;
16137       break;
16138     }
16139 
16140     llvm_unreachable("unknown error case for discarding qualifiers!");
16141     // fallthrough
16142   }
16143   case CompatiblePointerDiscardsQualifiers:
16144     // If the qualifiers lost were because we were applying the
16145     // (deprecated) C++ conversion from a string literal to a char*
16146     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
16147     // Ideally, this check would be performed in
16148     // checkPointerTypesForAssignment. However, that would require a
16149     // bit of refactoring (so that the second argument is an
16150     // expression, rather than a type), which should be done as part
16151     // of a larger effort to fix checkPointerTypesForAssignment for
16152     // C++ semantics.
16153     if (getLangOpts().CPlusPlus &&
16154         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16155       return false;
16156     if (getLangOpts().CPlusPlus) {
16157       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
16158       isInvalid = true;
16159     } else {
16160       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
16161     }
16162 
16163     break;
16164   case IncompatibleNestedPointerQualifiers:
16165     if (getLangOpts().CPlusPlus) {
16166       isInvalid = true;
16167       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16168     } else {
16169       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16170     }
16171     break;
16172   case IncompatibleNestedPointerAddressSpaceMismatch:
16173     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16174     isInvalid = true;
16175     break;
16176   case IntToBlockPointer:
16177     DiagKind = diag::err_int_to_block_pointer;
16178     isInvalid = true;
16179     break;
16180   case IncompatibleBlockPointer:
16181     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16182     isInvalid = true;
16183     break;
16184   case IncompatibleObjCQualifiedId: {
16185     if (SrcType->isObjCQualifiedIdType()) {
16186       const ObjCObjectPointerType *srcOPT =
16187                 SrcType->castAs<ObjCObjectPointerType>();
16188       for (auto *srcProto : srcOPT->quals()) {
16189         PDecl = srcProto;
16190         break;
16191       }
16192       if (const ObjCInterfaceType *IFaceT =
16193             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16194         IFace = IFaceT->getDecl();
16195     }
16196     else if (DstType->isObjCQualifiedIdType()) {
16197       const ObjCObjectPointerType *dstOPT =
16198         DstType->castAs<ObjCObjectPointerType>();
16199       for (auto *dstProto : dstOPT->quals()) {
16200         PDecl = dstProto;
16201         break;
16202       }
16203       if (const ObjCInterfaceType *IFaceT =
16204             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16205         IFace = IFaceT->getDecl();
16206     }
16207     if (getLangOpts().CPlusPlus) {
16208       DiagKind = diag::err_incompatible_qualified_id;
16209       isInvalid = true;
16210     } else {
16211       DiagKind = diag::warn_incompatible_qualified_id;
16212     }
16213     break;
16214   }
16215   case IncompatibleVectors:
16216     if (getLangOpts().CPlusPlus) {
16217       DiagKind = diag::err_incompatible_vectors;
16218       isInvalid = true;
16219     } else {
16220       DiagKind = diag::warn_incompatible_vectors;
16221     }
16222     break;
16223   case IncompatibleObjCWeakRef:
16224     DiagKind = diag::err_arc_weak_unavailable_assign;
16225     isInvalid = true;
16226     break;
16227   case Incompatible:
16228     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16229       if (Complained)
16230         *Complained = true;
16231       return true;
16232     }
16233 
16234     DiagKind = diag::err_typecheck_convert_incompatible;
16235     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16236     MayHaveConvFixit = true;
16237     isInvalid = true;
16238     MayHaveFunctionDiff = true;
16239     break;
16240   }
16241 
16242   QualType FirstType, SecondType;
16243   switch (Action) {
16244   case AA_Assigning:
16245   case AA_Initializing:
16246     // The destination type comes first.
16247     FirstType = DstType;
16248     SecondType = SrcType;
16249     break;
16250 
16251   case AA_Returning:
16252   case AA_Passing:
16253   case AA_Passing_CFAudited:
16254   case AA_Converting:
16255   case AA_Sending:
16256   case AA_Casting:
16257     // The source type comes first.
16258     FirstType = SrcType;
16259     SecondType = DstType;
16260     break;
16261   }
16262 
16263   PartialDiagnostic FDiag = PDiag(DiagKind);
16264   if (Action == AA_Passing_CFAudited)
16265     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
16266   else
16267     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
16268 
16269   if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16270       DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16271     auto isPlainChar = [](const clang::Type *Type) {
16272       return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16273              Type->isSpecificBuiltinType(BuiltinType::Char_U);
16274     };
16275     FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16276               isPlainChar(SecondType->getPointeeOrArrayElementType()));
16277   }
16278 
16279   // If we can fix the conversion, suggest the FixIts.
16280   if (!ConvHints.isNull()) {
16281     for (FixItHint &H : ConvHints.Hints)
16282       FDiag << H;
16283   }
16284 
16285   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16286 
16287   if (MayHaveFunctionDiff)
16288     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16289 
16290   Diag(Loc, FDiag);
16291   if ((DiagKind == diag::warn_incompatible_qualified_id ||
16292        DiagKind == diag::err_incompatible_qualified_id) &&
16293       PDecl && IFace && !IFace->hasDefinition())
16294     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16295         << IFace << PDecl;
16296 
16297   if (SecondType == Context.OverloadTy)
16298     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16299                               FirstType, /*TakingAddress=*/true);
16300 
16301   if (CheckInferredResultType)
16302     EmitRelatedResultTypeNote(SrcExpr);
16303 
16304   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16305     EmitRelatedResultTypeNoteForReturn(DstType);
16306 
16307   if (Complained)
16308     *Complained = true;
16309   return isInvalid;
16310 }
16311 
16312 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16313                                                  llvm::APSInt *Result,
16314                                                  AllowFoldKind CanFold) {
16315   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16316   public:
16317     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16318                                              QualType T) override {
16319       return S.Diag(Loc, diag::err_ice_not_integral)
16320              << T << S.LangOpts.CPlusPlus;
16321     }
16322     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16323       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16324     }
16325   } Diagnoser;
16326 
16327   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16328 }
16329 
16330 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16331                                                  llvm::APSInt *Result,
16332                                                  unsigned DiagID,
16333                                                  AllowFoldKind CanFold) {
16334   class IDDiagnoser : public VerifyICEDiagnoser {
16335     unsigned DiagID;
16336 
16337   public:
16338     IDDiagnoser(unsigned DiagID)
16339       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16340 
16341     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16342       return S.Diag(Loc, DiagID);
16343     }
16344   } Diagnoser(DiagID);
16345 
16346   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16347 }
16348 
16349 Sema::SemaDiagnosticBuilder
16350 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
16351                                              QualType T) {
16352   return diagnoseNotICE(S, Loc);
16353 }
16354 
16355 Sema::SemaDiagnosticBuilder
16356 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
16357   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16358 }
16359 
16360 ExprResult
16361 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16362                                       VerifyICEDiagnoser &Diagnoser,
16363                                       AllowFoldKind CanFold) {
16364   SourceLocation DiagLoc = E->getBeginLoc();
16365 
16366   if (getLangOpts().CPlusPlus11) {
16367     // C++11 [expr.const]p5:
16368     //   If an expression of literal class type is used in a context where an
16369     //   integral constant expression is required, then that class type shall
16370     //   have a single non-explicit conversion function to an integral or
16371     //   unscoped enumeration type
16372     ExprResult Converted;
16373     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16374       VerifyICEDiagnoser &BaseDiagnoser;
16375     public:
16376       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16377           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16378                                 BaseDiagnoser.Suppress, true),
16379             BaseDiagnoser(BaseDiagnoser) {}
16380 
16381       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16382                                            QualType T) override {
16383         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16384       }
16385 
16386       SemaDiagnosticBuilder diagnoseIncomplete(
16387           Sema &S, SourceLocation Loc, QualType T) override {
16388         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16389       }
16390 
16391       SemaDiagnosticBuilder diagnoseExplicitConv(
16392           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16393         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16394       }
16395 
16396       SemaDiagnosticBuilder noteExplicitConv(
16397           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16398         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16399                  << ConvTy->isEnumeralType() << ConvTy;
16400       }
16401 
16402       SemaDiagnosticBuilder diagnoseAmbiguous(
16403           Sema &S, SourceLocation Loc, QualType T) override {
16404         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16405       }
16406 
16407       SemaDiagnosticBuilder noteAmbiguous(
16408           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16409         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16410                  << ConvTy->isEnumeralType() << ConvTy;
16411       }
16412 
16413       SemaDiagnosticBuilder diagnoseConversion(
16414           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16415         llvm_unreachable("conversion functions are permitted");
16416       }
16417     } ConvertDiagnoser(Diagnoser);
16418 
16419     Converted = PerformContextualImplicitConversion(DiagLoc, E,
16420                                                     ConvertDiagnoser);
16421     if (Converted.isInvalid())
16422       return Converted;
16423     E = Converted.get();
16424     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16425       return ExprError();
16426   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16427     // An ICE must be of integral or unscoped enumeration type.
16428     if (!Diagnoser.Suppress)
16429       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16430           << E->getSourceRange();
16431     return ExprError();
16432   }
16433 
16434   ExprResult RValueExpr = DefaultLvalueConversion(E);
16435   if (RValueExpr.isInvalid())
16436     return ExprError();
16437 
16438   E = RValueExpr.get();
16439 
16440   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16441   // in the non-ICE case.
16442   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16443     if (Result)
16444       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16445     if (!isa<ConstantExpr>(E))
16446       E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
16447                  : ConstantExpr::Create(Context, E);
16448     return E;
16449   }
16450 
16451   Expr::EvalResult EvalResult;
16452   SmallVector<PartialDiagnosticAt, 8> Notes;
16453   EvalResult.Diag = &Notes;
16454 
16455   // Try to evaluate the expression, and produce diagnostics explaining why it's
16456   // not a constant expression as a side-effect.
16457   bool Folded =
16458       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16459       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16460 
16461   if (!isa<ConstantExpr>(E))
16462     E = ConstantExpr::Create(Context, E, EvalResult.Val);
16463 
16464   // In C++11, we can rely on diagnostics being produced for any expression
16465   // which is not a constant expression. If no diagnostics were produced, then
16466   // this is a constant expression.
16467   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16468     if (Result)
16469       *Result = EvalResult.Val.getInt();
16470     return E;
16471   }
16472 
16473   // If our only note is the usual "invalid subexpression" note, just point
16474   // the caret at its location rather than producing an essentially
16475   // redundant note.
16476   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16477         diag::note_invalid_subexpr_in_const_expr) {
16478     DiagLoc = Notes[0].first;
16479     Notes.clear();
16480   }
16481 
16482   if (!Folded || !CanFold) {
16483     if (!Diagnoser.Suppress) {
16484       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16485       for (const PartialDiagnosticAt &Note : Notes)
16486         Diag(Note.first, Note.second);
16487     }
16488 
16489     return ExprError();
16490   }
16491 
16492   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16493   for (const PartialDiagnosticAt &Note : Notes)
16494     Diag(Note.first, Note.second);
16495 
16496   if (Result)
16497     *Result = EvalResult.Val.getInt();
16498   return E;
16499 }
16500 
16501 namespace {
16502   // Handle the case where we conclude a expression which we speculatively
16503   // considered to be unevaluated is actually evaluated.
16504   class TransformToPE : public TreeTransform<TransformToPE> {
16505     typedef TreeTransform<TransformToPE> BaseTransform;
16506 
16507   public:
16508     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16509 
16510     // Make sure we redo semantic analysis
16511     bool AlwaysRebuild() { return true; }
16512     bool ReplacingOriginal() { return true; }
16513 
16514     // We need to special-case DeclRefExprs referring to FieldDecls which
16515     // are not part of a member pointer formation; normal TreeTransforming
16516     // doesn't catch this case because of the way we represent them in the AST.
16517     // FIXME: This is a bit ugly; is it really the best way to handle this
16518     // case?
16519     //
16520     // Error on DeclRefExprs referring to FieldDecls.
16521     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16522       if (isa<FieldDecl>(E->getDecl()) &&
16523           !SemaRef.isUnevaluatedContext())
16524         return SemaRef.Diag(E->getLocation(),
16525                             diag::err_invalid_non_static_member_use)
16526             << E->getDecl() << E->getSourceRange();
16527 
16528       return BaseTransform::TransformDeclRefExpr(E);
16529     }
16530 
16531     // Exception: filter out member pointer formation
16532     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16533       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16534         return E;
16535 
16536       return BaseTransform::TransformUnaryOperator(E);
16537     }
16538 
16539     // The body of a lambda-expression is in a separate expression evaluation
16540     // context so never needs to be transformed.
16541     // FIXME: Ideally we wouldn't transform the closure type either, and would
16542     // just recreate the capture expressions and lambda expression.
16543     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16544       return SkipLambdaBody(E, Body);
16545     }
16546   };
16547 }
16548 
16549 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16550   assert(isUnevaluatedContext() &&
16551          "Should only transform unevaluated expressions");
16552   ExprEvalContexts.back().Context =
16553       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16554   if (isUnevaluatedContext())
16555     return E;
16556   return TransformToPE(*this).TransformExpr(E);
16557 }
16558 
16559 void
16560 Sema::PushExpressionEvaluationContext(
16561     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16562     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16563   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16564                                 LambdaContextDecl, ExprContext);
16565   Cleanup.reset();
16566   if (!MaybeODRUseExprs.empty())
16567     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16568 }
16569 
16570 void
16571 Sema::PushExpressionEvaluationContext(
16572     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16573     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16574   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16575   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16576 }
16577 
16578 namespace {
16579 
16580 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16581   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16582   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16583     if (E->getOpcode() == UO_Deref)
16584       return CheckPossibleDeref(S, E->getSubExpr());
16585   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16586     return CheckPossibleDeref(S, E->getBase());
16587   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16588     return CheckPossibleDeref(S, E->getBase());
16589   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16590     QualType Inner;
16591     QualType Ty = E->getType();
16592     if (const auto *Ptr = Ty->getAs<PointerType>())
16593       Inner = Ptr->getPointeeType();
16594     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16595       Inner = Arr->getElementType();
16596     else
16597       return nullptr;
16598 
16599     if (Inner->hasAttr(attr::NoDeref))
16600       return E;
16601   }
16602   return nullptr;
16603 }
16604 
16605 } // namespace
16606 
16607 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16608   for (const Expr *E : Rec.PossibleDerefs) {
16609     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16610     if (DeclRef) {
16611       const ValueDecl *Decl = DeclRef->getDecl();
16612       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16613           << Decl->getName() << E->getSourceRange();
16614       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16615     } else {
16616       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16617           << E->getSourceRange();
16618     }
16619   }
16620   Rec.PossibleDerefs.clear();
16621 }
16622 
16623 /// Check whether E, which is either a discarded-value expression or an
16624 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16625 /// and if so, remove it from the list of volatile-qualified assignments that
16626 /// we are going to warn are deprecated.
16627 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16628   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16629     return;
16630 
16631   // Note: ignoring parens here is not justified by the standard rules, but
16632   // ignoring parentheses seems like a more reasonable approach, and this only
16633   // drives a deprecation warning so doesn't affect conformance.
16634   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16635     if (BO->getOpcode() == BO_Assign) {
16636       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16637       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16638                  LHSs.end());
16639     }
16640   }
16641 }
16642 
16643 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16644   if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
16645       !Decl->isConsteval() || isConstantEvaluated() ||
16646       RebuildingImmediateInvocation || isImmediateFunctionContext())
16647     return E;
16648 
16649   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16650   /// It's OK if this fails; we'll also remove this in
16651   /// HandleImmediateInvocations, but catching it here allows us to avoid
16652   /// walking the AST looking for it in simple cases.
16653   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16654     if (auto *DeclRef =
16655             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16656       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16657 
16658   E = MaybeCreateExprWithCleanups(E);
16659 
16660   ConstantExpr *Res = ConstantExpr::Create(
16661       getASTContext(), E.get(),
16662       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16663                                    getASTContext()),
16664       /*IsImmediateInvocation*/ true);
16665   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16666   return Res;
16667 }
16668 
16669 static void EvaluateAndDiagnoseImmediateInvocation(
16670     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16671   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16672   Expr::EvalResult Eval;
16673   Eval.Diag = &Notes;
16674   ConstantExpr *CE = Candidate.getPointer();
16675   bool Result = CE->EvaluateAsConstantExpr(
16676       Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
16677   if (!Result || !Notes.empty()) {
16678     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16679     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16680       InnerExpr = FunctionalCast->getSubExpr();
16681     FunctionDecl *FD = nullptr;
16682     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16683       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16684     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16685       FD = Call->getConstructor();
16686     else
16687       llvm_unreachable("unhandled decl kind");
16688     assert(FD->isConsteval());
16689     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16690     for (auto &Note : Notes)
16691       SemaRef.Diag(Note.first, Note.second);
16692     return;
16693   }
16694   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16695 }
16696 
16697 static void RemoveNestedImmediateInvocation(
16698     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16699     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16700   struct ComplexRemove : TreeTransform<ComplexRemove> {
16701     using Base = TreeTransform<ComplexRemove>;
16702     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16703     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16704     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16705         CurrentII;
16706     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16707                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16708                   SmallVector<Sema::ImmediateInvocationCandidate,
16709                               4>::reverse_iterator Current)
16710         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16711     void RemoveImmediateInvocation(ConstantExpr* E) {
16712       auto It = std::find_if(CurrentII, IISet.rend(),
16713                              [E](Sema::ImmediateInvocationCandidate Elem) {
16714                                return Elem.getPointer() == E;
16715                              });
16716       assert(It != IISet.rend() &&
16717              "ConstantExpr marked IsImmediateInvocation should "
16718              "be present");
16719       It->setInt(1); // Mark as deleted
16720     }
16721     ExprResult TransformConstantExpr(ConstantExpr *E) {
16722       if (!E->isImmediateInvocation())
16723         return Base::TransformConstantExpr(E);
16724       RemoveImmediateInvocation(E);
16725       return Base::TransformExpr(E->getSubExpr());
16726     }
16727     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16728     /// we need to remove its DeclRefExpr from the DRSet.
16729     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16730       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16731       return Base::TransformCXXOperatorCallExpr(E);
16732     }
16733     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16734     /// here.
16735     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16736       if (!Init)
16737         return Init;
16738       /// ConstantExpr are the first layer of implicit node to be removed so if
16739       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16740       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16741         if (CE->isImmediateInvocation())
16742           RemoveImmediateInvocation(CE);
16743       return Base::TransformInitializer(Init, NotCopyInit);
16744     }
16745     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16746       DRSet.erase(E);
16747       return E;
16748     }
16749     bool AlwaysRebuild() { return false; }
16750     bool ReplacingOriginal() { return true; }
16751     bool AllowSkippingCXXConstructExpr() {
16752       bool Res = AllowSkippingFirstCXXConstructExpr;
16753       AllowSkippingFirstCXXConstructExpr = true;
16754       return Res;
16755     }
16756     bool AllowSkippingFirstCXXConstructExpr = true;
16757   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16758                 Rec.ImmediateInvocationCandidates, It);
16759 
16760   /// CXXConstructExpr with a single argument are getting skipped by
16761   /// TreeTransform in some situtation because they could be implicit. This
16762   /// can only occur for the top-level CXXConstructExpr because it is used
16763   /// nowhere in the expression being transformed therefore will not be rebuilt.
16764   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16765   /// skipping the first CXXConstructExpr.
16766   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16767     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16768 
16769   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16770   assert(Res.isUsable());
16771   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16772   It->getPointer()->setSubExpr(Res.get());
16773 }
16774 
16775 static void
16776 HandleImmediateInvocations(Sema &SemaRef,
16777                            Sema::ExpressionEvaluationContextRecord &Rec) {
16778   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16779        Rec.ReferenceToConsteval.size() == 0) ||
16780       SemaRef.RebuildingImmediateInvocation)
16781     return;
16782 
16783   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16784   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16785   /// need to remove ReferenceToConsteval in the immediate invocation.
16786   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16787 
16788     /// Prevent sema calls during the tree transform from adding pointers that
16789     /// are already in the sets.
16790     llvm::SaveAndRestore<bool> DisableIITracking(
16791         SemaRef.RebuildingImmediateInvocation, true);
16792 
16793     /// Prevent diagnostic during tree transfrom as they are duplicates
16794     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16795 
16796     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16797          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16798       if (!It->getInt())
16799         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16800   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16801              Rec.ReferenceToConsteval.size()) {
16802     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16803       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16804       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16805       bool VisitDeclRefExpr(DeclRefExpr *E) {
16806         DRSet.erase(E);
16807         return DRSet.size();
16808       }
16809     } Visitor(Rec.ReferenceToConsteval);
16810     Visitor.TraverseStmt(
16811         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16812   }
16813   for (auto CE : Rec.ImmediateInvocationCandidates)
16814     if (!CE.getInt())
16815       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16816   for (auto DR : Rec.ReferenceToConsteval) {
16817     auto *FD = cast<FunctionDecl>(DR->getDecl());
16818     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16819         << FD;
16820     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16821   }
16822 }
16823 
16824 void Sema::PopExpressionEvaluationContext() {
16825   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16826   unsigned NumTypos = Rec.NumTypos;
16827 
16828   if (!Rec.Lambdas.empty()) {
16829     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16830     if (!getLangOpts().CPlusPlus20 &&
16831         (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
16832          Rec.isUnevaluated() ||
16833          (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
16834       unsigned D;
16835       if (Rec.isUnevaluated()) {
16836         // C++11 [expr.prim.lambda]p2:
16837         //   A lambda-expression shall not appear in an unevaluated operand
16838         //   (Clause 5).
16839         D = diag::err_lambda_unevaluated_operand;
16840       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16841         // C++1y [expr.const]p2:
16842         //   A conditional-expression e is a core constant expression unless the
16843         //   evaluation of e, following the rules of the abstract machine, would
16844         //   evaluate [...] a lambda-expression.
16845         D = diag::err_lambda_in_constant_expression;
16846       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16847         // C++17 [expr.prim.lamda]p2:
16848         // A lambda-expression shall not appear [...] in a template-argument.
16849         D = diag::err_lambda_in_invalid_context;
16850       } else
16851         llvm_unreachable("Couldn't infer lambda error message.");
16852 
16853       for (const auto *L : Rec.Lambdas)
16854         Diag(L->getBeginLoc(), D);
16855     }
16856   }
16857 
16858   WarnOnPendingNoDerefs(Rec);
16859   HandleImmediateInvocations(*this, Rec);
16860 
16861   // Warn on any volatile-qualified simple-assignments that are not discarded-
16862   // value expressions nor unevaluated operands (those cases get removed from
16863   // this list by CheckUnusedVolatileAssignment).
16864   for (auto *BO : Rec.VolatileAssignmentLHSs)
16865     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16866         << BO->getType();
16867 
16868   // When are coming out of an unevaluated context, clear out any
16869   // temporaries that we may have created as part of the evaluation of
16870   // the expression in that context: they aren't relevant because they
16871   // will never be constructed.
16872   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16873     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16874                              ExprCleanupObjects.end());
16875     Cleanup = Rec.ParentCleanup;
16876     CleanupVarDeclMarking();
16877     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16878   // Otherwise, merge the contexts together.
16879   } else {
16880     Cleanup.mergeFrom(Rec.ParentCleanup);
16881     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16882                             Rec.SavedMaybeODRUseExprs.end());
16883   }
16884 
16885   // Pop the current expression evaluation context off the stack.
16886   ExprEvalContexts.pop_back();
16887 
16888   // The global expression evaluation context record is never popped.
16889   ExprEvalContexts.back().NumTypos += NumTypos;
16890 }
16891 
16892 void Sema::DiscardCleanupsInEvaluationContext() {
16893   ExprCleanupObjects.erase(
16894          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16895          ExprCleanupObjects.end());
16896   Cleanup.reset();
16897   MaybeODRUseExprs.clear();
16898 }
16899 
16900 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16901   ExprResult Result = CheckPlaceholderExpr(E);
16902   if (Result.isInvalid())
16903     return ExprError();
16904   E = Result.get();
16905   if (!E->getType()->isVariablyModifiedType())
16906     return E;
16907   return TransformToPotentiallyEvaluated(E);
16908 }
16909 
16910 /// Are we in a context that is potentially constant evaluated per C++20
16911 /// [expr.const]p12?
16912 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16913   /// C++2a [expr.const]p12:
16914   //   An expression or conversion is potentially constant evaluated if it is
16915   switch (SemaRef.ExprEvalContexts.back().Context) {
16916     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16917     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
16918 
16919       // -- a manifestly constant-evaluated expression,
16920     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16921     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16922     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16923       // -- a potentially-evaluated expression,
16924     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16925       // -- an immediate subexpression of a braced-init-list,
16926 
16927       // -- [FIXME] an expression of the form & cast-expression that occurs
16928       //    within a templated entity
16929       // -- a subexpression of one of the above that is not a subexpression of
16930       // a nested unevaluated operand.
16931       return true;
16932 
16933     case Sema::ExpressionEvaluationContext::Unevaluated:
16934     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16935       // Expressions in this context are never evaluated.
16936       return false;
16937   }
16938   llvm_unreachable("Invalid context");
16939 }
16940 
16941 /// Return true if this function has a calling convention that requires mangling
16942 /// in the size of the parameter pack.
16943 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16944   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16945   // we don't need parameter type sizes.
16946   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16947   if (!TT.isOSWindows() || !TT.isX86())
16948     return false;
16949 
16950   // If this is C++ and this isn't an extern "C" function, parameters do not
16951   // need to be complete. In this case, C++ mangling will apply, which doesn't
16952   // use the size of the parameters.
16953   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16954     return false;
16955 
16956   // Stdcall, fastcall, and vectorcall need this special treatment.
16957   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16958   switch (CC) {
16959   case CC_X86StdCall:
16960   case CC_X86FastCall:
16961   case CC_X86VectorCall:
16962     return true;
16963   default:
16964     break;
16965   }
16966   return false;
16967 }
16968 
16969 /// Require that all of the parameter types of function be complete. Normally,
16970 /// parameter types are only required to be complete when a function is called
16971 /// or defined, but to mangle functions with certain calling conventions, the
16972 /// mangler needs to know the size of the parameter list. In this situation,
16973 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16974 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16975 /// result in a linker error. Clang doesn't implement this behavior, and instead
16976 /// attempts to error at compile time.
16977 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16978                                                   SourceLocation Loc) {
16979   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16980     FunctionDecl *FD;
16981     ParmVarDecl *Param;
16982 
16983   public:
16984     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16985         : FD(FD), Param(Param) {}
16986 
16987     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16988       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16989       StringRef CCName;
16990       switch (CC) {
16991       case CC_X86StdCall:
16992         CCName = "stdcall";
16993         break;
16994       case CC_X86FastCall:
16995         CCName = "fastcall";
16996         break;
16997       case CC_X86VectorCall:
16998         CCName = "vectorcall";
16999         break;
17000       default:
17001         llvm_unreachable("CC does not need mangling");
17002       }
17003 
17004       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17005           << Param->getDeclName() << FD->getDeclName() << CCName;
17006     }
17007   };
17008 
17009   for (ParmVarDecl *Param : FD->parameters()) {
17010     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17011     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17012   }
17013 }
17014 
17015 namespace {
17016 enum class OdrUseContext {
17017   /// Declarations in this context are not odr-used.
17018   None,
17019   /// Declarations in this context are formally odr-used, but this is a
17020   /// dependent context.
17021   Dependent,
17022   /// Declarations in this context are odr-used but not actually used (yet).
17023   FormallyOdrUsed,
17024   /// Declarations in this context are used.
17025   Used
17026 };
17027 }
17028 
17029 /// Are we within a context in which references to resolved functions or to
17030 /// variables result in odr-use?
17031 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17032   OdrUseContext Result;
17033 
17034   switch (SemaRef.ExprEvalContexts.back().Context) {
17035     case Sema::ExpressionEvaluationContext::Unevaluated:
17036     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17037     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17038       return OdrUseContext::None;
17039 
17040     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17041     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17042     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17043       Result = OdrUseContext::Used;
17044       break;
17045 
17046     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17047       Result = OdrUseContext::FormallyOdrUsed;
17048       break;
17049 
17050     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17051       // A default argument formally results in odr-use, but doesn't actually
17052       // result in a use in any real sense until it itself is used.
17053       Result = OdrUseContext::FormallyOdrUsed;
17054       break;
17055   }
17056 
17057   if (SemaRef.CurContext->isDependentContext())
17058     return OdrUseContext::Dependent;
17059 
17060   return Result;
17061 }
17062 
17063 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17064   if (!Func->isConstexpr())
17065     return false;
17066 
17067   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17068     return true;
17069   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17070   return CCD && CCD->getInheritedConstructor();
17071 }
17072 
17073 /// Mark a function referenced, and check whether it is odr-used
17074 /// (C++ [basic.def.odr]p2, C99 6.9p3)
17075 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17076                                   bool MightBeOdrUse) {
17077   assert(Func && "No function?");
17078 
17079   Func->setReferenced();
17080 
17081   // Recursive functions aren't really used until they're used from some other
17082   // context.
17083   bool IsRecursiveCall = CurContext == Func;
17084 
17085   // C++11 [basic.def.odr]p3:
17086   //   A function whose name appears as a potentially-evaluated expression is
17087   //   odr-used if it is the unique lookup result or the selected member of a
17088   //   set of overloaded functions [...].
17089   //
17090   // We (incorrectly) mark overload resolution as an unevaluated context, so we
17091   // can just check that here.
17092   OdrUseContext OdrUse =
17093       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17094   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17095     OdrUse = OdrUseContext::FormallyOdrUsed;
17096 
17097   // Trivial default constructors and destructors are never actually used.
17098   // FIXME: What about other special members?
17099   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17100       OdrUse == OdrUseContext::Used) {
17101     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17102       if (Constructor->isDefaultConstructor())
17103         OdrUse = OdrUseContext::FormallyOdrUsed;
17104     if (isa<CXXDestructorDecl>(Func))
17105       OdrUse = OdrUseContext::FormallyOdrUsed;
17106   }
17107 
17108   // C++20 [expr.const]p12:
17109   //   A function [...] is needed for constant evaluation if it is [...] a
17110   //   constexpr function that is named by an expression that is potentially
17111   //   constant evaluated
17112   bool NeededForConstantEvaluation =
17113       isPotentiallyConstantEvaluatedContext(*this) &&
17114       isImplicitlyDefinableConstexprFunction(Func);
17115 
17116   // Determine whether we require a function definition to exist, per
17117   // C++11 [temp.inst]p3:
17118   //   Unless a function template specialization has been explicitly
17119   //   instantiated or explicitly specialized, the function template
17120   //   specialization is implicitly instantiated when the specialization is
17121   //   referenced in a context that requires a function definition to exist.
17122   // C++20 [temp.inst]p7:
17123   //   The existence of a definition of a [...] function is considered to
17124   //   affect the semantics of the program if the [...] function is needed for
17125   //   constant evaluation by an expression
17126   // C++20 [basic.def.odr]p10:
17127   //   Every program shall contain exactly one definition of every non-inline
17128   //   function or variable that is odr-used in that program outside of a
17129   //   discarded statement
17130   // C++20 [special]p1:
17131   //   The implementation will implicitly define [defaulted special members]
17132   //   if they are odr-used or needed for constant evaluation.
17133   //
17134   // Note that we skip the implicit instantiation of templates that are only
17135   // used in unused default arguments or by recursive calls to themselves.
17136   // This is formally non-conforming, but seems reasonable in practice.
17137   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
17138                                              NeededForConstantEvaluation);
17139 
17140   // C++14 [temp.expl.spec]p6:
17141   //   If a template [...] is explicitly specialized then that specialization
17142   //   shall be declared before the first use of that specialization that would
17143   //   cause an implicit instantiation to take place, in every translation unit
17144   //   in which such a use occurs
17145   if (NeedDefinition &&
17146       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17147        Func->getMemberSpecializationInfo()))
17148     checkSpecializationVisibility(Loc, Func);
17149 
17150   if (getLangOpts().CUDA)
17151     CheckCUDACall(Loc, Func);
17152 
17153   if (getLangOpts().SYCLIsDevice)
17154     checkSYCLDeviceFunction(Loc, Func);
17155 
17156   // If we need a definition, try to create one.
17157   if (NeedDefinition && !Func->getBody()) {
17158     runWithSufficientStackSpace(Loc, [&] {
17159       if (CXXConstructorDecl *Constructor =
17160               dyn_cast<CXXConstructorDecl>(Func)) {
17161         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17162         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17163           if (Constructor->isDefaultConstructor()) {
17164             if (Constructor->isTrivial() &&
17165                 !Constructor->hasAttr<DLLExportAttr>())
17166               return;
17167             DefineImplicitDefaultConstructor(Loc, Constructor);
17168           } else if (Constructor->isCopyConstructor()) {
17169             DefineImplicitCopyConstructor(Loc, Constructor);
17170           } else if (Constructor->isMoveConstructor()) {
17171             DefineImplicitMoveConstructor(Loc, Constructor);
17172           }
17173         } else if (Constructor->getInheritedConstructor()) {
17174           DefineInheritingConstructor(Loc, Constructor);
17175         }
17176       } else if (CXXDestructorDecl *Destructor =
17177                      dyn_cast<CXXDestructorDecl>(Func)) {
17178         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17179         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17180           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17181             return;
17182           DefineImplicitDestructor(Loc, Destructor);
17183         }
17184         if (Destructor->isVirtual() && getLangOpts().AppleKext)
17185           MarkVTableUsed(Loc, Destructor->getParent());
17186       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17187         if (MethodDecl->isOverloadedOperator() &&
17188             MethodDecl->getOverloadedOperator() == OO_Equal) {
17189           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17190           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17191             if (MethodDecl->isCopyAssignmentOperator())
17192               DefineImplicitCopyAssignment(Loc, MethodDecl);
17193             else if (MethodDecl->isMoveAssignmentOperator())
17194               DefineImplicitMoveAssignment(Loc, MethodDecl);
17195           }
17196         } else if (isa<CXXConversionDecl>(MethodDecl) &&
17197                    MethodDecl->getParent()->isLambda()) {
17198           CXXConversionDecl *Conversion =
17199               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17200           if (Conversion->isLambdaToBlockPointerConversion())
17201             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17202           else
17203             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17204         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17205           MarkVTableUsed(Loc, MethodDecl->getParent());
17206       }
17207 
17208       if (Func->isDefaulted() && !Func->isDeleted()) {
17209         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17210         if (DCK != DefaultedComparisonKind::None)
17211           DefineDefaultedComparison(Loc, Func, DCK);
17212       }
17213 
17214       // Implicit instantiation of function templates and member functions of
17215       // class templates.
17216       if (Func->isImplicitlyInstantiable()) {
17217         TemplateSpecializationKind TSK =
17218             Func->getTemplateSpecializationKindForInstantiation();
17219         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17220         bool FirstInstantiation = PointOfInstantiation.isInvalid();
17221         if (FirstInstantiation) {
17222           PointOfInstantiation = Loc;
17223           if (auto *MSI = Func->getMemberSpecializationInfo())
17224             MSI->setPointOfInstantiation(Loc);
17225             // FIXME: Notify listener.
17226           else
17227             Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17228         } else if (TSK != TSK_ImplicitInstantiation) {
17229           // Use the point of use as the point of instantiation, instead of the
17230           // point of explicit instantiation (which we track as the actual point
17231           // of instantiation). This gives better backtraces in diagnostics.
17232           PointOfInstantiation = Loc;
17233         }
17234 
17235         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17236             Func->isConstexpr()) {
17237           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17238               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17239               CodeSynthesisContexts.size())
17240             PendingLocalImplicitInstantiations.push_back(
17241                 std::make_pair(Func, PointOfInstantiation));
17242           else if (Func->isConstexpr())
17243             // Do not defer instantiations of constexpr functions, to avoid the
17244             // expression evaluator needing to call back into Sema if it sees a
17245             // call to such a function.
17246             InstantiateFunctionDefinition(PointOfInstantiation, Func);
17247           else {
17248             Func->setInstantiationIsPending(true);
17249             PendingInstantiations.push_back(
17250                 std::make_pair(Func, PointOfInstantiation));
17251             // Notify the consumer that a function was implicitly instantiated.
17252             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17253           }
17254         }
17255       } else {
17256         // Walk redefinitions, as some of them may be instantiable.
17257         for (auto i : Func->redecls()) {
17258           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17259             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17260         }
17261       }
17262     });
17263   }
17264 
17265   // C++14 [except.spec]p17:
17266   //   An exception-specification is considered to be needed when:
17267   //   - the function is odr-used or, if it appears in an unevaluated operand,
17268   //     would be odr-used if the expression were potentially-evaluated;
17269   //
17270   // Note, we do this even if MightBeOdrUse is false. That indicates that the
17271   // function is a pure virtual function we're calling, and in that case the
17272   // function was selected by overload resolution and we need to resolve its
17273   // exception specification for a different reason.
17274   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17275   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
17276     ResolveExceptionSpec(Loc, FPT);
17277 
17278   // If this is the first "real" use, act on that.
17279   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
17280     // Keep track of used but undefined functions.
17281     if (!Func->isDefined()) {
17282       if (mightHaveNonExternalLinkage(Func))
17283         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17284       else if (Func->getMostRecentDecl()->isInlined() &&
17285                !LangOpts.GNUInline &&
17286                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
17287         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17288       else if (isExternalWithNoLinkageType(Func))
17289         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17290     }
17291 
17292     // Some x86 Windows calling conventions mangle the size of the parameter
17293     // pack into the name. Computing the size of the parameters requires the
17294     // parameter types to be complete. Check that now.
17295     if (funcHasParameterSizeMangling(*this, Func))
17296       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
17297 
17298     // In the MS C++ ABI, the compiler emits destructor variants where they are
17299     // used. If the destructor is used here but defined elsewhere, mark the
17300     // virtual base destructors referenced. If those virtual base destructors
17301     // are inline, this will ensure they are defined when emitting the complete
17302     // destructor variant. This checking may be redundant if the destructor is
17303     // provided later in this TU.
17304     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17305       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
17306         CXXRecordDecl *Parent = Dtor->getParent();
17307         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
17308           CheckCompleteDestructorVariant(Loc, Dtor);
17309       }
17310     }
17311 
17312     Func->markUsed(Context);
17313   }
17314 }
17315 
17316 /// Directly mark a variable odr-used. Given a choice, prefer to use
17317 /// MarkVariableReferenced since it does additional checks and then
17318 /// calls MarkVarDeclODRUsed.
17319 /// If the variable must be captured:
17320 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
17321 ///  - else capture it in the DeclContext that maps to the
17322 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
17323 static void
17324 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
17325                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
17326   // Keep track of used but undefined variables.
17327   // FIXME: We shouldn't suppress this warning for static data members.
17328   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
17329       (!Var->isExternallyVisible() || Var->isInline() ||
17330        SemaRef.isExternalWithNoLinkageType(Var)) &&
17331       !(Var->isStaticDataMember() && Var->hasInit())) {
17332     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
17333     if (old.isInvalid())
17334       old = Loc;
17335   }
17336   QualType CaptureType, DeclRefType;
17337   if (SemaRef.LangOpts.OpenMP)
17338     SemaRef.tryCaptureOpenMPLambdas(Var);
17339   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
17340     /*EllipsisLoc*/ SourceLocation(),
17341     /*BuildAndDiagnose*/ true,
17342     CaptureType, DeclRefType,
17343     FunctionScopeIndexToStopAt);
17344 
17345   if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) {
17346     auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
17347     auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
17348     auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
17349     if (VarTarget == Sema::CVT_Host &&
17350         (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
17351          UserTarget == Sema::CFT_Global)) {
17352       // Diagnose ODR-use of host global variables in device functions.
17353       // Reference of device global variables in host functions is allowed
17354       // through shadow variables therefore it is not diagnosed.
17355       if (SemaRef.LangOpts.CUDAIsDevice) {
17356         SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
17357             << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
17358         SemaRef.targetDiag(Var->getLocation(),
17359                            Var->getType().isConstQualified()
17360                                ? diag::note_cuda_const_var_unpromoted
17361                                : diag::note_cuda_host_var);
17362       }
17363     } else if (VarTarget == Sema::CVT_Device &&
17364                (UserTarget == Sema::CFT_Host ||
17365                 UserTarget == Sema::CFT_HostDevice) &&
17366                !Var->hasExternalStorage()) {
17367       // Record a CUDA/HIP device side variable if it is ODR-used
17368       // by host code. This is done conservatively, when the variable is
17369       // referenced in any of the following contexts:
17370       //   - a non-function context
17371       //   - a host function
17372       //   - a host device function
17373       // This makes the ODR-use of the device side variable by host code to
17374       // be visible in the device compilation for the compiler to be able to
17375       // emit template variables instantiated by host code only and to
17376       // externalize the static device side variable ODR-used by host code.
17377       SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
17378     }
17379   }
17380 
17381   Var->markUsed(SemaRef.Context);
17382 }
17383 
17384 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
17385                                              SourceLocation Loc,
17386                                              unsigned CapturingScopeIndex) {
17387   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
17388 }
17389 
17390 static void
17391 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
17392                                    ValueDecl *var, DeclContext *DC) {
17393   DeclContext *VarDC = var->getDeclContext();
17394 
17395   //  If the parameter still belongs to the translation unit, then
17396   //  we're actually just using one parameter in the declaration of
17397   //  the next.
17398   if (isa<ParmVarDecl>(var) &&
17399       isa<TranslationUnitDecl>(VarDC))
17400     return;
17401 
17402   // For C code, don't diagnose about capture if we're not actually in code
17403   // right now; it's impossible to write a non-constant expression outside of
17404   // function context, so we'll get other (more useful) diagnostics later.
17405   //
17406   // For C++, things get a bit more nasty... it would be nice to suppress this
17407   // diagnostic for certain cases like using a local variable in an array bound
17408   // for a member of a local class, but the correct predicate is not obvious.
17409   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
17410     return;
17411 
17412   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
17413   unsigned ContextKind = 3; // unknown
17414   if (isa<CXXMethodDecl>(VarDC) &&
17415       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
17416     ContextKind = 2;
17417   } else if (isa<FunctionDecl>(VarDC)) {
17418     ContextKind = 0;
17419   } else if (isa<BlockDecl>(VarDC)) {
17420     ContextKind = 1;
17421   }
17422 
17423   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
17424     << var << ValueKind << ContextKind << VarDC;
17425   S.Diag(var->getLocation(), diag::note_entity_declared_at)
17426       << var;
17427 
17428   // FIXME: Add additional diagnostic info about class etc. which prevents
17429   // capture.
17430 }
17431 
17432 
17433 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17434                                       bool &SubCapturesAreNested,
17435                                       QualType &CaptureType,
17436                                       QualType &DeclRefType) {
17437    // Check whether we've already captured it.
17438   if (CSI->CaptureMap.count(Var)) {
17439     // If we found a capture, any subcaptures are nested.
17440     SubCapturesAreNested = true;
17441 
17442     // Retrieve the capture type for this variable.
17443     CaptureType = CSI->getCapture(Var).getCaptureType();
17444 
17445     // Compute the type of an expression that refers to this variable.
17446     DeclRefType = CaptureType.getNonReferenceType();
17447 
17448     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17449     // are mutable in the sense that user can change their value - they are
17450     // private instances of the captured declarations.
17451     const Capture &Cap = CSI->getCapture(Var);
17452     if (Cap.isCopyCapture() &&
17453         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17454         !(isa<CapturedRegionScopeInfo>(CSI) &&
17455           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17456       DeclRefType.addConst();
17457     return true;
17458   }
17459   return false;
17460 }
17461 
17462 // Only block literals, captured statements, and lambda expressions can
17463 // capture; other scopes don't work.
17464 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17465                                  SourceLocation Loc,
17466                                  const bool Diagnose, Sema &S) {
17467   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17468     return getLambdaAwareParentOfDeclContext(DC);
17469   else if (Var->hasLocalStorage()) {
17470     if (Diagnose)
17471        diagnoseUncapturableValueReference(S, Loc, Var, DC);
17472   }
17473   return nullptr;
17474 }
17475 
17476 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17477 // certain types of variables (unnamed, variably modified types etc.)
17478 // so check for eligibility.
17479 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17480                                  SourceLocation Loc,
17481                                  const bool Diagnose, Sema &S) {
17482 
17483   bool IsBlock = isa<BlockScopeInfo>(CSI);
17484   bool IsLambda = isa<LambdaScopeInfo>(CSI);
17485 
17486   // Lambdas are not allowed to capture unnamed variables
17487   // (e.g. anonymous unions).
17488   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17489   // assuming that's the intent.
17490   if (IsLambda && !Var->getDeclName()) {
17491     if (Diagnose) {
17492       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17493       S.Diag(Var->getLocation(), diag::note_declared_at);
17494     }
17495     return false;
17496   }
17497 
17498   // Prohibit variably-modified types in blocks; they're difficult to deal with.
17499   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17500     if (Diagnose) {
17501       S.Diag(Loc, diag::err_ref_vm_type);
17502       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17503     }
17504     return false;
17505   }
17506   // Prohibit structs with flexible array members too.
17507   // We cannot capture what is in the tail end of the struct.
17508   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17509     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17510       if (Diagnose) {
17511         if (IsBlock)
17512           S.Diag(Loc, diag::err_ref_flexarray_type);
17513         else
17514           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17515         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17516       }
17517       return false;
17518     }
17519   }
17520   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17521   // Lambdas and captured statements are not allowed to capture __block
17522   // variables; they don't support the expected semantics.
17523   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17524     if (Diagnose) {
17525       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17526       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17527     }
17528     return false;
17529   }
17530   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17531   if (S.getLangOpts().OpenCL && IsBlock &&
17532       Var->getType()->isBlockPointerType()) {
17533     if (Diagnose)
17534       S.Diag(Loc, diag::err_opencl_block_ref_block);
17535     return false;
17536   }
17537 
17538   return true;
17539 }
17540 
17541 // Returns true if the capture by block was successful.
17542 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17543                                  SourceLocation Loc,
17544                                  const bool BuildAndDiagnose,
17545                                  QualType &CaptureType,
17546                                  QualType &DeclRefType,
17547                                  const bool Nested,
17548                                  Sema &S, bool Invalid) {
17549   bool ByRef = false;
17550 
17551   // Blocks are not allowed to capture arrays, excepting OpenCL.
17552   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17553   // (decayed to pointers).
17554   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17555     if (BuildAndDiagnose) {
17556       S.Diag(Loc, diag::err_ref_array_type);
17557       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17558       Invalid = true;
17559     } else {
17560       return false;
17561     }
17562   }
17563 
17564   // Forbid the block-capture of autoreleasing variables.
17565   if (!Invalid &&
17566       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17567     if (BuildAndDiagnose) {
17568       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17569         << /*block*/ 0;
17570       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17571       Invalid = true;
17572     } else {
17573       return false;
17574     }
17575   }
17576 
17577   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17578   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17579     QualType PointeeTy = PT->getPointeeType();
17580 
17581     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17582         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17583         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17584       if (BuildAndDiagnose) {
17585         SourceLocation VarLoc = Var->getLocation();
17586         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17587         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17588       }
17589     }
17590   }
17591 
17592   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17593   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17594       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17595     // Block capture by reference does not change the capture or
17596     // declaration reference types.
17597     ByRef = true;
17598   } else {
17599     // Block capture by copy introduces 'const'.
17600     CaptureType = CaptureType.getNonReferenceType().withConst();
17601     DeclRefType = CaptureType;
17602   }
17603 
17604   // Actually capture the variable.
17605   if (BuildAndDiagnose)
17606     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17607                     CaptureType, Invalid);
17608 
17609   return !Invalid;
17610 }
17611 
17612 
17613 /// Capture the given variable in the captured region.
17614 static bool captureInCapturedRegion(
17615     CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
17616     const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
17617     const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
17618     bool IsTopScope, Sema &S, bool Invalid) {
17619   // By default, capture variables by reference.
17620   bool ByRef = true;
17621   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17622     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17623   } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17624     // Using an LValue reference type is consistent with Lambdas (see below).
17625     if (S.isOpenMPCapturedDecl(Var)) {
17626       bool HasConst = DeclRefType.isConstQualified();
17627       DeclRefType = DeclRefType.getUnqualifiedType();
17628       // Don't lose diagnostics about assignments to const.
17629       if (HasConst)
17630         DeclRefType.addConst();
17631     }
17632     // Do not capture firstprivates in tasks.
17633     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17634         OMPC_unknown)
17635       return true;
17636     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17637                                     RSI->OpenMPCaptureLevel);
17638   }
17639 
17640   if (ByRef)
17641     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17642   else
17643     CaptureType = DeclRefType;
17644 
17645   // Actually capture the variable.
17646   if (BuildAndDiagnose)
17647     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17648                     Loc, SourceLocation(), CaptureType, Invalid);
17649 
17650   return !Invalid;
17651 }
17652 
17653 /// Capture the given variable in the lambda.
17654 static bool captureInLambda(LambdaScopeInfo *LSI,
17655                             VarDecl *Var,
17656                             SourceLocation Loc,
17657                             const bool BuildAndDiagnose,
17658                             QualType &CaptureType,
17659                             QualType &DeclRefType,
17660                             const bool RefersToCapturedVariable,
17661                             const Sema::TryCaptureKind Kind,
17662                             SourceLocation EllipsisLoc,
17663                             const bool IsTopScope,
17664                             Sema &S, bool Invalid) {
17665   // Determine whether we are capturing by reference or by value.
17666   bool ByRef = false;
17667   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17668     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17669   } else {
17670     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17671   }
17672 
17673   // Compute the type of the field that will capture this variable.
17674   if (ByRef) {
17675     // C++11 [expr.prim.lambda]p15:
17676     //   An entity is captured by reference if it is implicitly or
17677     //   explicitly captured but not captured by copy. It is
17678     //   unspecified whether additional unnamed non-static data
17679     //   members are declared in the closure type for entities
17680     //   captured by reference.
17681     //
17682     // FIXME: It is not clear whether we want to build an lvalue reference
17683     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17684     // to do the former, while EDG does the latter. Core issue 1249 will
17685     // clarify, but for now we follow GCC because it's a more permissive and
17686     // easily defensible position.
17687     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17688   } else {
17689     // C++11 [expr.prim.lambda]p14:
17690     //   For each entity captured by copy, an unnamed non-static
17691     //   data member is declared in the closure type. The
17692     //   declaration order of these members is unspecified. The type
17693     //   of such a data member is the type of the corresponding
17694     //   captured entity if the entity is not a reference to an
17695     //   object, or the referenced type otherwise. [Note: If the
17696     //   captured entity is a reference to a function, the
17697     //   corresponding data member is also a reference to a
17698     //   function. - end note ]
17699     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17700       if (!RefType->getPointeeType()->isFunctionType())
17701         CaptureType = RefType->getPointeeType();
17702     }
17703 
17704     // Forbid the lambda copy-capture of autoreleasing variables.
17705     if (!Invalid &&
17706         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17707       if (BuildAndDiagnose) {
17708         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17709         S.Diag(Var->getLocation(), diag::note_previous_decl)
17710           << Var->getDeclName();
17711         Invalid = true;
17712       } else {
17713         return false;
17714       }
17715     }
17716 
17717     // Make sure that by-copy captures are of a complete and non-abstract type.
17718     if (!Invalid && BuildAndDiagnose) {
17719       if (!CaptureType->isDependentType() &&
17720           S.RequireCompleteSizedType(
17721               Loc, CaptureType,
17722               diag::err_capture_of_incomplete_or_sizeless_type,
17723               Var->getDeclName()))
17724         Invalid = true;
17725       else if (S.RequireNonAbstractType(Loc, CaptureType,
17726                                         diag::err_capture_of_abstract_type))
17727         Invalid = true;
17728     }
17729   }
17730 
17731   // Compute the type of a reference to this captured variable.
17732   if (ByRef)
17733     DeclRefType = CaptureType.getNonReferenceType();
17734   else {
17735     // C++ [expr.prim.lambda]p5:
17736     //   The closure type for a lambda-expression has a public inline
17737     //   function call operator [...]. This function call operator is
17738     //   declared const (9.3.1) if and only if the lambda-expression's
17739     //   parameter-declaration-clause is not followed by mutable.
17740     DeclRefType = CaptureType.getNonReferenceType();
17741     if (!LSI->Mutable && !CaptureType->isReferenceType())
17742       DeclRefType.addConst();
17743   }
17744 
17745   // Add the capture.
17746   if (BuildAndDiagnose)
17747     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17748                     Loc, EllipsisLoc, CaptureType, Invalid);
17749 
17750   return !Invalid;
17751 }
17752 
17753 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
17754   // Offer a Copy fix even if the type is dependent.
17755   if (Var->getType()->isDependentType())
17756     return true;
17757   QualType T = Var->getType().getNonReferenceType();
17758   if (T.isTriviallyCopyableType(Context))
17759     return true;
17760   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
17761 
17762     if (!(RD = RD->getDefinition()))
17763       return false;
17764     if (RD->hasSimpleCopyConstructor())
17765       return true;
17766     if (RD->hasUserDeclaredCopyConstructor())
17767       for (CXXConstructorDecl *Ctor : RD->ctors())
17768         if (Ctor->isCopyConstructor())
17769           return !Ctor->isDeleted();
17770   }
17771   return false;
17772 }
17773 
17774 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
17775 /// default capture. Fixes may be omitted if they aren't allowed by the
17776 /// standard, for example we can't emit a default copy capture fix-it if we
17777 /// already explicitly copy capture capture another variable.
17778 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
17779                                     VarDecl *Var) {
17780   assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
17781   // Don't offer Capture by copy of default capture by copy fixes if Var is
17782   // known not to be copy constructible.
17783   bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
17784 
17785   SmallString<32> FixBuffer;
17786   StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
17787   if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
17788     SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
17789     if (ShouldOfferCopyFix) {
17790       // Offer fixes to insert an explicit capture for the variable.
17791       // [] -> [VarName]
17792       // [OtherCapture] -> [OtherCapture, VarName]
17793       FixBuffer.assign({Separator, Var->getName()});
17794       Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17795           << Var << /*value*/ 0
17796           << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17797     }
17798     // As above but capture by reference.
17799     FixBuffer.assign({Separator, "&", Var->getName()});
17800     Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17801         << Var << /*reference*/ 1
17802         << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17803   }
17804 
17805   // Only try to offer default capture if there are no captures excluding this
17806   // and init captures.
17807   // [this]: OK.
17808   // [X = Y]: OK.
17809   // [&A, &B]: Don't offer.
17810   // [A, B]: Don't offer.
17811   if (llvm::any_of(LSI->Captures, [](Capture &C) {
17812         return !C.isThisCapture() && !C.isInitCapture();
17813       }))
17814     return;
17815 
17816   // The default capture specifiers, '=' or '&', must appear first in the
17817   // capture body.
17818   SourceLocation DefaultInsertLoc =
17819       LSI->IntroducerRange.getBegin().getLocWithOffset(1);
17820 
17821   if (ShouldOfferCopyFix) {
17822     bool CanDefaultCopyCapture = true;
17823     // [=, *this] OK since c++17
17824     // [=, this] OK since c++20
17825     if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
17826       CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
17827                                   ? LSI->getCXXThisCapture().isCopyCapture()
17828                                   : false;
17829     // We can't use default capture by copy if any captures already specified
17830     // capture by copy.
17831     if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
17832           return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
17833         })) {
17834       FixBuffer.assign({"=", Separator});
17835       Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
17836           << /*value*/ 0
17837           << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
17838     }
17839   }
17840 
17841   // We can't use default capture by reference if any captures already specified
17842   // capture by reference.
17843   if (llvm::none_of(LSI->Captures, [](Capture &C) {
17844         return !C.isInitCapture() && C.isReferenceCapture() &&
17845                !C.isThisCapture();
17846       })) {
17847     FixBuffer.assign({"&", Separator});
17848     Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
17849         << /*reference*/ 1
17850         << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
17851   }
17852 }
17853 
17854 bool Sema::tryCaptureVariable(
17855     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17856     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17857     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17858   // An init-capture is notionally from the context surrounding its
17859   // declaration, but its parent DC is the lambda class.
17860   DeclContext *VarDC = Var->getDeclContext();
17861   if (Var->isInitCapture())
17862     VarDC = VarDC->getParent();
17863 
17864   DeclContext *DC = CurContext;
17865   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17866       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17867   // We need to sync up the Declaration Context with the
17868   // FunctionScopeIndexToStopAt
17869   if (FunctionScopeIndexToStopAt) {
17870     unsigned FSIndex = FunctionScopes.size() - 1;
17871     while (FSIndex != MaxFunctionScopesIndex) {
17872       DC = getLambdaAwareParentOfDeclContext(DC);
17873       --FSIndex;
17874     }
17875   }
17876 
17877 
17878   // If the variable is declared in the current context, there is no need to
17879   // capture it.
17880   if (VarDC == DC) return true;
17881 
17882   // Capture global variables if it is required to use private copy of this
17883   // variable.
17884   bool IsGlobal = !Var->hasLocalStorage();
17885   if (IsGlobal &&
17886       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17887                                                 MaxFunctionScopesIndex)))
17888     return true;
17889   Var = Var->getCanonicalDecl();
17890 
17891   // Walk up the stack to determine whether we can capture the variable,
17892   // performing the "simple" checks that don't depend on type. We stop when
17893   // we've either hit the declared scope of the variable or find an existing
17894   // capture of that variable.  We start from the innermost capturing-entity
17895   // (the DC) and ensure that all intervening capturing-entities
17896   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17897   // declcontext can either capture the variable or have already captured
17898   // the variable.
17899   CaptureType = Var->getType();
17900   DeclRefType = CaptureType.getNonReferenceType();
17901   bool Nested = false;
17902   bool Explicit = (Kind != TryCapture_Implicit);
17903   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17904   do {
17905     // Only block literals, captured statements, and lambda expressions can
17906     // capture; other scopes don't work.
17907     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17908                                                               ExprLoc,
17909                                                               BuildAndDiagnose,
17910                                                               *this);
17911     // We need to check for the parent *first* because, if we *have*
17912     // private-captured a global variable, we need to recursively capture it in
17913     // intermediate blocks, lambdas, etc.
17914     if (!ParentDC) {
17915       if (IsGlobal) {
17916         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17917         break;
17918       }
17919       return true;
17920     }
17921 
17922     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17923     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17924 
17925 
17926     // Check whether we've already captured it.
17927     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17928                                              DeclRefType)) {
17929       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17930       break;
17931     }
17932     // If we are instantiating a generic lambda call operator body,
17933     // we do not want to capture new variables.  What was captured
17934     // during either a lambdas transformation or initial parsing
17935     // should be used.
17936     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17937       if (BuildAndDiagnose) {
17938         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17939         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17940           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17941           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17942           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17943           buildLambdaCaptureFixit(*this, LSI, Var);
17944         } else
17945           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17946       }
17947       return true;
17948     }
17949 
17950     // Try to capture variable-length arrays types.
17951     if (Var->getType()->isVariablyModifiedType()) {
17952       // We're going to walk down into the type and look for VLA
17953       // expressions.
17954       QualType QTy = Var->getType();
17955       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17956         QTy = PVD->getOriginalType();
17957       captureVariablyModifiedType(Context, QTy, CSI);
17958     }
17959 
17960     if (getLangOpts().OpenMP) {
17961       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17962         // OpenMP private variables should not be captured in outer scope, so
17963         // just break here. Similarly, global variables that are captured in a
17964         // target region should not be captured outside the scope of the region.
17965         if (RSI->CapRegionKind == CR_OpenMP) {
17966           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17967               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17968           // If the variable is private (i.e. not captured) and has variably
17969           // modified type, we still need to capture the type for correct
17970           // codegen in all regions, associated with the construct. Currently,
17971           // it is captured in the innermost captured region only.
17972           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17973               Var->getType()->isVariablyModifiedType()) {
17974             QualType QTy = Var->getType();
17975             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17976               QTy = PVD->getOriginalType();
17977             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17978                  I < E; ++I) {
17979               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17980                   FunctionScopes[FunctionScopesIndex - I]);
17981               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17982                      "Wrong number of captured regions associated with the "
17983                      "OpenMP construct.");
17984               captureVariablyModifiedType(Context, QTy, OuterRSI);
17985             }
17986           }
17987           bool IsTargetCap =
17988               IsOpenMPPrivateDecl != OMPC_private &&
17989               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17990                                          RSI->OpenMPCaptureLevel);
17991           // Do not capture global if it is not privatized in outer regions.
17992           bool IsGlobalCap =
17993               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17994                                                      RSI->OpenMPCaptureLevel);
17995 
17996           // When we detect target captures we are looking from inside the
17997           // target region, therefore we need to propagate the capture from the
17998           // enclosing region. Therefore, the capture is not initially nested.
17999           if (IsTargetCap)
18000             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
18001 
18002           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18003               (IsGlobal && !IsGlobalCap)) {
18004             Nested = !IsTargetCap;
18005             bool HasConst = DeclRefType.isConstQualified();
18006             DeclRefType = DeclRefType.getUnqualifiedType();
18007             // Don't lose diagnostics about assignments to const.
18008             if (HasConst)
18009               DeclRefType.addConst();
18010             CaptureType = Context.getLValueReferenceType(DeclRefType);
18011             break;
18012           }
18013         }
18014       }
18015     }
18016     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18017       // No capture-default, and this is not an explicit capture
18018       // so cannot capture this variable.
18019       if (BuildAndDiagnose) {
18020         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18021         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18022         auto *LSI = cast<LambdaScopeInfo>(CSI);
18023         if (LSI->Lambda) {
18024           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18025           buildLambdaCaptureFixit(*this, LSI, Var);
18026         }
18027         // FIXME: If we error out because an outer lambda can not implicitly
18028         // capture a variable that an inner lambda explicitly captures, we
18029         // should have the inner lambda do the explicit capture - because
18030         // it makes for cleaner diagnostics later.  This would purely be done
18031         // so that the diagnostic does not misleadingly claim that a variable
18032         // can not be captured by a lambda implicitly even though it is captured
18033         // explicitly.  Suggestion:
18034         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18035         //    at the function head
18036         //  - cache the StartingDeclContext - this must be a lambda
18037         //  - captureInLambda in the innermost lambda the variable.
18038       }
18039       return true;
18040     }
18041 
18042     FunctionScopesIndex--;
18043     DC = ParentDC;
18044     Explicit = false;
18045   } while (!VarDC->Equals(DC));
18046 
18047   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18048   // computing the type of the capture at each step, checking type-specific
18049   // requirements, and adding captures if requested.
18050   // If the variable had already been captured previously, we start capturing
18051   // at the lambda nested within that one.
18052   bool Invalid = false;
18053   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18054        ++I) {
18055     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18056 
18057     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18058     // certain types of variables (unnamed, variably modified types etc.)
18059     // so check for eligibility.
18060     if (!Invalid)
18061       Invalid =
18062           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18063 
18064     // After encountering an error, if we're actually supposed to capture, keep
18065     // capturing in nested contexts to suppress any follow-on diagnostics.
18066     if (Invalid && !BuildAndDiagnose)
18067       return true;
18068 
18069     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18070       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18071                                DeclRefType, Nested, *this, Invalid);
18072       Nested = true;
18073     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18074       Invalid = !captureInCapturedRegion(
18075           RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18076           Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18077       Nested = true;
18078     } else {
18079       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18080       Invalid =
18081           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18082                            DeclRefType, Nested, Kind, EllipsisLoc,
18083                            /*IsTopScope*/ I == N - 1, *this, Invalid);
18084       Nested = true;
18085     }
18086 
18087     if (Invalid && !BuildAndDiagnose)
18088       return true;
18089   }
18090   return Invalid;
18091 }
18092 
18093 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
18094                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18095   QualType CaptureType;
18096   QualType DeclRefType;
18097   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18098                             /*BuildAndDiagnose=*/true, CaptureType,
18099                             DeclRefType, nullptr);
18100 }
18101 
18102 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
18103   QualType CaptureType;
18104   QualType DeclRefType;
18105   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18106                              /*BuildAndDiagnose=*/false, CaptureType,
18107                              DeclRefType, nullptr);
18108 }
18109 
18110 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
18111   QualType CaptureType;
18112   QualType DeclRefType;
18113 
18114   // Determine whether we can capture this variable.
18115   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18116                          /*BuildAndDiagnose=*/false, CaptureType,
18117                          DeclRefType, nullptr))
18118     return QualType();
18119 
18120   return DeclRefType;
18121 }
18122 
18123 namespace {
18124 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
18125 // The produced TemplateArgumentListInfo* points to data stored within this
18126 // object, so should only be used in contexts where the pointer will not be
18127 // used after the CopiedTemplateArgs object is destroyed.
18128 class CopiedTemplateArgs {
18129   bool HasArgs;
18130   TemplateArgumentListInfo TemplateArgStorage;
18131 public:
18132   template<typename RefExpr>
18133   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
18134     if (HasArgs)
18135       E->copyTemplateArgumentsInto(TemplateArgStorage);
18136   }
18137   operator TemplateArgumentListInfo*()
18138 #ifdef __has_cpp_attribute
18139 #if __has_cpp_attribute(clang::lifetimebound)
18140   [[clang::lifetimebound]]
18141 #endif
18142 #endif
18143   {
18144     return HasArgs ? &TemplateArgStorage : nullptr;
18145   }
18146 };
18147 }
18148 
18149 /// Walk the set of potential results of an expression and mark them all as
18150 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
18151 ///
18152 /// \return A new expression if we found any potential results, ExprEmpty() if
18153 ///         not, and ExprError() if we diagnosed an error.
18154 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
18155                                                       NonOdrUseReason NOUR) {
18156   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
18157   // an object that satisfies the requirements for appearing in a
18158   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
18159   // is immediately applied."  This function handles the lvalue-to-rvalue
18160   // conversion part.
18161   //
18162   // If we encounter a node that claims to be an odr-use but shouldn't be, we
18163   // transform it into the relevant kind of non-odr-use node and rebuild the
18164   // tree of nodes leading to it.
18165   //
18166   // This is a mini-TreeTransform that only transforms a restricted subset of
18167   // nodes (and only certain operands of them).
18168 
18169   // Rebuild a subexpression.
18170   auto Rebuild = [&](Expr *Sub) {
18171     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
18172   };
18173 
18174   // Check whether a potential result satisfies the requirements of NOUR.
18175   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
18176     // Any entity other than a VarDecl is always odr-used whenever it's named
18177     // in a potentially-evaluated expression.
18178     auto *VD = dyn_cast<VarDecl>(D);
18179     if (!VD)
18180       return true;
18181 
18182     // C++2a [basic.def.odr]p4:
18183     //   A variable x whose name appears as a potentially-evalauted expression
18184     //   e is odr-used by e unless
18185     //   -- x is a reference that is usable in constant expressions, or
18186     //   -- x is a variable of non-reference type that is usable in constant
18187     //      expressions and has no mutable subobjects, and e is an element of
18188     //      the set of potential results of an expression of
18189     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18190     //      conversion is applied, or
18191     //   -- x is a variable of non-reference type, and e is an element of the
18192     //      set of potential results of a discarded-value expression to which
18193     //      the lvalue-to-rvalue conversion is not applied
18194     //
18195     // We check the first bullet and the "potentially-evaluated" condition in
18196     // BuildDeclRefExpr. We check the type requirements in the second bullet
18197     // in CheckLValueToRValueConversionOperand below.
18198     switch (NOUR) {
18199     case NOUR_None:
18200     case NOUR_Unevaluated:
18201       llvm_unreachable("unexpected non-odr-use-reason");
18202 
18203     case NOUR_Constant:
18204       // Constant references were handled when they were built.
18205       if (VD->getType()->isReferenceType())
18206         return true;
18207       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
18208         if (RD->hasMutableFields())
18209           return true;
18210       if (!VD->isUsableInConstantExpressions(S.Context))
18211         return true;
18212       break;
18213 
18214     case NOUR_Discarded:
18215       if (VD->getType()->isReferenceType())
18216         return true;
18217       break;
18218     }
18219     return false;
18220   };
18221 
18222   // Mark that this expression does not constitute an odr-use.
18223   auto MarkNotOdrUsed = [&] {
18224     S.MaybeODRUseExprs.remove(E);
18225     if (LambdaScopeInfo *LSI = S.getCurLambda())
18226       LSI->markVariableExprAsNonODRUsed(E);
18227   };
18228 
18229   // C++2a [basic.def.odr]p2:
18230   //   The set of potential results of an expression e is defined as follows:
18231   switch (E->getStmtClass()) {
18232   //   -- If e is an id-expression, ...
18233   case Expr::DeclRefExprClass: {
18234     auto *DRE = cast<DeclRefExpr>(E);
18235     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
18236       break;
18237 
18238     // Rebuild as a non-odr-use DeclRefExpr.
18239     MarkNotOdrUsed();
18240     return DeclRefExpr::Create(
18241         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
18242         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
18243         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
18244         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
18245   }
18246 
18247   case Expr::FunctionParmPackExprClass: {
18248     auto *FPPE = cast<FunctionParmPackExpr>(E);
18249     // If any of the declarations in the pack is odr-used, then the expression
18250     // as a whole constitutes an odr-use.
18251     for (VarDecl *D : *FPPE)
18252       if (IsPotentialResultOdrUsed(D))
18253         return ExprEmpty();
18254 
18255     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
18256     // nothing cares about whether we marked this as an odr-use, but it might
18257     // be useful for non-compiler tools.
18258     MarkNotOdrUsed();
18259     break;
18260   }
18261 
18262   //   -- If e is a subscripting operation with an array operand...
18263   case Expr::ArraySubscriptExprClass: {
18264     auto *ASE = cast<ArraySubscriptExpr>(E);
18265     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
18266     if (!OldBase->getType()->isArrayType())
18267       break;
18268     ExprResult Base = Rebuild(OldBase);
18269     if (!Base.isUsable())
18270       return Base;
18271     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
18272     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
18273     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
18274     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
18275                                      ASE->getRBracketLoc());
18276   }
18277 
18278   case Expr::MemberExprClass: {
18279     auto *ME = cast<MemberExpr>(E);
18280     // -- If e is a class member access expression [...] naming a non-static
18281     //    data member...
18282     if (isa<FieldDecl>(ME->getMemberDecl())) {
18283       ExprResult Base = Rebuild(ME->getBase());
18284       if (!Base.isUsable())
18285         return Base;
18286       return MemberExpr::Create(
18287           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
18288           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
18289           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
18290           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
18291           ME->getObjectKind(), ME->isNonOdrUse());
18292     }
18293 
18294     if (ME->getMemberDecl()->isCXXInstanceMember())
18295       break;
18296 
18297     // -- If e is a class member access expression naming a static data member,
18298     //    ...
18299     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
18300       break;
18301 
18302     // Rebuild as a non-odr-use MemberExpr.
18303     MarkNotOdrUsed();
18304     return MemberExpr::Create(
18305         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
18306         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
18307         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
18308         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
18309   }
18310 
18311   case Expr::BinaryOperatorClass: {
18312     auto *BO = cast<BinaryOperator>(E);
18313     Expr *LHS = BO->getLHS();
18314     Expr *RHS = BO->getRHS();
18315     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
18316     if (BO->getOpcode() == BO_PtrMemD) {
18317       ExprResult Sub = Rebuild(LHS);
18318       if (!Sub.isUsable())
18319         return Sub;
18320       LHS = Sub.get();
18321     //   -- If e is a comma expression, ...
18322     } else if (BO->getOpcode() == BO_Comma) {
18323       ExprResult Sub = Rebuild(RHS);
18324       if (!Sub.isUsable())
18325         return Sub;
18326       RHS = Sub.get();
18327     } else {
18328       break;
18329     }
18330     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
18331                         LHS, RHS);
18332   }
18333 
18334   //   -- If e has the form (e1)...
18335   case Expr::ParenExprClass: {
18336     auto *PE = cast<ParenExpr>(E);
18337     ExprResult Sub = Rebuild(PE->getSubExpr());
18338     if (!Sub.isUsable())
18339       return Sub;
18340     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
18341   }
18342 
18343   //   -- If e is a glvalue conditional expression, ...
18344   // We don't apply this to a binary conditional operator. FIXME: Should we?
18345   case Expr::ConditionalOperatorClass: {
18346     auto *CO = cast<ConditionalOperator>(E);
18347     ExprResult LHS = Rebuild(CO->getLHS());
18348     if (LHS.isInvalid())
18349       return ExprError();
18350     ExprResult RHS = Rebuild(CO->getRHS());
18351     if (RHS.isInvalid())
18352       return ExprError();
18353     if (!LHS.isUsable() && !RHS.isUsable())
18354       return ExprEmpty();
18355     if (!LHS.isUsable())
18356       LHS = CO->getLHS();
18357     if (!RHS.isUsable())
18358       RHS = CO->getRHS();
18359     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
18360                                 CO->getCond(), LHS.get(), RHS.get());
18361   }
18362 
18363   // [Clang extension]
18364   //   -- If e has the form __extension__ e1...
18365   case Expr::UnaryOperatorClass: {
18366     auto *UO = cast<UnaryOperator>(E);
18367     if (UO->getOpcode() != UO_Extension)
18368       break;
18369     ExprResult Sub = Rebuild(UO->getSubExpr());
18370     if (!Sub.isUsable())
18371       return Sub;
18372     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
18373                           Sub.get());
18374   }
18375 
18376   // [Clang extension]
18377   //   -- If e has the form _Generic(...), the set of potential results is the
18378   //      union of the sets of potential results of the associated expressions.
18379   case Expr::GenericSelectionExprClass: {
18380     auto *GSE = cast<GenericSelectionExpr>(E);
18381 
18382     SmallVector<Expr *, 4> AssocExprs;
18383     bool AnyChanged = false;
18384     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
18385       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
18386       if (AssocExpr.isInvalid())
18387         return ExprError();
18388       if (AssocExpr.isUsable()) {
18389         AssocExprs.push_back(AssocExpr.get());
18390         AnyChanged = true;
18391       } else {
18392         AssocExprs.push_back(OrigAssocExpr);
18393       }
18394     }
18395 
18396     return AnyChanged ? S.CreateGenericSelectionExpr(
18397                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
18398                             GSE->getRParenLoc(), GSE->getControllingExpr(),
18399                             GSE->getAssocTypeSourceInfos(), AssocExprs)
18400                       : ExprEmpty();
18401   }
18402 
18403   // [Clang extension]
18404   //   -- If e has the form __builtin_choose_expr(...), the set of potential
18405   //      results is the union of the sets of potential results of the
18406   //      second and third subexpressions.
18407   case Expr::ChooseExprClass: {
18408     auto *CE = cast<ChooseExpr>(E);
18409 
18410     ExprResult LHS = Rebuild(CE->getLHS());
18411     if (LHS.isInvalid())
18412       return ExprError();
18413 
18414     ExprResult RHS = Rebuild(CE->getLHS());
18415     if (RHS.isInvalid())
18416       return ExprError();
18417 
18418     if (!LHS.get() && !RHS.get())
18419       return ExprEmpty();
18420     if (!LHS.isUsable())
18421       LHS = CE->getLHS();
18422     if (!RHS.isUsable())
18423       RHS = CE->getRHS();
18424 
18425     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
18426                              RHS.get(), CE->getRParenLoc());
18427   }
18428 
18429   // Step through non-syntactic nodes.
18430   case Expr::ConstantExprClass: {
18431     auto *CE = cast<ConstantExpr>(E);
18432     ExprResult Sub = Rebuild(CE->getSubExpr());
18433     if (!Sub.isUsable())
18434       return Sub;
18435     return ConstantExpr::Create(S.Context, Sub.get());
18436   }
18437 
18438   // We could mostly rely on the recursive rebuilding to rebuild implicit
18439   // casts, but not at the top level, so rebuild them here.
18440   case Expr::ImplicitCastExprClass: {
18441     auto *ICE = cast<ImplicitCastExpr>(E);
18442     // Only step through the narrow set of cast kinds we expect to encounter.
18443     // Anything else suggests we've left the region in which potential results
18444     // can be found.
18445     switch (ICE->getCastKind()) {
18446     case CK_NoOp:
18447     case CK_DerivedToBase:
18448     case CK_UncheckedDerivedToBase: {
18449       ExprResult Sub = Rebuild(ICE->getSubExpr());
18450       if (!Sub.isUsable())
18451         return Sub;
18452       CXXCastPath Path(ICE->path());
18453       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
18454                                  ICE->getValueKind(), &Path);
18455     }
18456 
18457     default:
18458       break;
18459     }
18460     break;
18461   }
18462 
18463   default:
18464     break;
18465   }
18466 
18467   // Can't traverse through this node. Nothing to do.
18468   return ExprEmpty();
18469 }
18470 
18471 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
18472   // Check whether the operand is or contains an object of non-trivial C union
18473   // type.
18474   if (E->getType().isVolatileQualified() &&
18475       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
18476        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
18477     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
18478                           Sema::NTCUC_LValueToRValueVolatile,
18479                           NTCUK_Destruct|NTCUK_Copy);
18480 
18481   // C++2a [basic.def.odr]p4:
18482   //   [...] an expression of non-volatile-qualified non-class type to which
18483   //   the lvalue-to-rvalue conversion is applied [...]
18484   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
18485     return E;
18486 
18487   ExprResult Result =
18488       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
18489   if (Result.isInvalid())
18490     return ExprError();
18491   return Result.get() ? Result : E;
18492 }
18493 
18494 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
18495   Res = CorrectDelayedTyposInExpr(Res);
18496 
18497   if (!Res.isUsable())
18498     return Res;
18499 
18500   // If a constant-expression is a reference to a variable where we delay
18501   // deciding whether it is an odr-use, just assume we will apply the
18502   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
18503   // (a non-type template argument), we have special handling anyway.
18504   return CheckLValueToRValueConversionOperand(Res.get());
18505 }
18506 
18507 void Sema::CleanupVarDeclMarking() {
18508   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
18509   // call.
18510   MaybeODRUseExprSet LocalMaybeODRUseExprs;
18511   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
18512 
18513   for (Expr *E : LocalMaybeODRUseExprs) {
18514     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
18515       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
18516                          DRE->getLocation(), *this);
18517     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
18518       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
18519                          *this);
18520     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
18521       for (VarDecl *VD : *FP)
18522         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
18523     } else {
18524       llvm_unreachable("Unexpected expression");
18525     }
18526   }
18527 
18528   assert(MaybeODRUseExprs.empty() &&
18529          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
18530 }
18531 
18532 static void DoMarkVarDeclReferenced(
18533     Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
18534     llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18535   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
18536           isa<FunctionParmPackExpr>(E)) &&
18537          "Invalid Expr argument to DoMarkVarDeclReferenced");
18538   Var->setReferenced();
18539 
18540   if (Var->isInvalidDecl())
18541     return;
18542 
18543   auto *MSI = Var->getMemberSpecializationInfo();
18544   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18545                                        : Var->getTemplateSpecializationKind();
18546 
18547   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18548   bool UsableInConstantExpr =
18549       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18550 
18551   if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
18552     RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
18553   }
18554 
18555   // C++20 [expr.const]p12:
18556   //   A variable [...] is needed for constant evaluation if it is [...] a
18557   //   variable whose name appears as a potentially constant evaluated
18558   //   expression that is either a contexpr variable or is of non-volatile
18559   //   const-qualified integral type or of reference type
18560   bool NeededForConstantEvaluation =
18561       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18562 
18563   bool NeedDefinition =
18564       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18565 
18566   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
18567          "Can't instantiate a partial template specialization.");
18568 
18569   // If this might be a member specialization of a static data member, check
18570   // the specialization is visible. We already did the checks for variable
18571   // template specializations when we created them.
18572   if (NeedDefinition && TSK != TSK_Undeclared &&
18573       !isa<VarTemplateSpecializationDecl>(Var))
18574     SemaRef.checkSpecializationVisibility(Loc, Var);
18575 
18576   // Perform implicit instantiation of static data members, static data member
18577   // templates of class templates, and variable template specializations. Delay
18578   // instantiations of variable templates, except for those that could be used
18579   // in a constant expression.
18580   if (NeedDefinition && isTemplateInstantiation(TSK)) {
18581     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18582     // instantiation declaration if a variable is usable in a constant
18583     // expression (among other cases).
18584     bool TryInstantiating =
18585         TSK == TSK_ImplicitInstantiation ||
18586         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18587 
18588     if (TryInstantiating) {
18589       SourceLocation PointOfInstantiation =
18590           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18591       bool FirstInstantiation = PointOfInstantiation.isInvalid();
18592       if (FirstInstantiation) {
18593         PointOfInstantiation = Loc;
18594         if (MSI)
18595           MSI->setPointOfInstantiation(PointOfInstantiation);
18596           // FIXME: Notify listener.
18597         else
18598           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18599       }
18600 
18601       if (UsableInConstantExpr) {
18602         // Do not defer instantiations of variables that could be used in a
18603         // constant expression.
18604         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18605           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18606         });
18607 
18608         // Re-set the member to trigger a recomputation of the dependence bits
18609         // for the expression.
18610         if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18611           DRE->setDecl(DRE->getDecl());
18612         else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
18613           ME->setMemberDecl(ME->getMemberDecl());
18614       } else if (FirstInstantiation ||
18615                  isa<VarTemplateSpecializationDecl>(Var)) {
18616         // FIXME: For a specialization of a variable template, we don't
18617         // distinguish between "declaration and type implicitly instantiated"
18618         // and "implicit instantiation of definition requested", so we have
18619         // no direct way to avoid enqueueing the pending instantiation
18620         // multiple times.
18621         SemaRef.PendingInstantiations
18622             .push_back(std::make_pair(Var, PointOfInstantiation));
18623       }
18624     }
18625   }
18626 
18627   // C++2a [basic.def.odr]p4:
18628   //   A variable x whose name appears as a potentially-evaluated expression e
18629   //   is odr-used by e unless
18630   //   -- x is a reference that is usable in constant expressions
18631   //   -- x is a variable of non-reference type that is usable in constant
18632   //      expressions and has no mutable subobjects [FIXME], and e is an
18633   //      element of the set of potential results of an expression of
18634   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18635   //      conversion is applied
18636   //   -- x is a variable of non-reference type, and e is an element of the set
18637   //      of potential results of a discarded-value expression to which the
18638   //      lvalue-to-rvalue conversion is not applied [FIXME]
18639   //
18640   // We check the first part of the second bullet here, and
18641   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18642   // FIXME: To get the third bullet right, we need to delay this even for
18643   // variables that are not usable in constant expressions.
18644 
18645   // If we already know this isn't an odr-use, there's nothing more to do.
18646   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18647     if (DRE->isNonOdrUse())
18648       return;
18649   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18650     if (ME->isNonOdrUse())
18651       return;
18652 
18653   switch (OdrUse) {
18654   case OdrUseContext::None:
18655     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18656            "missing non-odr-use marking for unevaluated decl ref");
18657     break;
18658 
18659   case OdrUseContext::FormallyOdrUsed:
18660     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18661     // behavior.
18662     break;
18663 
18664   case OdrUseContext::Used:
18665     // If we might later find that this expression isn't actually an odr-use,
18666     // delay the marking.
18667     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18668       SemaRef.MaybeODRUseExprs.insert(E);
18669     else
18670       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18671     break;
18672 
18673   case OdrUseContext::Dependent:
18674     // If this is a dependent context, we don't need to mark variables as
18675     // odr-used, but we may still need to track them for lambda capture.
18676     // FIXME: Do we also need to do this inside dependent typeid expressions
18677     // (which are modeled as unevaluated at this point)?
18678     const bool RefersToEnclosingScope =
18679         (SemaRef.CurContext != Var->getDeclContext() &&
18680          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18681     if (RefersToEnclosingScope) {
18682       LambdaScopeInfo *const LSI =
18683           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18684       if (LSI && (!LSI->CallOperator ||
18685                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18686         // If a variable could potentially be odr-used, defer marking it so
18687         // until we finish analyzing the full expression for any
18688         // lvalue-to-rvalue
18689         // or discarded value conversions that would obviate odr-use.
18690         // Add it to the list of potential captures that will be analyzed
18691         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18692         // unless the variable is a reference that was initialized by a constant
18693         // expression (this will never need to be captured or odr-used).
18694         //
18695         // FIXME: We can simplify this a lot after implementing P0588R1.
18696         assert(E && "Capture variable should be used in an expression.");
18697         if (!Var->getType()->isReferenceType() ||
18698             !Var->isUsableInConstantExpressions(SemaRef.Context))
18699           LSI->addPotentialCapture(E->IgnoreParens());
18700       }
18701     }
18702     break;
18703   }
18704 }
18705 
18706 /// Mark a variable referenced, and check whether it is odr-used
18707 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18708 /// used directly for normal expressions referring to VarDecl.
18709 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18710   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
18711 }
18712 
18713 static void
18714 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
18715                    bool MightBeOdrUse,
18716                    llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18717   if (SemaRef.isInOpenMPDeclareTargetContext())
18718     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18719 
18720   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18721     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
18722     return;
18723   }
18724 
18725   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18726 
18727   // If this is a call to a method via a cast, also mark the method in the
18728   // derived class used in case codegen can devirtualize the call.
18729   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18730   if (!ME)
18731     return;
18732   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18733   if (!MD)
18734     return;
18735   // Only attempt to devirtualize if this is truly a virtual call.
18736   bool IsVirtualCall = MD->isVirtual() &&
18737                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18738   if (!IsVirtualCall)
18739     return;
18740 
18741   // If it's possible to devirtualize the call, mark the called function
18742   // referenced.
18743   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18744       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18745   if (DM)
18746     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18747 }
18748 
18749 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18750 ///
18751 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
18752 /// handled with care if the DeclRefExpr is not newly-created.
18753 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18754   // TODO: update this with DR# once a defect report is filed.
18755   // C++11 defect. The address of a pure member should not be an ODR use, even
18756   // if it's a qualified reference.
18757   bool OdrUse = true;
18758   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18759     if (Method->isVirtual() &&
18760         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18761       OdrUse = false;
18762 
18763   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18764     if (!isUnevaluatedContext() && !isConstantEvaluated() &&
18765         FD->isConsteval() && !RebuildingImmediateInvocation)
18766       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18767   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
18768                      RefsMinusAssignments);
18769 }
18770 
18771 /// Perform reference-marking and odr-use handling for a MemberExpr.
18772 void Sema::MarkMemberReferenced(MemberExpr *E) {
18773   // C++11 [basic.def.odr]p2:
18774   //   A non-overloaded function whose name appears as a potentially-evaluated
18775   //   expression or a member of a set of candidate functions, if selected by
18776   //   overload resolution when referred to from a potentially-evaluated
18777   //   expression, is odr-used, unless it is a pure virtual function and its
18778   //   name is not explicitly qualified.
18779   bool MightBeOdrUse = true;
18780   if (E->performsVirtualDispatch(getLangOpts())) {
18781     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18782       if (Method->isPure())
18783         MightBeOdrUse = false;
18784   }
18785   SourceLocation Loc =
18786       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18787   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
18788                      RefsMinusAssignments);
18789 }
18790 
18791 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18792 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18793   for (VarDecl *VD : *E)
18794     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
18795                        RefsMinusAssignments);
18796 }
18797 
18798 /// Perform marking for a reference to an arbitrary declaration.  It
18799 /// marks the declaration referenced, and performs odr-use checking for
18800 /// functions and variables. This method should not be used when building a
18801 /// normal expression which refers to a variable.
18802 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18803                                  bool MightBeOdrUse) {
18804   if (MightBeOdrUse) {
18805     if (auto *VD = dyn_cast<VarDecl>(D)) {
18806       MarkVariableReferenced(Loc, VD);
18807       return;
18808     }
18809   }
18810   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18811     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18812     return;
18813   }
18814   D->setReferenced();
18815 }
18816 
18817 namespace {
18818   // Mark all of the declarations used by a type as referenced.
18819   // FIXME: Not fully implemented yet! We need to have a better understanding
18820   // of when we're entering a context we should not recurse into.
18821   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18822   // TreeTransforms rebuilding the type in a new context. Rather than
18823   // duplicating the TreeTransform logic, we should consider reusing it here.
18824   // Currently that causes problems when rebuilding LambdaExprs.
18825   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18826     Sema &S;
18827     SourceLocation Loc;
18828 
18829   public:
18830     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18831 
18832     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18833 
18834     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18835   };
18836 }
18837 
18838 bool MarkReferencedDecls::TraverseTemplateArgument(
18839     const TemplateArgument &Arg) {
18840   {
18841     // A non-type template argument is a constant-evaluated context.
18842     EnterExpressionEvaluationContext Evaluated(
18843         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18844     if (Arg.getKind() == TemplateArgument::Declaration) {
18845       if (Decl *D = Arg.getAsDecl())
18846         S.MarkAnyDeclReferenced(Loc, D, true);
18847     } else if (Arg.getKind() == TemplateArgument::Expression) {
18848       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18849     }
18850   }
18851 
18852   return Inherited::TraverseTemplateArgument(Arg);
18853 }
18854 
18855 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18856   MarkReferencedDecls Marker(*this, Loc);
18857   Marker.TraverseType(T);
18858 }
18859 
18860 namespace {
18861 /// Helper class that marks all of the declarations referenced by
18862 /// potentially-evaluated subexpressions as "referenced".
18863 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18864 public:
18865   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18866   bool SkipLocalVariables;
18867 
18868   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18869       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18870 
18871   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18872     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18873   }
18874 
18875   void VisitDeclRefExpr(DeclRefExpr *E) {
18876     // If we were asked not to visit local variables, don't.
18877     if (SkipLocalVariables) {
18878       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18879         if (VD->hasLocalStorage())
18880           return;
18881     }
18882 
18883     // FIXME: This can trigger the instantiation of the initializer of a
18884     // variable, which can cause the expression to become value-dependent
18885     // or error-dependent. Do we need to propagate the new dependence bits?
18886     S.MarkDeclRefReferenced(E);
18887   }
18888 
18889   void VisitMemberExpr(MemberExpr *E) {
18890     S.MarkMemberReferenced(E);
18891     Visit(E->getBase());
18892   }
18893 };
18894 } // namespace
18895 
18896 /// Mark any declarations that appear within this expression or any
18897 /// potentially-evaluated subexpressions as "referenced".
18898 ///
18899 /// \param SkipLocalVariables If true, don't mark local variables as
18900 /// 'referenced'.
18901 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18902                                             bool SkipLocalVariables) {
18903   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18904 }
18905 
18906 /// Emit a diagnostic when statements are reachable.
18907 /// FIXME: check for reachability even in expressions for which we don't build a
18908 ///        CFG (eg, in the initializer of a global or in a constant expression).
18909 ///        For example,
18910 ///        namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
18911 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
18912                            const PartialDiagnostic &PD) {
18913   if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18914     if (!FunctionScopes.empty())
18915       FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
18916           sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18917     return true;
18918   }
18919 
18920   // The initializer of a constexpr variable or of the first declaration of a
18921   // static data member is not syntactically a constant evaluated constant,
18922   // but nonetheless is always required to be a constant expression, so we
18923   // can skip diagnosing.
18924   // FIXME: Using the mangling context here is a hack.
18925   if (auto *VD = dyn_cast_or_null<VarDecl>(
18926           ExprEvalContexts.back().ManglingContextDecl)) {
18927     if (VD->isConstexpr() ||
18928         (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18929       return false;
18930     // FIXME: For any other kind of variable, we should build a CFG for its
18931     // initializer and check whether the context in question is reachable.
18932   }
18933 
18934   Diag(Loc, PD);
18935   return true;
18936 }
18937 
18938 /// Emit a diagnostic that describes an effect on the run-time behavior
18939 /// of the program being compiled.
18940 ///
18941 /// This routine emits the given diagnostic when the code currently being
18942 /// type-checked is "potentially evaluated", meaning that there is a
18943 /// possibility that the code will actually be executable. Code in sizeof()
18944 /// expressions, code used only during overload resolution, etc., are not
18945 /// potentially evaluated. This routine will suppress such diagnostics or,
18946 /// in the absolutely nutty case of potentially potentially evaluated
18947 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18948 /// later.
18949 ///
18950 /// This routine should be used for all diagnostics that describe the run-time
18951 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18952 /// Failure to do so will likely result in spurious diagnostics or failures
18953 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18954 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18955                                const PartialDiagnostic &PD) {
18956   switch (ExprEvalContexts.back().Context) {
18957   case ExpressionEvaluationContext::Unevaluated:
18958   case ExpressionEvaluationContext::UnevaluatedList:
18959   case ExpressionEvaluationContext::UnevaluatedAbstract:
18960   case ExpressionEvaluationContext::DiscardedStatement:
18961     // The argument will never be evaluated, so don't complain.
18962     break;
18963 
18964   case ExpressionEvaluationContext::ConstantEvaluated:
18965   case ExpressionEvaluationContext::ImmediateFunctionContext:
18966     // Relevant diagnostics should be produced by constant evaluation.
18967     break;
18968 
18969   case ExpressionEvaluationContext::PotentiallyEvaluated:
18970   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18971     return DiagIfReachable(Loc, Stmts, PD);
18972   }
18973 
18974   return false;
18975 }
18976 
18977 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18978                                const PartialDiagnostic &PD) {
18979   return DiagRuntimeBehavior(
18980       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18981 }
18982 
18983 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18984                                CallExpr *CE, FunctionDecl *FD) {
18985   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18986     return false;
18987 
18988   // If we're inside a decltype's expression, don't check for a valid return
18989   // type or construct temporaries until we know whether this is the last call.
18990   if (ExprEvalContexts.back().ExprContext ==
18991       ExpressionEvaluationContextRecord::EK_Decltype) {
18992     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18993     return false;
18994   }
18995 
18996   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18997     FunctionDecl *FD;
18998     CallExpr *CE;
18999 
19000   public:
19001     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
19002       : FD(FD), CE(CE) { }
19003 
19004     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19005       if (!FD) {
19006         S.Diag(Loc, diag::err_call_incomplete_return)
19007           << T << CE->getSourceRange();
19008         return;
19009       }
19010 
19011       S.Diag(Loc, diag::err_call_function_incomplete_return)
19012           << CE->getSourceRange() << FD << T;
19013       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
19014           << FD->getDeclName();
19015     }
19016   } Diagnoser(FD, CE);
19017 
19018   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
19019     return true;
19020 
19021   return false;
19022 }
19023 
19024 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
19025 // will prevent this condition from triggering, which is what we want.
19026 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
19027   SourceLocation Loc;
19028 
19029   unsigned diagnostic = diag::warn_condition_is_assignment;
19030   bool IsOrAssign = false;
19031 
19032   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
19033     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
19034       return;
19035 
19036     IsOrAssign = Op->getOpcode() == BO_OrAssign;
19037 
19038     // Greylist some idioms by putting them into a warning subcategory.
19039     if (ObjCMessageExpr *ME
19040           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
19041       Selector Sel = ME->getSelector();
19042 
19043       // self = [<foo> init...]
19044       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
19045         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19046 
19047       // <foo> = [<bar> nextObject]
19048       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
19049         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19050     }
19051 
19052     Loc = Op->getOperatorLoc();
19053   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
19054     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
19055       return;
19056 
19057     IsOrAssign = Op->getOperator() == OO_PipeEqual;
19058     Loc = Op->getOperatorLoc();
19059   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
19060     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
19061   else {
19062     // Not an assignment.
19063     return;
19064   }
19065 
19066   Diag(Loc, diagnostic) << E->getSourceRange();
19067 
19068   SourceLocation Open = E->getBeginLoc();
19069   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
19070   Diag(Loc, diag::note_condition_assign_silence)
19071         << FixItHint::CreateInsertion(Open, "(")
19072         << FixItHint::CreateInsertion(Close, ")");
19073 
19074   if (IsOrAssign)
19075     Diag(Loc, diag::note_condition_or_assign_to_comparison)
19076       << FixItHint::CreateReplacement(Loc, "!=");
19077   else
19078     Diag(Loc, diag::note_condition_assign_to_comparison)
19079       << FixItHint::CreateReplacement(Loc, "==");
19080 }
19081 
19082 /// Redundant parentheses over an equality comparison can indicate
19083 /// that the user intended an assignment used as condition.
19084 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
19085   // Don't warn if the parens came from a macro.
19086   SourceLocation parenLoc = ParenE->getBeginLoc();
19087   if (parenLoc.isInvalid() || parenLoc.isMacroID())
19088     return;
19089   // Don't warn for dependent expressions.
19090   if (ParenE->isTypeDependent())
19091     return;
19092 
19093   Expr *E = ParenE->IgnoreParens();
19094 
19095   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
19096     if (opE->getOpcode() == BO_EQ &&
19097         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
19098                                                            == Expr::MLV_Valid) {
19099       SourceLocation Loc = opE->getOperatorLoc();
19100 
19101       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
19102       SourceRange ParenERange = ParenE->getSourceRange();
19103       Diag(Loc, diag::note_equality_comparison_silence)
19104         << FixItHint::CreateRemoval(ParenERange.getBegin())
19105         << FixItHint::CreateRemoval(ParenERange.getEnd());
19106       Diag(Loc, diag::note_equality_comparison_to_assign)
19107         << FixItHint::CreateReplacement(Loc, "=");
19108     }
19109 }
19110 
19111 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
19112                                        bool IsConstexpr) {
19113   DiagnoseAssignmentAsCondition(E);
19114   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
19115     DiagnoseEqualityWithExtraParens(parenE);
19116 
19117   ExprResult result = CheckPlaceholderExpr(E);
19118   if (result.isInvalid()) return ExprError();
19119   E = result.get();
19120 
19121   if (!E->isTypeDependent()) {
19122     if (getLangOpts().CPlusPlus)
19123       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
19124 
19125     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
19126     if (ERes.isInvalid())
19127       return ExprError();
19128     E = ERes.get();
19129 
19130     QualType T = E->getType();
19131     if (!T->isScalarType()) { // C99 6.8.4.1p1
19132       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
19133         << T << E->getSourceRange();
19134       return ExprError();
19135     }
19136     CheckBoolLikeConversion(E, Loc);
19137   }
19138 
19139   return E;
19140 }
19141 
19142 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
19143                                            Expr *SubExpr, ConditionKind CK) {
19144   // Empty conditions are valid in for-statements.
19145   if (!SubExpr)
19146     return ConditionResult();
19147 
19148   ExprResult Cond;
19149   switch (CK) {
19150   case ConditionKind::Boolean:
19151     Cond = CheckBooleanCondition(Loc, SubExpr);
19152     break;
19153 
19154   case ConditionKind::ConstexprIf:
19155     Cond = CheckBooleanCondition(Loc, SubExpr, true);
19156     break;
19157 
19158   case ConditionKind::Switch:
19159     Cond = CheckSwitchCondition(Loc, SubExpr);
19160     break;
19161   }
19162   if (Cond.isInvalid()) {
19163     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
19164                               {SubExpr});
19165     if (!Cond.get())
19166       return ConditionError();
19167   }
19168   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
19169   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
19170   if (!FullExpr.get())
19171     return ConditionError();
19172 
19173   return ConditionResult(*this, nullptr, FullExpr,
19174                          CK == ConditionKind::ConstexprIf);
19175 }
19176 
19177 namespace {
19178   /// A visitor for rebuilding a call to an __unknown_any expression
19179   /// to have an appropriate type.
19180   struct RebuildUnknownAnyFunction
19181     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
19182 
19183     Sema &S;
19184 
19185     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
19186 
19187     ExprResult VisitStmt(Stmt *S) {
19188       llvm_unreachable("unexpected statement!");
19189     }
19190 
19191     ExprResult VisitExpr(Expr *E) {
19192       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
19193         << E->getSourceRange();
19194       return ExprError();
19195     }
19196 
19197     /// Rebuild an expression which simply semantically wraps another
19198     /// expression which it shares the type and value kind of.
19199     template <class T> ExprResult rebuildSugarExpr(T *E) {
19200       ExprResult SubResult = Visit(E->getSubExpr());
19201       if (SubResult.isInvalid()) return ExprError();
19202 
19203       Expr *SubExpr = SubResult.get();
19204       E->setSubExpr(SubExpr);
19205       E->setType(SubExpr->getType());
19206       E->setValueKind(SubExpr->getValueKind());
19207       assert(E->getObjectKind() == OK_Ordinary);
19208       return E;
19209     }
19210 
19211     ExprResult VisitParenExpr(ParenExpr *E) {
19212       return rebuildSugarExpr(E);
19213     }
19214 
19215     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19216       return rebuildSugarExpr(E);
19217     }
19218 
19219     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19220       ExprResult SubResult = Visit(E->getSubExpr());
19221       if (SubResult.isInvalid()) return ExprError();
19222 
19223       Expr *SubExpr = SubResult.get();
19224       E->setSubExpr(SubExpr);
19225       E->setType(S.Context.getPointerType(SubExpr->getType()));
19226       assert(E->isPRValue());
19227       assert(E->getObjectKind() == OK_Ordinary);
19228       return E;
19229     }
19230 
19231     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
19232       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
19233 
19234       E->setType(VD->getType());
19235 
19236       assert(E->isPRValue());
19237       if (S.getLangOpts().CPlusPlus &&
19238           !(isa<CXXMethodDecl>(VD) &&
19239             cast<CXXMethodDecl>(VD)->isInstance()))
19240         E->setValueKind(VK_LValue);
19241 
19242       return E;
19243     }
19244 
19245     ExprResult VisitMemberExpr(MemberExpr *E) {
19246       return resolveDecl(E, E->getMemberDecl());
19247     }
19248 
19249     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19250       return resolveDecl(E, E->getDecl());
19251     }
19252   };
19253 }
19254 
19255 /// Given a function expression of unknown-any type, try to rebuild it
19256 /// to have a function type.
19257 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
19258   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
19259   if (Result.isInvalid()) return ExprError();
19260   return S.DefaultFunctionArrayConversion(Result.get());
19261 }
19262 
19263 namespace {
19264   /// A visitor for rebuilding an expression of type __unknown_anytype
19265   /// into one which resolves the type directly on the referring
19266   /// expression.  Strict preservation of the original source
19267   /// structure is not a goal.
19268   struct RebuildUnknownAnyExpr
19269     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
19270 
19271     Sema &S;
19272 
19273     /// The current destination type.
19274     QualType DestType;
19275 
19276     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
19277       : S(S), DestType(CastType) {}
19278 
19279     ExprResult VisitStmt(Stmt *S) {
19280       llvm_unreachable("unexpected statement!");
19281     }
19282 
19283     ExprResult VisitExpr(Expr *E) {
19284       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19285         << E->getSourceRange();
19286       return ExprError();
19287     }
19288 
19289     ExprResult VisitCallExpr(CallExpr *E);
19290     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
19291 
19292     /// Rebuild an expression which simply semantically wraps another
19293     /// expression which it shares the type and value kind of.
19294     template <class T> ExprResult rebuildSugarExpr(T *E) {
19295       ExprResult SubResult = Visit(E->getSubExpr());
19296       if (SubResult.isInvalid()) return ExprError();
19297       Expr *SubExpr = SubResult.get();
19298       E->setSubExpr(SubExpr);
19299       E->setType(SubExpr->getType());
19300       E->setValueKind(SubExpr->getValueKind());
19301       assert(E->getObjectKind() == OK_Ordinary);
19302       return E;
19303     }
19304 
19305     ExprResult VisitParenExpr(ParenExpr *E) {
19306       return rebuildSugarExpr(E);
19307     }
19308 
19309     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19310       return rebuildSugarExpr(E);
19311     }
19312 
19313     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19314       const PointerType *Ptr = DestType->getAs<PointerType>();
19315       if (!Ptr) {
19316         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
19317           << E->getSourceRange();
19318         return ExprError();
19319       }
19320 
19321       if (isa<CallExpr>(E->getSubExpr())) {
19322         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
19323           << E->getSourceRange();
19324         return ExprError();
19325       }
19326 
19327       assert(E->isPRValue());
19328       assert(E->getObjectKind() == OK_Ordinary);
19329       E->setType(DestType);
19330 
19331       // Build the sub-expression as if it were an object of the pointee type.
19332       DestType = Ptr->getPointeeType();
19333       ExprResult SubResult = Visit(E->getSubExpr());
19334       if (SubResult.isInvalid()) return ExprError();
19335       E->setSubExpr(SubResult.get());
19336       return E;
19337     }
19338 
19339     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
19340 
19341     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
19342 
19343     ExprResult VisitMemberExpr(MemberExpr *E) {
19344       return resolveDecl(E, E->getMemberDecl());
19345     }
19346 
19347     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19348       return resolveDecl(E, E->getDecl());
19349     }
19350   };
19351 }
19352 
19353 /// Rebuilds a call expression which yielded __unknown_anytype.
19354 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
19355   Expr *CalleeExpr = E->getCallee();
19356 
19357   enum FnKind {
19358     FK_MemberFunction,
19359     FK_FunctionPointer,
19360     FK_BlockPointer
19361   };
19362 
19363   FnKind Kind;
19364   QualType CalleeType = CalleeExpr->getType();
19365   if (CalleeType == S.Context.BoundMemberTy) {
19366     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
19367     Kind = FK_MemberFunction;
19368     CalleeType = Expr::findBoundMemberType(CalleeExpr);
19369   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
19370     CalleeType = Ptr->getPointeeType();
19371     Kind = FK_FunctionPointer;
19372   } else {
19373     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
19374     Kind = FK_BlockPointer;
19375   }
19376   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
19377 
19378   // Verify that this is a legal result type of a function.
19379   if (DestType->isArrayType() || DestType->isFunctionType()) {
19380     unsigned diagID = diag::err_func_returning_array_function;
19381     if (Kind == FK_BlockPointer)
19382       diagID = diag::err_block_returning_array_function;
19383 
19384     S.Diag(E->getExprLoc(), diagID)
19385       << DestType->isFunctionType() << DestType;
19386     return ExprError();
19387   }
19388 
19389   // Otherwise, go ahead and set DestType as the call's result.
19390   E->setType(DestType.getNonLValueExprType(S.Context));
19391   E->setValueKind(Expr::getValueKindForType(DestType));
19392   assert(E->getObjectKind() == OK_Ordinary);
19393 
19394   // Rebuild the function type, replacing the result type with DestType.
19395   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
19396   if (Proto) {
19397     // __unknown_anytype(...) is a special case used by the debugger when
19398     // it has no idea what a function's signature is.
19399     //
19400     // We want to build this call essentially under the K&R
19401     // unprototyped rules, but making a FunctionNoProtoType in C++
19402     // would foul up all sorts of assumptions.  However, we cannot
19403     // simply pass all arguments as variadic arguments, nor can we
19404     // portably just call the function under a non-variadic type; see
19405     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
19406     // However, it turns out that in practice it is generally safe to
19407     // call a function declared as "A foo(B,C,D);" under the prototype
19408     // "A foo(B,C,D,...);".  The only known exception is with the
19409     // Windows ABI, where any variadic function is implicitly cdecl
19410     // regardless of its normal CC.  Therefore we change the parameter
19411     // types to match the types of the arguments.
19412     //
19413     // This is a hack, but it is far superior to moving the
19414     // corresponding target-specific code from IR-gen to Sema/AST.
19415 
19416     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
19417     SmallVector<QualType, 8> ArgTypes;
19418     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
19419       ArgTypes.reserve(E->getNumArgs());
19420       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
19421         ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
19422       }
19423       ParamTypes = ArgTypes;
19424     }
19425     DestType = S.Context.getFunctionType(DestType, ParamTypes,
19426                                          Proto->getExtProtoInfo());
19427   } else {
19428     DestType = S.Context.getFunctionNoProtoType(DestType,
19429                                                 FnType->getExtInfo());
19430   }
19431 
19432   // Rebuild the appropriate pointer-to-function type.
19433   switch (Kind) {
19434   case FK_MemberFunction:
19435     // Nothing to do.
19436     break;
19437 
19438   case FK_FunctionPointer:
19439     DestType = S.Context.getPointerType(DestType);
19440     break;
19441 
19442   case FK_BlockPointer:
19443     DestType = S.Context.getBlockPointerType(DestType);
19444     break;
19445   }
19446 
19447   // Finally, we can recurse.
19448   ExprResult CalleeResult = Visit(CalleeExpr);
19449   if (!CalleeResult.isUsable()) return ExprError();
19450   E->setCallee(CalleeResult.get());
19451 
19452   // Bind a temporary if necessary.
19453   return S.MaybeBindToTemporary(E);
19454 }
19455 
19456 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
19457   // Verify that this is a legal result type of a call.
19458   if (DestType->isArrayType() || DestType->isFunctionType()) {
19459     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
19460       << DestType->isFunctionType() << DestType;
19461     return ExprError();
19462   }
19463 
19464   // Rewrite the method result type if available.
19465   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
19466     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
19467     Method->setReturnType(DestType);
19468   }
19469 
19470   // Change the type of the message.
19471   E->setType(DestType.getNonReferenceType());
19472   E->setValueKind(Expr::getValueKindForType(DestType));
19473 
19474   return S.MaybeBindToTemporary(E);
19475 }
19476 
19477 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
19478   // The only case we should ever see here is a function-to-pointer decay.
19479   if (E->getCastKind() == CK_FunctionToPointerDecay) {
19480     assert(E->isPRValue());
19481     assert(E->getObjectKind() == OK_Ordinary);
19482 
19483     E->setType(DestType);
19484 
19485     // Rebuild the sub-expression as the pointee (function) type.
19486     DestType = DestType->castAs<PointerType>()->getPointeeType();
19487 
19488     ExprResult Result = Visit(E->getSubExpr());
19489     if (!Result.isUsable()) return ExprError();
19490 
19491     E->setSubExpr(Result.get());
19492     return E;
19493   } else if (E->getCastKind() == CK_LValueToRValue) {
19494     assert(E->isPRValue());
19495     assert(E->getObjectKind() == OK_Ordinary);
19496 
19497     assert(isa<BlockPointerType>(E->getType()));
19498 
19499     E->setType(DestType);
19500 
19501     // The sub-expression has to be a lvalue reference, so rebuild it as such.
19502     DestType = S.Context.getLValueReferenceType(DestType);
19503 
19504     ExprResult Result = Visit(E->getSubExpr());
19505     if (!Result.isUsable()) return ExprError();
19506 
19507     E->setSubExpr(Result.get());
19508     return E;
19509   } else {
19510     llvm_unreachable("Unhandled cast type!");
19511   }
19512 }
19513 
19514 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
19515   ExprValueKind ValueKind = VK_LValue;
19516   QualType Type = DestType;
19517 
19518   // We know how to make this work for certain kinds of decls:
19519 
19520   //  - functions
19521   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
19522     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
19523       DestType = Ptr->getPointeeType();
19524       ExprResult Result = resolveDecl(E, VD);
19525       if (Result.isInvalid()) return ExprError();
19526       return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
19527                                  VK_PRValue);
19528     }
19529 
19530     if (!Type->isFunctionType()) {
19531       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
19532         << VD << E->getSourceRange();
19533       return ExprError();
19534     }
19535     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
19536       // We must match the FunctionDecl's type to the hack introduced in
19537       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
19538       // type. See the lengthy commentary in that routine.
19539       QualType FDT = FD->getType();
19540       const FunctionType *FnType = FDT->castAs<FunctionType>();
19541       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
19542       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19543       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19544         SourceLocation Loc = FD->getLocation();
19545         FunctionDecl *NewFD = FunctionDecl::Create(
19546             S.Context, FD->getDeclContext(), Loc, Loc,
19547             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19548             SC_None, S.getCurFPFeatures().isFPConstrained(),
19549             false /*isInlineSpecified*/, FD->hasPrototype(),
19550             /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
19551 
19552         if (FD->getQualifier())
19553           NewFD->setQualifierInfo(FD->getQualifierLoc());
19554 
19555         SmallVector<ParmVarDecl*, 16> Params;
19556         for (const auto &AI : FT->param_types()) {
19557           ParmVarDecl *Param =
19558             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19559           Param->setScopeInfo(0, Params.size());
19560           Params.push_back(Param);
19561         }
19562         NewFD->setParams(Params);
19563         DRE->setDecl(NewFD);
19564         VD = DRE->getDecl();
19565       }
19566     }
19567 
19568     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19569       if (MD->isInstance()) {
19570         ValueKind = VK_PRValue;
19571         Type = S.Context.BoundMemberTy;
19572       }
19573 
19574     // Function references aren't l-values in C.
19575     if (!S.getLangOpts().CPlusPlus)
19576       ValueKind = VK_PRValue;
19577 
19578   //  - variables
19579   } else if (isa<VarDecl>(VD)) {
19580     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19581       Type = RefTy->getPointeeType();
19582     } else if (Type->isFunctionType()) {
19583       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19584         << VD << E->getSourceRange();
19585       return ExprError();
19586     }
19587 
19588   //  - nothing else
19589   } else {
19590     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19591       << VD << E->getSourceRange();
19592     return ExprError();
19593   }
19594 
19595   // Modifying the declaration like this is friendly to IR-gen but
19596   // also really dangerous.
19597   VD->setType(DestType);
19598   E->setType(Type);
19599   E->setValueKind(ValueKind);
19600   return E;
19601 }
19602 
19603 /// Check a cast of an unknown-any type.  We intentionally only
19604 /// trigger this for C-style casts.
19605 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19606                                      Expr *CastExpr, CastKind &CastKind,
19607                                      ExprValueKind &VK, CXXCastPath &Path) {
19608   // The type we're casting to must be either void or complete.
19609   if (!CastType->isVoidType() &&
19610       RequireCompleteType(TypeRange.getBegin(), CastType,
19611                           diag::err_typecheck_cast_to_incomplete))
19612     return ExprError();
19613 
19614   // Rewrite the casted expression from scratch.
19615   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19616   if (!result.isUsable()) return ExprError();
19617 
19618   CastExpr = result.get();
19619   VK = CastExpr->getValueKind();
19620   CastKind = CK_NoOp;
19621 
19622   return CastExpr;
19623 }
19624 
19625 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19626   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19627 }
19628 
19629 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19630                                     Expr *arg, QualType &paramType) {
19631   // If the syntactic form of the argument is not an explicit cast of
19632   // any sort, just do default argument promotion.
19633   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19634   if (!castArg) {
19635     ExprResult result = DefaultArgumentPromotion(arg);
19636     if (result.isInvalid()) return ExprError();
19637     paramType = result.get()->getType();
19638     return result;
19639   }
19640 
19641   // Otherwise, use the type that was written in the explicit cast.
19642   assert(!arg->hasPlaceholderType());
19643   paramType = castArg->getTypeAsWritten();
19644 
19645   // Copy-initialize a parameter of that type.
19646   InitializedEntity entity =
19647     InitializedEntity::InitializeParameter(Context, paramType,
19648                                            /*consumed*/ false);
19649   return PerformCopyInitialization(entity, callLoc, arg);
19650 }
19651 
19652 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19653   Expr *orig = E;
19654   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19655   while (true) {
19656     E = E->IgnoreParenImpCasts();
19657     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19658       E = call->getCallee();
19659       diagID = diag::err_uncasted_call_of_unknown_any;
19660     } else {
19661       break;
19662     }
19663   }
19664 
19665   SourceLocation loc;
19666   NamedDecl *d;
19667   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19668     loc = ref->getLocation();
19669     d = ref->getDecl();
19670   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19671     loc = mem->getMemberLoc();
19672     d = mem->getMemberDecl();
19673   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19674     diagID = diag::err_uncasted_call_of_unknown_any;
19675     loc = msg->getSelectorStartLoc();
19676     d = msg->getMethodDecl();
19677     if (!d) {
19678       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19679         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19680         << orig->getSourceRange();
19681       return ExprError();
19682     }
19683   } else {
19684     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19685       << E->getSourceRange();
19686     return ExprError();
19687   }
19688 
19689   S.Diag(loc, diagID) << d << orig->getSourceRange();
19690 
19691   // Never recoverable.
19692   return ExprError();
19693 }
19694 
19695 /// Check for operands with placeholder types and complain if found.
19696 /// Returns ExprError() if there was an error and no recovery was possible.
19697 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19698   if (!Context.isDependenceAllowed()) {
19699     // C cannot handle TypoExpr nodes on either side of a binop because it
19700     // doesn't handle dependent types properly, so make sure any TypoExprs have
19701     // been dealt with before checking the operands.
19702     ExprResult Result = CorrectDelayedTyposInExpr(E);
19703     if (!Result.isUsable()) return ExprError();
19704     E = Result.get();
19705   }
19706 
19707   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19708   if (!placeholderType) return E;
19709 
19710   switch (placeholderType->getKind()) {
19711 
19712   // Overloaded expressions.
19713   case BuiltinType::Overload: {
19714     // Try to resolve a single function template specialization.
19715     // This is obligatory.
19716     ExprResult Result = E;
19717     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19718       return Result;
19719 
19720     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19721     // leaves Result unchanged on failure.
19722     Result = E;
19723     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19724       return Result;
19725 
19726     // If that failed, try to recover with a call.
19727     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19728                          /*complain*/ true);
19729     return Result;
19730   }
19731 
19732   // Bound member functions.
19733   case BuiltinType::BoundMember: {
19734     ExprResult result = E;
19735     const Expr *BME = E->IgnoreParens();
19736     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19737     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19738     if (isa<CXXPseudoDestructorExpr>(BME)) {
19739       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19740     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19741       if (ME->getMemberNameInfo().getName().getNameKind() ==
19742           DeclarationName::CXXDestructorName)
19743         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19744     }
19745     tryToRecoverWithCall(result, PD,
19746                          /*complain*/ true);
19747     return result;
19748   }
19749 
19750   // ARC unbridged casts.
19751   case BuiltinType::ARCUnbridgedCast: {
19752     Expr *realCast = stripARCUnbridgedCast(E);
19753     diagnoseARCUnbridgedCast(realCast);
19754     return realCast;
19755   }
19756 
19757   // Expressions of unknown type.
19758   case BuiltinType::UnknownAny:
19759     return diagnoseUnknownAnyExpr(*this, E);
19760 
19761   // Pseudo-objects.
19762   case BuiltinType::PseudoObject:
19763     return checkPseudoObjectRValue(E);
19764 
19765   case BuiltinType::BuiltinFn: {
19766     // Accept __noop without parens by implicitly converting it to a call expr.
19767     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19768     if (DRE) {
19769       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19770       if (FD->getBuiltinID() == Builtin::BI__noop) {
19771         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19772                               CK_BuiltinFnToFnPtr)
19773                 .get();
19774         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19775                                 VK_PRValue, SourceLocation(),
19776                                 FPOptionsOverride());
19777       }
19778     }
19779 
19780     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19781     return ExprError();
19782   }
19783 
19784   case BuiltinType::IncompleteMatrixIdx:
19785     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19786              ->getRowIdx()
19787              ->getBeginLoc(),
19788          diag::err_matrix_incomplete_index);
19789     return ExprError();
19790 
19791   // Expressions of unknown type.
19792   case BuiltinType::OMPArraySection:
19793     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19794     return ExprError();
19795 
19796   // Expressions of unknown type.
19797   case BuiltinType::OMPArrayShaping:
19798     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19799 
19800   case BuiltinType::OMPIterator:
19801     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19802 
19803   // Everything else should be impossible.
19804 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19805   case BuiltinType::Id:
19806 #include "clang/Basic/OpenCLImageTypes.def"
19807 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19808   case BuiltinType::Id:
19809 #include "clang/Basic/OpenCLExtensionTypes.def"
19810 #define SVE_TYPE(Name, Id, SingletonId) \
19811   case BuiltinType::Id:
19812 #include "clang/Basic/AArch64SVEACLETypes.def"
19813 #define PPC_VECTOR_TYPE(Name, Id, Size) \
19814   case BuiltinType::Id:
19815 #include "clang/Basic/PPCTypes.def"
19816 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
19817 #include "clang/Basic/RISCVVTypes.def"
19818 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19819 #define PLACEHOLDER_TYPE(Id, SingletonId)
19820 #include "clang/AST/BuiltinTypes.def"
19821     break;
19822   }
19823 
19824   llvm_unreachable("invalid placeholder type!");
19825 }
19826 
19827 bool Sema::CheckCaseExpression(Expr *E) {
19828   if (E->isTypeDependent())
19829     return true;
19830   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19831     return E->getType()->isIntegralOrEnumerationType();
19832   return false;
19833 }
19834 
19835 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19836 ExprResult
19837 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19838   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19839          "Unknown Objective-C Boolean value!");
19840   QualType BoolT = Context.ObjCBuiltinBoolTy;
19841   if (!Context.getBOOLDecl()) {
19842     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19843                         Sema::LookupOrdinaryName);
19844     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19845       NamedDecl *ND = Result.getFoundDecl();
19846       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19847         Context.setBOOLDecl(TD);
19848     }
19849   }
19850   if (Context.getBOOLDecl())
19851     BoolT = Context.getBOOLType();
19852   return new (Context)
19853       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19854 }
19855 
19856 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19857     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19858     SourceLocation RParen) {
19859   auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
19860     auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19861       return Spec.getPlatform() == Platform;
19862     });
19863     // Transcribe the "ios" availability check to "maccatalyst" when compiling
19864     // for "maccatalyst" if "maccatalyst" is not specified.
19865     if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
19866       Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19867         return Spec.getPlatform() == "ios";
19868       });
19869     }
19870     if (Spec == AvailSpecs.end())
19871       return None;
19872     return Spec->getVersion();
19873   };
19874 
19875   VersionTuple Version;
19876   if (auto MaybeVersion =
19877           FindSpecVersion(Context.getTargetInfo().getPlatformName()))
19878     Version = *MaybeVersion;
19879 
19880   // The use of `@available` in the enclosing context should be analyzed to
19881   // warn when it's used inappropriately (i.e. not if(@available)).
19882   if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
19883     Context->HasPotentialAvailabilityViolations = true;
19884 
19885   return new (Context)
19886       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19887 }
19888 
19889 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19890                                     ArrayRef<Expr *> SubExprs, QualType T) {
19891   if (!Context.getLangOpts().RecoveryAST)
19892     return ExprError();
19893 
19894   if (isSFINAEContext())
19895     return ExprError();
19896 
19897   if (T.isNull() || T->isUndeducedType() ||
19898       !Context.getLangOpts().RecoveryASTType)
19899     // We don't know the concrete type, fallback to dependent type.
19900     T = Context.DependentTy;
19901 
19902   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19903 }
19904