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/Type.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/DiagnosticSema.h"
34 #include "clang/Basic/PartialDiagnostic.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/Specifiers.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Lex/LiteralSupport.h"
39 #include "clang/Lex/Preprocessor.h"
40 #include "clang/Sema/AnalysisBasedWarnings.h"
41 #include "clang/Sema/DeclSpec.h"
42 #include "clang/Sema/DelayedDiagnostic.h"
43 #include "clang/Sema/Designator.h"
44 #include "clang/Sema/Initialization.h"
45 #include "clang/Sema/Lookup.h"
46 #include "clang/Sema/Overload.h"
47 #include "clang/Sema/ParsedTemplate.h"
48 #include "clang/Sema/Scope.h"
49 #include "clang/Sema/ScopeInfo.h"
50 #include "clang/Sema/SemaFixItUtils.h"
51 #include "clang/Sema/SemaInternal.h"
52 #include "clang/Sema/Template.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/ConvertUTF.h"
57 #include "llvm/Support/SaveAndRestore.h"
58 #include "llvm/Support/TypeSize.h"
59 
60 using namespace clang;
61 using namespace sema;
62 
63 /// Determine whether the use of this declaration is valid, without
64 /// emitting diagnostics.
65 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
66   // See if this is an auto-typed variable whose initializer we are parsing.
67   if (ParsingInitForAutoVars.count(D))
68     return false;
69 
70   // See if this is a deleted function.
71   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
72     if (FD->isDeleted())
73       return false;
74 
75     // If the function has a deduced return type, and we can't deduce it,
76     // then we can't use it either.
77     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
78         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
79       return false;
80 
81     // See if this is an aligned allocation/deallocation function that is
82     // unavailable.
83     if (TreatUnavailableAsInvalid &&
84         isUnavailableAlignedAllocationFunction(*FD))
85       return false;
86   }
87 
88   // See if this function is unavailable.
89   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
90       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
91     return false;
92 
93   if (isa<UnresolvedUsingIfExistsDecl>(D))
94     return false;
95 
96   return true;
97 }
98 
99 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
100   // Warn if this is used but marked unused.
101   if (const auto *A = D->getAttr<UnusedAttr>()) {
102     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
103     // should diagnose them.
104     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
105         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
106       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
107       if (DC && !DC->hasAttr<UnusedAttr>())
108         S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
109     }
110   }
111 }
112 
113 /// Emit a note explaining that this function is deleted.
114 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
115   assert(Decl && Decl->isDeleted());
116 
117   if (Decl->isDefaulted()) {
118     // If the method was explicitly defaulted, point at that declaration.
119     if (!Decl->isImplicit())
120       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
121 
122     // Try to diagnose why this special member function was implicitly
123     // deleted. This might fail, if that reason no longer applies.
124     DiagnoseDeletedDefaultedFunction(Decl);
125     return;
126   }
127 
128   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
129   if (Ctor && Ctor->isInheritingConstructor())
130     return NoteDeletedInheritingConstructor(Ctor);
131 
132   Diag(Decl->getLocation(), diag::note_availability_specified_here)
133     << Decl << 1;
134 }
135 
136 /// Determine whether a FunctionDecl was ever declared with an
137 /// explicit storage class.
138 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
139   for (auto I : D->redecls()) {
140     if (I->getStorageClass() != SC_None)
141       return true;
142   }
143   return false;
144 }
145 
146 /// Check whether we're in an extern inline function and referring to a
147 /// variable or function with internal linkage (C11 6.7.4p3).
148 ///
149 /// This is only a warning because we used to silently accept this code, but
150 /// in many cases it will not behave correctly. This is not enabled in C++ mode
151 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
152 /// and so while there may still be user mistakes, most of the time we can't
153 /// prove that there are errors.
154 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
155                                                       const NamedDecl *D,
156                                                       SourceLocation Loc) {
157   // This is disabled under C++; there are too many ways for this to fire in
158   // contexts where the warning is a false positive, or where it is technically
159   // correct but benign.
160   if (S.getLangOpts().CPlusPlus)
161     return;
162 
163   // Check if this is an inlined function or method.
164   FunctionDecl *Current = S.getCurFunctionDecl();
165   if (!Current)
166     return;
167   if (!Current->isInlined())
168     return;
169   if (!Current->isExternallyVisible())
170     return;
171 
172   // Check if the decl has internal linkage.
173   if (D->getFormalLinkage() != InternalLinkage)
174     return;
175 
176   // Downgrade from ExtWarn to Extension if
177   //  (1) the supposedly external inline function is in the main file,
178   //      and probably won't be included anywhere else.
179   //  (2) the thing we're referencing is a pure function.
180   //  (3) the thing we're referencing is another inline function.
181   // This last can give us false negatives, but it's better than warning on
182   // wrappers for simple C library functions.
183   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
184   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
185   if (!DowngradeWarning && UsedFn)
186     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
187 
188   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
189                                : diag::ext_internal_in_extern_inline)
190     << /*IsVar=*/!UsedFn << D;
191 
192   S.MaybeSuggestAddingStaticToDecl(Current);
193 
194   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
195       << D;
196 }
197 
198 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
199   const FunctionDecl *First = Cur->getFirstDecl();
200 
201   // Suggest "static" on the function, if possible.
202   if (!hasAnyExplicitStorageClass(First)) {
203     SourceLocation DeclBegin = First->getSourceRange().getBegin();
204     Diag(DeclBegin, diag::note_convert_inline_to_static)
205       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
206   }
207 }
208 
209 /// Determine whether the use of this declaration is valid, and
210 /// emit any corresponding diagnostics.
211 ///
212 /// This routine diagnoses various problems with referencing
213 /// declarations that can occur when using a declaration. For example,
214 /// it might warn if a deprecated or unavailable declaration is being
215 /// used, or produce an error (and return true) if a C++0x deleted
216 /// function is being used.
217 ///
218 /// \returns true if there was an error (this declaration cannot be
219 /// referenced), false otherwise.
220 ///
221 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
222                              const ObjCInterfaceDecl *UnknownObjCClass,
223                              bool ObjCPropertyAccess,
224                              bool AvoidPartialAvailabilityChecks,
225                              ObjCInterfaceDecl *ClassReceiver) {
226   SourceLocation Loc = Locs.front();
227   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
228     // If there were any diagnostics suppressed by template argument deduction,
229     // emit them now.
230     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
231     if (Pos != SuppressedDiagnostics.end()) {
232       for (const PartialDiagnosticAt &Suppressed : Pos->second)
233         Diag(Suppressed.first, Suppressed.second);
234 
235       // Clear out the list of suppressed diagnostics, so that we don't emit
236       // them again for this specialization. However, we don't obsolete this
237       // entry from the table, because we want to avoid ever emitting these
238       // diagnostics again.
239       Pos->second.clear();
240     }
241 
242     // C++ [basic.start.main]p3:
243     //   The function 'main' shall not be used within a program.
244     if (cast<FunctionDecl>(D)->isMain())
245       Diag(Loc, diag::ext_main_used);
246 
247     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
248   }
249 
250   // See if this is an auto-typed variable whose initializer we are parsing.
251   if (ParsingInitForAutoVars.count(D)) {
252     if (isa<BindingDecl>(D)) {
253       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
254         << D->getDeclName();
255     } else {
256       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
257         << D->getDeclName() << cast<VarDecl>(D)->getType();
258     }
259     return true;
260   }
261 
262   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
263     // See if this is a deleted function.
264     if (FD->isDeleted()) {
265       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
266       if (Ctor && Ctor->isInheritingConstructor())
267         Diag(Loc, diag::err_deleted_inherited_ctor_use)
268             << Ctor->getParent()
269             << Ctor->getInheritedConstructor().getConstructor()->getParent();
270       else
271         Diag(Loc, diag::err_deleted_function_use);
272       NoteDeletedFunction(FD);
273       return true;
274     }
275 
276     // [expr.prim.id]p4
277     //   A program that refers explicitly or implicitly to a function with a
278     //   trailing requires-clause whose constraint-expression is not satisfied,
279     //   other than to declare it, is ill-formed. [...]
280     //
281     // See if this is a function with constraints that need to be satisfied.
282     // Check this before deducing the return type, as it might instantiate the
283     // definition.
284     if (FD->getTrailingRequiresClause()) {
285       ConstraintSatisfaction Satisfaction;
286       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
287         // A diagnostic will have already been generated (non-constant
288         // constraint expression, for example)
289         return true;
290       if (!Satisfaction.IsSatisfied) {
291         Diag(Loc,
292              diag::err_reference_to_function_with_unsatisfied_constraints)
293             << D;
294         DiagnoseUnsatisfiedConstraint(Satisfaction);
295         return true;
296       }
297     }
298 
299     // If the function has a deduced return type, and we can't deduce it,
300     // then we can't use it either.
301     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
302         DeduceReturnType(FD, Loc))
303       return true;
304 
305     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
306       return true;
307 
308     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
309       return true;
310   }
311 
312   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
313     // Lambdas are only default-constructible or assignable in C++2a onwards.
314     if (MD->getParent()->isLambda() &&
315         ((isa<CXXConstructorDecl>(MD) &&
316           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
317          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
318       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
319         << !isa<CXXConstructorDecl>(MD);
320     }
321   }
322 
323   auto getReferencedObjCProp = [](const NamedDecl *D) ->
324                                       const ObjCPropertyDecl * {
325     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
326       return MD->findPropertyDecl();
327     return nullptr;
328   };
329   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
330     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
331       return true;
332   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
333       return true;
334   }
335 
336   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
337   // Only the variables omp_in and omp_out are allowed in the combiner.
338   // Only the variables omp_priv and omp_orig are allowed in the
339   // initializer-clause.
340   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
341   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
342       isa<VarDecl>(D)) {
343     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
344         << getCurFunction()->HasOMPDeclareReductionCombiner;
345     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
346     return true;
347   }
348 
349   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
350   //  List-items in map clauses on this construct may only refer to the declared
351   //  variable var and entities that could be referenced by a procedure defined
352   //  at the same location
353   if (LangOpts.OpenMP && isa<VarDecl>(D) &&
354       !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
355     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
356         << getOpenMPDeclareMapperVarName();
357     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
358     return true;
359   }
360 
361   if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
362     Diag(Loc, diag::err_use_of_empty_using_if_exists);
363     Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
364     return true;
365   }
366 
367   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
368                              AvoidPartialAvailabilityChecks, ClassReceiver);
369 
370   DiagnoseUnusedOfDecl(*this, D, Loc);
371 
372   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
373 
374   if (auto *VD = dyn_cast<ValueDecl>(D))
375     checkTypeSupport(VD->getType(), Loc, VD);
376 
377   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
378     if (!Context.getTargetInfo().isTLSSupported())
379       if (const auto *VD = dyn_cast<VarDecl>(D))
380         if (VD->getTLSKind() != VarDecl::TLS_None)
381           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
382   }
383 
384   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
385       !isUnevaluatedContext()) {
386     // C++ [expr.prim.req.nested] p3
387     //   A local parameter shall only appear as an unevaluated operand
388     //   (Clause 8) within the constraint-expression.
389     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
390         << D;
391     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
392     return true;
393   }
394 
395   return false;
396 }
397 
398 /// DiagnoseSentinelCalls - This routine checks whether a call or
399 /// message-send is to a declaration with the sentinel attribute, and
400 /// if so, it checks that the requirements of the sentinel are
401 /// satisfied.
402 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
403                                  ArrayRef<Expr *> Args) {
404   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
405   if (!attr)
406     return;
407 
408   // The number of formal parameters of the declaration.
409   unsigned numFormalParams;
410 
411   // The kind of declaration.  This is also an index into a %select in
412   // the diagnostic.
413   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
414 
415   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
416     numFormalParams = MD->param_size();
417     calleeType = CT_Method;
418   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
419     numFormalParams = FD->param_size();
420     calleeType = CT_Function;
421   } else if (isa<VarDecl>(D)) {
422     QualType type = cast<ValueDecl>(D)->getType();
423     const FunctionType *fn = nullptr;
424     if (const PointerType *ptr = type->getAs<PointerType>()) {
425       fn = ptr->getPointeeType()->getAs<FunctionType>();
426       if (!fn) return;
427       calleeType = CT_Function;
428     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
429       fn = ptr->getPointeeType()->castAs<FunctionType>();
430       calleeType = CT_Block;
431     } else {
432       return;
433     }
434 
435     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
436       numFormalParams = proto->getNumParams();
437     } else {
438       numFormalParams = 0;
439     }
440   } else {
441     return;
442   }
443 
444   // "nullPos" is the number of formal parameters at the end which
445   // effectively count as part of the variadic arguments.  This is
446   // useful if you would prefer to not have *any* formal parameters,
447   // but the language forces you to have at least one.
448   unsigned nullPos = attr->getNullPos();
449   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
450   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
451 
452   // The number of arguments which should follow the sentinel.
453   unsigned numArgsAfterSentinel = attr->getSentinel();
454 
455   // If there aren't enough arguments for all the formal parameters,
456   // the sentinel, and the args after the sentinel, complain.
457   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
458     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
459     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
460     return;
461   }
462 
463   // Otherwise, find the sentinel expression.
464   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
465   if (!sentinelExpr) return;
466   if (sentinelExpr->isValueDependent()) return;
467   if (Context.isSentinelNullExpr(sentinelExpr)) return;
468 
469   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
470   // or 'NULL' if those are actually defined in the context.  Only use
471   // 'nil' for ObjC methods, where it's much more likely that the
472   // variadic arguments form a list of object pointers.
473   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
474   std::string NullValue;
475   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
476     NullValue = "nil";
477   else if (getLangOpts().CPlusPlus11)
478     NullValue = "nullptr";
479   else if (PP.isMacroDefined("NULL"))
480     NullValue = "NULL";
481   else
482     NullValue = "(void*) 0";
483 
484   if (MissingNilLoc.isInvalid())
485     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
486   else
487     Diag(MissingNilLoc, diag::warn_missing_sentinel)
488       << int(calleeType)
489       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
490   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
491 }
492 
493 SourceRange Sema::getExprRange(Expr *E) const {
494   return E ? E->getSourceRange() : SourceRange();
495 }
496 
497 //===----------------------------------------------------------------------===//
498 //  Standard Promotions and Conversions
499 //===----------------------------------------------------------------------===//
500 
501 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
502 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
503   // Handle any placeholder expressions which made it here.
504   if (E->hasPlaceholderType()) {
505     ExprResult result = CheckPlaceholderExpr(E);
506     if (result.isInvalid()) return ExprError();
507     E = result.get();
508   }
509 
510   QualType Ty = E->getType();
511   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
512 
513   if (Ty->isFunctionType()) {
514     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
515       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
516         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
517           return ExprError();
518 
519     E = ImpCastExprToType(E, Context.getPointerType(Ty),
520                           CK_FunctionToPointerDecay).get();
521   } else if (Ty->isArrayType()) {
522     // In C90 mode, arrays only promote to pointers if the array expression is
523     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
524     // type 'array of type' is converted to an expression that has type 'pointer
525     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
526     // that has type 'array of type' ...".  The relevant change is "an lvalue"
527     // (C90) to "an expression" (C99).
528     //
529     // C++ 4.2p1:
530     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
531     // T" can be converted to an rvalue of type "pointer to T".
532     //
533     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
534       ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
535                                          CK_ArrayToPointerDecay);
536       if (Res.isInvalid())
537         return ExprError();
538       E = Res.get();
539     }
540   }
541   return E;
542 }
543 
544 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
545   // Check to see if we are dereferencing a null pointer.  If so,
546   // and if not volatile-qualified, this is undefined behavior that the
547   // optimizer will delete, so warn about it.  People sometimes try to use this
548   // to get a deterministic trap and are surprised by clang's behavior.  This
549   // only handles the pattern "*null", which is a very syntactic check.
550   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
551   if (UO && UO->getOpcode() == UO_Deref &&
552       UO->getSubExpr()->getType()->isPointerType()) {
553     const LangAS AS =
554         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
555     if ((!isTargetAddressSpace(AS) ||
556          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
557         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
558             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
559         !UO->getType().isVolatileQualified()) {
560       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
561                             S.PDiag(diag::warn_indirection_through_null)
562                                 << UO->getSubExpr()->getSourceRange());
563       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
564                             S.PDiag(diag::note_indirection_through_null));
565     }
566   }
567 }
568 
569 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
570                                     SourceLocation AssignLoc,
571                                     const Expr* RHS) {
572   const ObjCIvarDecl *IV = OIRE->getDecl();
573   if (!IV)
574     return;
575 
576   DeclarationName MemberName = IV->getDeclName();
577   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
578   if (!Member || !Member->isStr("isa"))
579     return;
580 
581   const Expr *Base = OIRE->getBase();
582   QualType BaseType = Base->getType();
583   if (OIRE->isArrow())
584     BaseType = BaseType->getPointeeType();
585   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
586     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
587       ObjCInterfaceDecl *ClassDeclared = nullptr;
588       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
589       if (!ClassDeclared->getSuperClass()
590           && (*ClassDeclared->ivar_begin()) == IV) {
591         if (RHS) {
592           NamedDecl *ObjectSetClass =
593             S.LookupSingleName(S.TUScope,
594                                &S.Context.Idents.get("object_setClass"),
595                                SourceLocation(), S.LookupOrdinaryName);
596           if (ObjectSetClass) {
597             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
598             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
599                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
600                                               "object_setClass(")
601                 << FixItHint::CreateReplacement(
602                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
603                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
604           }
605           else
606             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
607         } else {
608           NamedDecl *ObjectGetClass =
609             S.LookupSingleName(S.TUScope,
610                                &S.Context.Idents.get("object_getClass"),
611                                SourceLocation(), S.LookupOrdinaryName);
612           if (ObjectGetClass)
613             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
614                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
615                                               "object_getClass(")
616                 << FixItHint::CreateReplacement(
617                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
618           else
619             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
620         }
621         S.Diag(IV->getLocation(), diag::note_ivar_decl);
622       }
623     }
624 }
625 
626 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
627   // Handle any placeholder expressions which made it here.
628   if (E->hasPlaceholderType()) {
629     ExprResult result = CheckPlaceholderExpr(E);
630     if (result.isInvalid()) return ExprError();
631     E = result.get();
632   }
633 
634   // C++ [conv.lval]p1:
635   //   A glvalue of a non-function, non-array type T can be
636   //   converted to a prvalue.
637   if (!E->isGLValue()) return E;
638 
639   QualType T = E->getType();
640   assert(!T.isNull() && "r-value conversion on typeless expression?");
641 
642   // lvalue-to-rvalue conversion cannot be applied to function or array types.
643   if (T->isFunctionType() || T->isArrayType())
644     return E;
645 
646   // We don't want to throw lvalue-to-rvalue casts on top of
647   // expressions of certain types in C++.
648   if (getLangOpts().CPlusPlus &&
649       (E->getType() == Context.OverloadTy ||
650        T->isDependentType() ||
651        T->isRecordType()))
652     return E;
653 
654   // The C standard is actually really unclear on this point, and
655   // DR106 tells us what the result should be but not why.  It's
656   // generally best to say that void types just doesn't undergo
657   // lvalue-to-rvalue at all.  Note that expressions of unqualified
658   // 'void' type are never l-values, but qualified void can be.
659   if (T->isVoidType())
660     return E;
661 
662   // OpenCL usually rejects direct accesses to values of 'half' type.
663   if (getLangOpts().OpenCL &&
664       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
665       T->isHalfType()) {
666     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
667       << 0 << T;
668     return ExprError();
669   }
670 
671   CheckForNullPointerDereference(*this, E);
672   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
673     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
674                                      &Context.Idents.get("object_getClass"),
675                                      SourceLocation(), LookupOrdinaryName);
676     if (ObjectGetClass)
677       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
678           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
679           << FixItHint::CreateReplacement(
680                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
681     else
682       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
683   }
684   else if (const ObjCIvarRefExpr *OIRE =
685             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
686     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
687 
688   // C++ [conv.lval]p1:
689   //   [...] If T is a non-class type, the type of the prvalue is the
690   //   cv-unqualified version of T. Otherwise, the type of the
691   //   rvalue is T.
692   //
693   // C99 6.3.2.1p2:
694   //   If the lvalue has qualified type, the value has the unqualified
695   //   version of the type of the lvalue; otherwise, the value has the
696   //   type of the lvalue.
697   if (T.hasQualifiers())
698     T = T.getUnqualifiedType();
699 
700   // Under the MS ABI, lock down the inheritance model now.
701   if (T->isMemberPointerType() &&
702       Context.getTargetInfo().getCXXABI().isMicrosoft())
703     (void)isCompleteType(E->getExprLoc(), T);
704 
705   ExprResult Res = CheckLValueToRValueConversionOperand(E);
706   if (Res.isInvalid())
707     return Res;
708   E = Res.get();
709 
710   // Loading a __weak object implicitly retains the value, so we need a cleanup to
711   // balance that.
712   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
713     Cleanup.setExprNeedsCleanups(true);
714 
715   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
716     Cleanup.setExprNeedsCleanups(true);
717 
718   // C++ [conv.lval]p3:
719   //   If T is cv std::nullptr_t, the result is a null pointer constant.
720   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
721   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
722                                  CurFPFeatureOverrides());
723 
724   // C11 6.3.2.1p2:
725   //   ... if the lvalue has atomic type, the value has the non-atomic version
726   //   of the type of the lvalue ...
727   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
728     T = Atomic->getValueType().getUnqualifiedType();
729     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
730                                    nullptr, VK_PRValue, FPOptionsOverride());
731   }
732 
733   return Res;
734 }
735 
736 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
737   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
738   if (Res.isInvalid())
739     return ExprError();
740   Res = DefaultLvalueConversion(Res.get());
741   if (Res.isInvalid())
742     return ExprError();
743   return Res;
744 }
745 
746 /// CallExprUnaryConversions - a special case of an unary conversion
747 /// performed on a function designator of a call expression.
748 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
749   QualType Ty = E->getType();
750   ExprResult Res = E;
751   // Only do implicit cast for a function type, but not for a pointer
752   // to function type.
753   if (Ty->isFunctionType()) {
754     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
755                             CK_FunctionToPointerDecay);
756     if (Res.isInvalid())
757       return ExprError();
758   }
759   Res = DefaultLvalueConversion(Res.get());
760   if (Res.isInvalid())
761     return ExprError();
762   return Res.get();
763 }
764 
765 /// UsualUnaryConversions - Performs various conversions that are common to most
766 /// operators (C99 6.3). The conversions of array and function types are
767 /// sometimes suppressed. For example, the array->pointer conversion doesn't
768 /// apply if the array is an argument to the sizeof or address (&) operators.
769 /// In these instances, this routine should *not* be called.
770 ExprResult Sema::UsualUnaryConversions(Expr *E) {
771   // First, convert to an r-value.
772   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
773   if (Res.isInvalid())
774     return ExprError();
775   E = Res.get();
776 
777   QualType Ty = E->getType();
778   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
779 
780   LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
781   if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
782       (getLangOpts().getFPEvalMethod() !=
783            LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
784        PP.getLastFPEvalPragmaLocation().isValid())) {
785     switch (EvalMethod) {
786     default:
787       llvm_unreachable("Unrecognized float evaluation method");
788       break;
789     case LangOptions::FEM_UnsetOnCommandLine:
790       llvm_unreachable("Float evaluation method should be set by now");
791       break;
792     case LangOptions::FEM_Double:
793       if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
794         // Widen the expression to double.
795         return Ty->isComplexType()
796                    ? ImpCastExprToType(E,
797                                        Context.getComplexType(Context.DoubleTy),
798                                        CK_FloatingComplexCast)
799                    : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
800       break;
801     case LangOptions::FEM_Extended:
802       if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
803         // Widen the expression to long double.
804         return Ty->isComplexType()
805                    ? ImpCastExprToType(
806                          E, Context.getComplexType(Context.LongDoubleTy),
807                          CK_FloatingComplexCast)
808                    : ImpCastExprToType(E, Context.LongDoubleTy,
809                                        CK_FloatingCast);
810       break;
811     }
812   }
813 
814   // Half FP have to be promoted to float unless it is natively supported
815   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
816     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
817 
818   // Try to perform integral promotions if the object has a theoretically
819   // promotable type.
820   if (Ty->isIntegralOrUnscopedEnumerationType()) {
821     // C99 6.3.1.1p2:
822     //
823     //   The following may be used in an expression wherever an int or
824     //   unsigned int may be used:
825     //     - an object or expression with an integer type whose integer
826     //       conversion rank is less than or equal to the rank of int
827     //       and unsigned int.
828     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
829     //
830     //   If an int can represent all values of the original type, the
831     //   value is converted to an int; otherwise, it is converted to an
832     //   unsigned int. These are called the integer promotions. All
833     //   other types are unchanged by the integer promotions.
834 
835     QualType PTy = Context.isPromotableBitField(E);
836     if (!PTy.isNull()) {
837       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
838       return E;
839     }
840     if (Ty->isPromotableIntegerType()) {
841       QualType PT = Context.getPromotedIntegerType(Ty);
842       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
843       return E;
844     }
845   }
846   return E;
847 }
848 
849 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
850 /// do not have a prototype. Arguments that have type float or __fp16
851 /// are promoted to double. All other argument types are converted by
852 /// UsualUnaryConversions().
853 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
854   QualType Ty = E->getType();
855   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
856 
857   ExprResult Res = UsualUnaryConversions(E);
858   if (Res.isInvalid())
859     return ExprError();
860   E = Res.get();
861 
862   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
863   // promote to double.
864   // Note that default argument promotion applies only to float (and
865   // half/fp16); it does not apply to _Float16.
866   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
867   if (BTy && (BTy->getKind() == BuiltinType::Half ||
868               BTy->getKind() == BuiltinType::Float)) {
869     if (getLangOpts().OpenCL &&
870         !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
871       if (BTy->getKind() == BuiltinType::Half) {
872         E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
873       }
874     } else {
875       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
876     }
877   }
878   if (BTy &&
879       getLangOpts().getExtendIntArgs() ==
880           LangOptions::ExtendArgsKind::ExtendTo64 &&
881       Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
882       Context.getTypeSizeInChars(BTy) <
883           Context.getTypeSizeInChars(Context.LongLongTy)) {
884     E = (Ty->isUnsignedIntegerType())
885             ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
886                   .get()
887             : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
888     assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
889            "Unexpected typesize for LongLongTy");
890   }
891 
892   // C++ performs lvalue-to-rvalue conversion as a default argument
893   // promotion, even on class types, but note:
894   //   C++11 [conv.lval]p2:
895   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
896   //     operand or a subexpression thereof the value contained in the
897   //     referenced object is not accessed. Otherwise, if the glvalue
898   //     has a class type, the conversion copy-initializes a temporary
899   //     of type T from the glvalue and the result of the conversion
900   //     is a prvalue for the temporary.
901   // FIXME: add some way to gate this entire thing for correctness in
902   // potentially potentially evaluated contexts.
903   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
904     ExprResult Temp = PerformCopyInitialization(
905                        InitializedEntity::InitializeTemporary(E->getType()),
906                                                 E->getExprLoc(), E);
907     if (Temp.isInvalid())
908       return ExprError();
909     E = Temp.get();
910   }
911 
912   return E;
913 }
914 
915 /// Determine the degree of POD-ness for an expression.
916 /// Incomplete types are considered POD, since this check can be performed
917 /// when we're in an unevaluated context.
918 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
919   if (Ty->isIncompleteType()) {
920     // C++11 [expr.call]p7:
921     //   After these conversions, if the argument does not have arithmetic,
922     //   enumeration, pointer, pointer to member, or class type, the program
923     //   is ill-formed.
924     //
925     // Since we've already performed array-to-pointer and function-to-pointer
926     // decay, the only such type in C++ is cv void. This also handles
927     // initializer lists as variadic arguments.
928     if (Ty->isVoidType())
929       return VAK_Invalid;
930 
931     if (Ty->isObjCObjectType())
932       return VAK_Invalid;
933     return VAK_Valid;
934   }
935 
936   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
937     return VAK_Invalid;
938 
939   if (Ty.isCXX98PODType(Context))
940     return VAK_Valid;
941 
942   // C++11 [expr.call]p7:
943   //   Passing a potentially-evaluated argument of class type (Clause 9)
944   //   having a non-trivial copy constructor, a non-trivial move constructor,
945   //   or a non-trivial destructor, with no corresponding parameter,
946   //   is conditionally-supported with implementation-defined semantics.
947   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
948     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
949       if (!Record->hasNonTrivialCopyConstructor() &&
950           !Record->hasNonTrivialMoveConstructor() &&
951           !Record->hasNonTrivialDestructor())
952         return VAK_ValidInCXX11;
953 
954   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
955     return VAK_Valid;
956 
957   if (Ty->isObjCObjectType())
958     return VAK_Invalid;
959 
960   if (getLangOpts().MSVCCompat)
961     return VAK_MSVCUndefined;
962 
963   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
964   // permitted to reject them. We should consider doing so.
965   return VAK_Undefined;
966 }
967 
968 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
969   // Don't allow one to pass an Objective-C interface to a vararg.
970   const QualType &Ty = E->getType();
971   VarArgKind VAK = isValidVarArgType(Ty);
972 
973   // Complain about passing non-POD types through varargs.
974   switch (VAK) {
975   case VAK_ValidInCXX11:
976     DiagRuntimeBehavior(
977         E->getBeginLoc(), nullptr,
978         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
979     LLVM_FALLTHROUGH;
980   case VAK_Valid:
981     if (Ty->isRecordType()) {
982       // This is unlikely to be what the user intended. If the class has a
983       // 'c_str' member function, the user probably meant to call that.
984       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
985                           PDiag(diag::warn_pass_class_arg_to_vararg)
986                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
987     }
988     break;
989 
990   case VAK_Undefined:
991   case VAK_MSVCUndefined:
992     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
993                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
994                             << getLangOpts().CPlusPlus11 << Ty << CT);
995     break;
996 
997   case VAK_Invalid:
998     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
999       Diag(E->getBeginLoc(),
1000            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1001           << Ty << CT;
1002     else if (Ty->isObjCObjectType())
1003       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1004                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1005                               << Ty << CT);
1006     else
1007       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1008           << isa<InitListExpr>(E) << Ty << CT;
1009     break;
1010   }
1011 }
1012 
1013 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1014 /// will create a trap if the resulting type is not a POD type.
1015 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1016                                                   FunctionDecl *FDecl) {
1017   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1018     // Strip the unbridged-cast placeholder expression off, if applicable.
1019     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1020         (CT == VariadicMethod ||
1021          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1022       E = stripARCUnbridgedCast(E);
1023 
1024     // Otherwise, do normal placeholder checking.
1025     } else {
1026       ExprResult ExprRes = CheckPlaceholderExpr(E);
1027       if (ExprRes.isInvalid())
1028         return ExprError();
1029       E = ExprRes.get();
1030     }
1031   }
1032 
1033   ExprResult ExprRes = DefaultArgumentPromotion(E);
1034   if (ExprRes.isInvalid())
1035     return ExprError();
1036 
1037   // Copy blocks to the heap.
1038   if (ExprRes.get()->getType()->isBlockPointerType())
1039     maybeExtendBlockObject(ExprRes);
1040 
1041   E = ExprRes.get();
1042 
1043   // Diagnostics regarding non-POD argument types are
1044   // emitted along with format string checking in Sema::CheckFunctionCall().
1045   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1046     // Turn this into a trap.
1047     CXXScopeSpec SS;
1048     SourceLocation TemplateKWLoc;
1049     UnqualifiedId Name;
1050     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1051                        E->getBeginLoc());
1052     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1053                                           /*HasTrailingLParen=*/true,
1054                                           /*IsAddressOfOperand=*/false);
1055     if (TrapFn.isInvalid())
1056       return ExprError();
1057 
1058     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1059                                     None, E->getEndLoc());
1060     if (Call.isInvalid())
1061       return ExprError();
1062 
1063     ExprResult Comma =
1064         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1065     if (Comma.isInvalid())
1066       return ExprError();
1067     return Comma.get();
1068   }
1069 
1070   if (!getLangOpts().CPlusPlus &&
1071       RequireCompleteType(E->getExprLoc(), E->getType(),
1072                           diag::err_call_incomplete_argument))
1073     return ExprError();
1074 
1075   return E;
1076 }
1077 
1078 /// Converts an integer to complex float type.  Helper function of
1079 /// UsualArithmeticConversions()
1080 ///
1081 /// \return false if the integer expression is an integer type and is
1082 /// successfully converted to the complex type.
1083 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1084                                                   ExprResult &ComplexExpr,
1085                                                   QualType IntTy,
1086                                                   QualType ComplexTy,
1087                                                   bool SkipCast) {
1088   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1089   if (SkipCast) return false;
1090   if (IntTy->isIntegerType()) {
1091     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1092     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1093     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1094                                   CK_FloatingRealToComplex);
1095   } else {
1096     assert(IntTy->isComplexIntegerType());
1097     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1098                                   CK_IntegralComplexToFloatingComplex);
1099   }
1100   return false;
1101 }
1102 
1103 /// Handle arithmetic conversion with complex types.  Helper function of
1104 /// UsualArithmeticConversions()
1105 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1106                                              ExprResult &RHS, QualType LHSType,
1107                                              QualType RHSType,
1108                                              bool IsCompAssign) {
1109   // if we have an integer operand, the result is the complex type.
1110   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1111                                              /*skipCast*/false))
1112     return LHSType;
1113   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1114                                              /*skipCast*/IsCompAssign))
1115     return RHSType;
1116 
1117   // This handles complex/complex, complex/float, or float/complex.
1118   // When both operands are complex, the shorter operand is converted to the
1119   // type of the longer, and that is the type of the result. This corresponds
1120   // to what is done when combining two real floating-point operands.
1121   // The fun begins when size promotion occur across type domains.
1122   // From H&S 6.3.4: When one operand is complex and the other is a real
1123   // floating-point type, the less precise type is converted, within it's
1124   // real or complex domain, to the precision of the other type. For example,
1125   // when combining a "long double" with a "double _Complex", the
1126   // "double _Complex" is promoted to "long double _Complex".
1127 
1128   // Compute the rank of the two types, regardless of whether they are complex.
1129   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1130 
1131   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1132   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1133   QualType LHSElementType =
1134       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1135   QualType RHSElementType =
1136       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1137 
1138   QualType ResultType = S.Context.getComplexType(LHSElementType);
1139   if (Order < 0) {
1140     // Promote the precision of the LHS if not an assignment.
1141     ResultType = S.Context.getComplexType(RHSElementType);
1142     if (!IsCompAssign) {
1143       if (LHSComplexType)
1144         LHS =
1145             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1146       else
1147         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1148     }
1149   } else if (Order > 0) {
1150     // Promote the precision of the RHS.
1151     if (RHSComplexType)
1152       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1153     else
1154       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1155   }
1156   return ResultType;
1157 }
1158 
1159 /// Handle arithmetic conversion from integer to float.  Helper function
1160 /// of UsualArithmeticConversions()
1161 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1162                                            ExprResult &IntExpr,
1163                                            QualType FloatTy, QualType IntTy,
1164                                            bool ConvertFloat, bool ConvertInt) {
1165   if (IntTy->isIntegerType()) {
1166     if (ConvertInt)
1167       // Convert intExpr to the lhs floating point type.
1168       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1169                                     CK_IntegralToFloating);
1170     return FloatTy;
1171   }
1172 
1173   // Convert both sides to the appropriate complex float.
1174   assert(IntTy->isComplexIntegerType());
1175   QualType result = S.Context.getComplexType(FloatTy);
1176 
1177   // _Complex int -> _Complex float
1178   if (ConvertInt)
1179     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1180                                   CK_IntegralComplexToFloatingComplex);
1181 
1182   // float -> _Complex float
1183   if (ConvertFloat)
1184     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1185                                     CK_FloatingRealToComplex);
1186 
1187   return result;
1188 }
1189 
1190 /// Handle arithmethic conversion with floating point types.  Helper
1191 /// function of UsualArithmeticConversions()
1192 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1193                                       ExprResult &RHS, QualType LHSType,
1194                                       QualType RHSType, bool IsCompAssign) {
1195   bool LHSFloat = LHSType->isRealFloatingType();
1196   bool RHSFloat = RHSType->isRealFloatingType();
1197 
1198   // N1169 4.1.4: If one of the operands has a floating type and the other
1199   //              operand has a fixed-point type, the fixed-point operand
1200   //              is converted to the floating type [...]
1201   if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1202     if (LHSFloat)
1203       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1204     else if (!IsCompAssign)
1205       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1206     return LHSFloat ? LHSType : RHSType;
1207   }
1208 
1209   // If we have two real floating types, convert the smaller operand
1210   // to the bigger result.
1211   if (LHSFloat && RHSFloat) {
1212     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1213     if (order > 0) {
1214       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1215       return LHSType;
1216     }
1217 
1218     assert(order < 0 && "illegal float comparison");
1219     if (!IsCompAssign)
1220       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1221     return RHSType;
1222   }
1223 
1224   if (LHSFloat) {
1225     // Half FP has to be promoted to float unless it is natively supported
1226     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1227       LHSType = S.Context.FloatTy;
1228 
1229     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1230                                       /*ConvertFloat=*/!IsCompAssign,
1231                                       /*ConvertInt=*/ true);
1232   }
1233   assert(RHSFloat);
1234   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1235                                     /*ConvertFloat=*/ true,
1236                                     /*ConvertInt=*/!IsCompAssign);
1237 }
1238 
1239 /// Diagnose attempts to convert between __float128, __ibm128 and
1240 /// long double if there is no support for such conversion.
1241 /// Helper function of UsualArithmeticConversions().
1242 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1243                                       QualType RHSType) {
1244   // No issue if either is not a floating point type.
1245   if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1246     return false;
1247 
1248   // No issue if both have the same 128-bit float semantics.
1249   auto *LHSComplex = LHSType->getAs<ComplexType>();
1250   auto *RHSComplex = RHSType->getAs<ComplexType>();
1251 
1252   QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1253   QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1254 
1255   const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1256   const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1257 
1258   if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1259        &RHSSem != &llvm::APFloat::IEEEquad()) &&
1260       (&LHSSem != &llvm::APFloat::IEEEquad() ||
1261        &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1262     return false;
1263 
1264   return true;
1265 }
1266 
1267 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1268 
1269 namespace {
1270 /// These helper callbacks are placed in an anonymous namespace to
1271 /// permit their use as function template parameters.
1272 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1273   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1274 }
1275 
1276 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1277   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1278                              CK_IntegralComplexCast);
1279 }
1280 }
1281 
1282 /// Handle integer arithmetic conversions.  Helper function of
1283 /// UsualArithmeticConversions()
1284 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1285 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1286                                         ExprResult &RHS, QualType LHSType,
1287                                         QualType RHSType, bool IsCompAssign) {
1288   // The rules for this case are in C99 6.3.1.8
1289   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1290   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1291   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1292   if (LHSSigned == RHSSigned) {
1293     // Same signedness; use the higher-ranked type
1294     if (order >= 0) {
1295       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1296       return LHSType;
1297     } else if (!IsCompAssign)
1298       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1299     return RHSType;
1300   } else if (order != (LHSSigned ? 1 : -1)) {
1301     // The unsigned type has greater than or equal rank to the
1302     // signed type, so use the unsigned type
1303     if (RHSSigned) {
1304       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1305       return LHSType;
1306     } else if (!IsCompAssign)
1307       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1308     return RHSType;
1309   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1310     // The two types are different widths; if we are here, that
1311     // means the signed type is larger than the unsigned type, so
1312     // use the signed type.
1313     if (LHSSigned) {
1314       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1315       return LHSType;
1316     } else if (!IsCompAssign)
1317       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1318     return RHSType;
1319   } else {
1320     // The signed type is higher-ranked than the unsigned type,
1321     // but isn't actually any bigger (like unsigned int and long
1322     // on most 32-bit systems).  Use the unsigned type corresponding
1323     // to the signed type.
1324     QualType result =
1325       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1326     RHS = (*doRHSCast)(S, RHS.get(), result);
1327     if (!IsCompAssign)
1328       LHS = (*doLHSCast)(S, LHS.get(), result);
1329     return result;
1330   }
1331 }
1332 
1333 /// Handle conversions with GCC complex int extension.  Helper function
1334 /// of UsualArithmeticConversions()
1335 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1336                                            ExprResult &RHS, QualType LHSType,
1337                                            QualType RHSType,
1338                                            bool IsCompAssign) {
1339   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1340   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1341 
1342   if (LHSComplexInt && RHSComplexInt) {
1343     QualType LHSEltType = LHSComplexInt->getElementType();
1344     QualType RHSEltType = RHSComplexInt->getElementType();
1345     QualType ScalarType =
1346       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1347         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1348 
1349     return S.Context.getComplexType(ScalarType);
1350   }
1351 
1352   if (LHSComplexInt) {
1353     QualType LHSEltType = LHSComplexInt->getElementType();
1354     QualType ScalarType =
1355       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1356         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1357     QualType ComplexType = S.Context.getComplexType(ScalarType);
1358     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1359                               CK_IntegralRealToComplex);
1360 
1361     return ComplexType;
1362   }
1363 
1364   assert(RHSComplexInt);
1365 
1366   QualType RHSEltType = RHSComplexInt->getElementType();
1367   QualType ScalarType =
1368     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1369       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1370   QualType ComplexType = S.Context.getComplexType(ScalarType);
1371 
1372   if (!IsCompAssign)
1373     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1374                               CK_IntegralRealToComplex);
1375   return ComplexType;
1376 }
1377 
1378 /// Return the rank of a given fixed point or integer type. The value itself
1379 /// doesn't matter, but the values must be increasing with proper increasing
1380 /// rank as described in N1169 4.1.1.
1381 static unsigned GetFixedPointRank(QualType Ty) {
1382   const auto *BTy = Ty->getAs<BuiltinType>();
1383   assert(BTy && "Expected a builtin type.");
1384 
1385   switch (BTy->getKind()) {
1386   case BuiltinType::ShortFract:
1387   case BuiltinType::UShortFract:
1388   case BuiltinType::SatShortFract:
1389   case BuiltinType::SatUShortFract:
1390     return 1;
1391   case BuiltinType::Fract:
1392   case BuiltinType::UFract:
1393   case BuiltinType::SatFract:
1394   case BuiltinType::SatUFract:
1395     return 2;
1396   case BuiltinType::LongFract:
1397   case BuiltinType::ULongFract:
1398   case BuiltinType::SatLongFract:
1399   case BuiltinType::SatULongFract:
1400     return 3;
1401   case BuiltinType::ShortAccum:
1402   case BuiltinType::UShortAccum:
1403   case BuiltinType::SatShortAccum:
1404   case BuiltinType::SatUShortAccum:
1405     return 4;
1406   case BuiltinType::Accum:
1407   case BuiltinType::UAccum:
1408   case BuiltinType::SatAccum:
1409   case BuiltinType::SatUAccum:
1410     return 5;
1411   case BuiltinType::LongAccum:
1412   case BuiltinType::ULongAccum:
1413   case BuiltinType::SatLongAccum:
1414   case BuiltinType::SatULongAccum:
1415     return 6;
1416   default:
1417     if (BTy->isInteger())
1418       return 0;
1419     llvm_unreachable("Unexpected fixed point or integer type");
1420   }
1421 }
1422 
1423 /// handleFixedPointConversion - Fixed point operations between fixed
1424 /// point types and integers or other fixed point types do not fall under
1425 /// usual arithmetic conversion since these conversions could result in loss
1426 /// of precsision (N1169 4.1.4). These operations should be calculated with
1427 /// the full precision of their result type (N1169 4.1.6.2.1).
1428 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1429                                            QualType RHSTy) {
1430   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1431          "Expected at least one of the operands to be a fixed point type");
1432   assert((LHSTy->isFixedPointOrIntegerType() ||
1433           RHSTy->isFixedPointOrIntegerType()) &&
1434          "Special fixed point arithmetic operation conversions are only "
1435          "applied to ints or other fixed point types");
1436 
1437   // If one operand has signed fixed-point type and the other operand has
1438   // unsigned fixed-point type, then the unsigned fixed-point operand is
1439   // converted to its corresponding signed fixed-point type and the resulting
1440   // type is the type of the converted operand.
1441   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1442     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1443   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1444     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1445 
1446   // The result type is the type with the highest rank, whereby a fixed-point
1447   // conversion rank is always greater than an integer conversion rank; if the
1448   // type of either of the operands is a saturating fixedpoint type, the result
1449   // type shall be the saturating fixed-point type corresponding to the type
1450   // with the highest rank; the resulting value is converted (taking into
1451   // account rounding and overflow) to the precision of the resulting type.
1452   // Same ranks between signed and unsigned types are resolved earlier, so both
1453   // types are either signed or both unsigned at this point.
1454   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1455   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1456 
1457   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1458 
1459   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1460     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1461 
1462   return ResultTy;
1463 }
1464 
1465 /// Check that the usual arithmetic conversions can be performed on this pair of
1466 /// expressions that might be of enumeration type.
1467 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1468                                            SourceLocation Loc,
1469                                            Sema::ArithConvKind ACK) {
1470   // C++2a [expr.arith.conv]p1:
1471   //   If one operand is of enumeration type and the other operand is of a
1472   //   different enumeration type or a floating-point type, this behavior is
1473   //   deprecated ([depr.arith.conv.enum]).
1474   //
1475   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1476   // Eventually we will presumably reject these cases (in C++23 onwards?).
1477   QualType L = LHS->getType(), R = RHS->getType();
1478   bool LEnum = L->isUnscopedEnumerationType(),
1479        REnum = R->isUnscopedEnumerationType();
1480   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1481   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1482       (REnum && L->isFloatingType())) {
1483     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1484                     ? diag::warn_arith_conv_enum_float_cxx20
1485                     : diag::warn_arith_conv_enum_float)
1486         << LHS->getSourceRange() << RHS->getSourceRange()
1487         << (int)ACK << LEnum << L << R;
1488   } else if (!IsCompAssign && LEnum && REnum &&
1489              !S.Context.hasSameUnqualifiedType(L, R)) {
1490     unsigned DiagID;
1491     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1492         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1493       // If either enumeration type is unnamed, it's less likely that the
1494       // user cares about this, but this situation is still deprecated in
1495       // C++2a. Use a different warning group.
1496       DiagID = S.getLangOpts().CPlusPlus20
1497                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1498                     : diag::warn_arith_conv_mixed_anon_enum_types;
1499     } else if (ACK == Sema::ACK_Conditional) {
1500       // Conditional expressions are separated out because they have
1501       // historically had a different warning flag.
1502       DiagID = S.getLangOpts().CPlusPlus20
1503                    ? diag::warn_conditional_mixed_enum_types_cxx20
1504                    : diag::warn_conditional_mixed_enum_types;
1505     } else if (ACK == Sema::ACK_Comparison) {
1506       // Comparison expressions are separated out because they have
1507       // historically had a different warning flag.
1508       DiagID = S.getLangOpts().CPlusPlus20
1509                    ? diag::warn_comparison_mixed_enum_types_cxx20
1510                    : diag::warn_comparison_mixed_enum_types;
1511     } else {
1512       DiagID = S.getLangOpts().CPlusPlus20
1513                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1514                    : diag::warn_arith_conv_mixed_enum_types;
1515     }
1516     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1517                         << (int)ACK << L << R;
1518   }
1519 }
1520 
1521 /// UsualArithmeticConversions - Performs various conversions that are common to
1522 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1523 /// routine returns the first non-arithmetic type found. The client is
1524 /// responsible for emitting appropriate error diagnostics.
1525 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1526                                           SourceLocation Loc,
1527                                           ArithConvKind ACK) {
1528   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1529 
1530   if (ACK != ACK_CompAssign) {
1531     LHS = UsualUnaryConversions(LHS.get());
1532     if (LHS.isInvalid())
1533       return QualType();
1534   }
1535 
1536   RHS = UsualUnaryConversions(RHS.get());
1537   if (RHS.isInvalid())
1538     return QualType();
1539 
1540   // For conversion purposes, we ignore any qualifiers.
1541   // For example, "const float" and "float" are equivalent.
1542   QualType LHSType =
1543     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1544   QualType RHSType =
1545     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1546 
1547   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1548   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1549     LHSType = AtomicLHS->getValueType();
1550 
1551   // If both types are identical, no conversion is needed.
1552   if (LHSType == RHSType)
1553     return LHSType;
1554 
1555   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1556   // The caller can deal with this (e.g. pointer + int).
1557   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1558     return QualType();
1559 
1560   // Apply unary and bitfield promotions to the LHS's type.
1561   QualType LHSUnpromotedType = LHSType;
1562   if (LHSType->isPromotableIntegerType())
1563     LHSType = Context.getPromotedIntegerType(LHSType);
1564   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1565   if (!LHSBitfieldPromoteTy.isNull())
1566     LHSType = LHSBitfieldPromoteTy;
1567   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1568     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1569 
1570   // If both types are identical, no conversion is needed.
1571   if (LHSType == RHSType)
1572     return LHSType;
1573 
1574   // At this point, we have two different arithmetic types.
1575 
1576   // Diagnose attempts to convert between __ibm128, __float128 and long double
1577   // where such conversions currently can't be handled.
1578   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1579     return QualType();
1580 
1581   // Handle complex types first (C99 6.3.1.8p1).
1582   if (LHSType->isComplexType() || RHSType->isComplexType())
1583     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1584                                         ACK == ACK_CompAssign);
1585 
1586   // Now handle "real" floating types (i.e. float, double, long double).
1587   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1588     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1589                                  ACK == ACK_CompAssign);
1590 
1591   // Handle GCC complex int extension.
1592   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1593     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1594                                       ACK == ACK_CompAssign);
1595 
1596   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1597     return handleFixedPointConversion(*this, LHSType, RHSType);
1598 
1599   // Finally, we have two differing integer types.
1600   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1601            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1602 }
1603 
1604 //===----------------------------------------------------------------------===//
1605 //  Semantic Analysis for various Expression Types
1606 //===----------------------------------------------------------------------===//
1607 
1608 
1609 ExprResult
1610 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1611                                 SourceLocation DefaultLoc,
1612                                 SourceLocation RParenLoc,
1613                                 Expr *ControllingExpr,
1614                                 ArrayRef<ParsedType> ArgTypes,
1615                                 ArrayRef<Expr *> ArgExprs) {
1616   unsigned NumAssocs = ArgTypes.size();
1617   assert(NumAssocs == ArgExprs.size());
1618 
1619   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1620   for (unsigned i = 0; i < NumAssocs; ++i) {
1621     if (ArgTypes[i])
1622       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1623     else
1624       Types[i] = nullptr;
1625   }
1626 
1627   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1628                                              ControllingExpr,
1629                                              llvm::makeArrayRef(Types, NumAssocs),
1630                                              ArgExprs);
1631   delete [] Types;
1632   return ER;
1633 }
1634 
1635 ExprResult
1636 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1637                                  SourceLocation DefaultLoc,
1638                                  SourceLocation RParenLoc,
1639                                  Expr *ControllingExpr,
1640                                  ArrayRef<TypeSourceInfo *> Types,
1641                                  ArrayRef<Expr *> Exprs) {
1642   unsigned NumAssocs = Types.size();
1643   assert(NumAssocs == Exprs.size());
1644 
1645   // Decay and strip qualifiers for the controlling expression type, and handle
1646   // placeholder type replacement. See committee discussion from WG14 DR423.
1647   {
1648     EnterExpressionEvaluationContext Unevaluated(
1649         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1650     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1651     if (R.isInvalid())
1652       return ExprError();
1653     ControllingExpr = R.get();
1654   }
1655 
1656   bool TypeErrorFound = false,
1657        IsResultDependent = ControllingExpr->isTypeDependent(),
1658        ContainsUnexpandedParameterPack
1659          = ControllingExpr->containsUnexpandedParameterPack();
1660 
1661   // The controlling expression is an unevaluated operand, so side effects are
1662   // likely unintended.
1663   if (!inTemplateInstantiation() && !IsResultDependent &&
1664       ControllingExpr->HasSideEffects(Context, false))
1665     Diag(ControllingExpr->getExprLoc(),
1666          diag::warn_side_effects_unevaluated_context);
1667 
1668   for (unsigned i = 0; i < NumAssocs; ++i) {
1669     if (Exprs[i]->containsUnexpandedParameterPack())
1670       ContainsUnexpandedParameterPack = true;
1671 
1672     if (Types[i]) {
1673       if (Types[i]->getType()->containsUnexpandedParameterPack())
1674         ContainsUnexpandedParameterPack = true;
1675 
1676       if (Types[i]->getType()->isDependentType()) {
1677         IsResultDependent = true;
1678       } else {
1679         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1680         // complete object type other than a variably modified type."
1681         unsigned D = 0;
1682         if (Types[i]->getType()->isIncompleteType())
1683           D = diag::err_assoc_type_incomplete;
1684         else if (!Types[i]->getType()->isObjectType())
1685           D = diag::err_assoc_type_nonobject;
1686         else if (Types[i]->getType()->isVariablyModifiedType())
1687           D = diag::err_assoc_type_variably_modified;
1688         else {
1689           // Because the controlling expression undergoes lvalue conversion,
1690           // array conversion, and function conversion, an association which is
1691           // of array type, function type, or is qualified can never be
1692           // reached. We will warn about this so users are less surprised by
1693           // the unreachable association. However, we don't have to handle
1694           // function types; that's not an object type, so it's handled above.
1695           //
1696           // The logic is somewhat different for C++ because C++ has different
1697           // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1698           // If T is a non-class type, the type of the prvalue is the cv-
1699           // unqualified version of T. Otherwise, the type of the prvalue is T.
1700           // The result of these rules is that all qualified types in an
1701           // association in C are unreachable, and in C++, only qualified non-
1702           // class types are unreachable.
1703           unsigned Reason = 0;
1704           QualType QT = Types[i]->getType();
1705           if (QT->isArrayType())
1706             Reason = 1;
1707           else if (QT.hasQualifiers() &&
1708                    (!LangOpts.CPlusPlus || !QT->isRecordType()))
1709             Reason = 2;
1710 
1711           if (Reason)
1712             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1713                  diag::warn_unreachable_association)
1714                 << QT << (Reason - 1);
1715         }
1716 
1717         if (D != 0) {
1718           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1719             << Types[i]->getTypeLoc().getSourceRange()
1720             << Types[i]->getType();
1721           TypeErrorFound = true;
1722         }
1723 
1724         // C11 6.5.1.1p2 "No two generic associations in the same generic
1725         // selection shall specify compatible types."
1726         for (unsigned j = i+1; j < NumAssocs; ++j)
1727           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1728               Context.typesAreCompatible(Types[i]->getType(),
1729                                          Types[j]->getType())) {
1730             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1731                  diag::err_assoc_compatible_types)
1732               << Types[j]->getTypeLoc().getSourceRange()
1733               << Types[j]->getType()
1734               << Types[i]->getType();
1735             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1736                  diag::note_compat_assoc)
1737               << Types[i]->getTypeLoc().getSourceRange()
1738               << Types[i]->getType();
1739             TypeErrorFound = true;
1740           }
1741       }
1742     }
1743   }
1744   if (TypeErrorFound)
1745     return ExprError();
1746 
1747   // If we determined that the generic selection is result-dependent, don't
1748   // try to compute the result expression.
1749   if (IsResultDependent)
1750     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1751                                         Exprs, DefaultLoc, RParenLoc,
1752                                         ContainsUnexpandedParameterPack);
1753 
1754   SmallVector<unsigned, 1> CompatIndices;
1755   unsigned DefaultIndex = -1U;
1756   // Look at the canonical type of the controlling expression in case it was a
1757   // deduced type like __auto_type. However, when issuing diagnostics, use the
1758   // type the user wrote in source rather than the canonical one.
1759   for (unsigned i = 0; i < NumAssocs; ++i) {
1760     if (!Types[i])
1761       DefaultIndex = i;
1762     else if (Context.typesAreCompatible(
1763                  ControllingExpr->getType().getCanonicalType(),
1764                                         Types[i]->getType()))
1765       CompatIndices.push_back(i);
1766   }
1767 
1768   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1769   // type compatible with at most one of the types named in its generic
1770   // association list."
1771   if (CompatIndices.size() > 1) {
1772     // We strip parens here because the controlling expression is typically
1773     // parenthesized in macro definitions.
1774     ControllingExpr = ControllingExpr->IgnoreParens();
1775     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1776         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1777         << (unsigned)CompatIndices.size();
1778     for (unsigned I : CompatIndices) {
1779       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1780            diag::note_compat_assoc)
1781         << Types[I]->getTypeLoc().getSourceRange()
1782         << Types[I]->getType();
1783     }
1784     return ExprError();
1785   }
1786 
1787   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1788   // its controlling expression shall have type compatible with exactly one of
1789   // the types named in its generic association list."
1790   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1791     // We strip parens here because the controlling expression is typically
1792     // parenthesized in macro definitions.
1793     ControllingExpr = ControllingExpr->IgnoreParens();
1794     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1795         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1796     return ExprError();
1797   }
1798 
1799   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1800   // type name that is compatible with the type of the controlling expression,
1801   // then the result expression of the generic selection is the expression
1802   // in that generic association. Otherwise, the result expression of the
1803   // generic selection is the expression in the default generic association."
1804   unsigned ResultIndex =
1805     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1806 
1807   return GenericSelectionExpr::Create(
1808       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1809       ContainsUnexpandedParameterPack, ResultIndex);
1810 }
1811 
1812 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1813 /// location of the token and the offset of the ud-suffix within it.
1814 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1815                                      unsigned Offset) {
1816   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1817                                         S.getLangOpts());
1818 }
1819 
1820 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1821 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1822 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1823                                                  IdentifierInfo *UDSuffix,
1824                                                  SourceLocation UDSuffixLoc,
1825                                                  ArrayRef<Expr*> Args,
1826                                                  SourceLocation LitEndLoc) {
1827   assert(Args.size() <= 2 && "too many arguments for literal operator");
1828 
1829   QualType ArgTy[2];
1830   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1831     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1832     if (ArgTy[ArgIdx]->isArrayType())
1833       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1834   }
1835 
1836   DeclarationName OpName =
1837     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1838   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1839   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1840 
1841   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1842   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1843                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1844                               /*AllowStringTemplatePack*/ false,
1845                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1846     return ExprError();
1847 
1848   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1849 }
1850 
1851 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1852 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1853 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1854 /// multiple tokens.  However, the common case is that StringToks points to one
1855 /// string.
1856 ///
1857 ExprResult
1858 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1859   assert(!StringToks.empty() && "Must have at least one string!");
1860 
1861   StringLiteralParser Literal(StringToks, PP);
1862   if (Literal.hadError)
1863     return ExprError();
1864 
1865   SmallVector<SourceLocation, 4> StringTokLocs;
1866   for (const Token &Tok : StringToks)
1867     StringTokLocs.push_back(Tok.getLocation());
1868 
1869   QualType CharTy = Context.CharTy;
1870   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1871   if (Literal.isWide()) {
1872     CharTy = Context.getWideCharType();
1873     Kind = StringLiteral::Wide;
1874   } else if (Literal.isUTF8()) {
1875     if (getLangOpts().Char8)
1876       CharTy = Context.Char8Ty;
1877     Kind = StringLiteral::UTF8;
1878   } else if (Literal.isUTF16()) {
1879     CharTy = Context.Char16Ty;
1880     Kind = StringLiteral::UTF16;
1881   } else if (Literal.isUTF32()) {
1882     CharTy = Context.Char32Ty;
1883     Kind = StringLiteral::UTF32;
1884   } else if (Literal.isPascal()) {
1885     CharTy = Context.UnsignedCharTy;
1886   }
1887 
1888   // Warn on initializing an array of char from a u8 string literal; this
1889   // becomes ill-formed in C++2a.
1890   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1891       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1892     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1893 
1894     // Create removals for all 'u8' prefixes in the string literal(s). This
1895     // ensures C++2a compatibility (but may change the program behavior when
1896     // built by non-Clang compilers for which the execution character set is
1897     // not always UTF-8).
1898     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1899     SourceLocation RemovalDiagLoc;
1900     for (const Token &Tok : StringToks) {
1901       if (Tok.getKind() == tok::utf8_string_literal) {
1902         if (RemovalDiagLoc.isInvalid())
1903           RemovalDiagLoc = Tok.getLocation();
1904         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1905             Tok.getLocation(),
1906             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1907                                            getSourceManager(), getLangOpts())));
1908       }
1909     }
1910     Diag(RemovalDiagLoc, RemovalDiag);
1911   }
1912 
1913   QualType StrTy =
1914       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1915 
1916   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1917   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1918                                              Kind, Literal.Pascal, StrTy,
1919                                              &StringTokLocs[0],
1920                                              StringTokLocs.size());
1921   if (Literal.getUDSuffix().empty())
1922     return Lit;
1923 
1924   // We're building a user-defined literal.
1925   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1926   SourceLocation UDSuffixLoc =
1927     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1928                    Literal.getUDSuffixOffset());
1929 
1930   // Make sure we're allowed user-defined literals here.
1931   if (!UDLScope)
1932     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1933 
1934   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1935   //   operator "" X (str, len)
1936   QualType SizeType = Context.getSizeType();
1937 
1938   DeclarationName OpName =
1939     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1940   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1941   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1942 
1943   QualType ArgTy[] = {
1944     Context.getArrayDecayedType(StrTy), SizeType
1945   };
1946 
1947   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1948   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1949                                 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1950                                 /*AllowStringTemplatePack*/ true,
1951                                 /*DiagnoseMissing*/ true, Lit)) {
1952 
1953   case LOLR_Cooked: {
1954     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1955     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1956                                                     StringTokLocs[0]);
1957     Expr *Args[] = { Lit, LenArg };
1958 
1959     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1960   }
1961 
1962   case LOLR_Template: {
1963     TemplateArgumentListInfo ExplicitArgs;
1964     TemplateArgument Arg(Lit);
1965     TemplateArgumentLocInfo ArgInfo(Lit);
1966     ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1967     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1968                                     &ExplicitArgs);
1969   }
1970 
1971   case LOLR_StringTemplatePack: {
1972     TemplateArgumentListInfo ExplicitArgs;
1973 
1974     unsigned CharBits = Context.getIntWidth(CharTy);
1975     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1976     llvm::APSInt Value(CharBits, CharIsUnsigned);
1977 
1978     TemplateArgument TypeArg(CharTy);
1979     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1980     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1981 
1982     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1983       Value = Lit->getCodeUnit(I);
1984       TemplateArgument Arg(Context, Value, CharTy);
1985       TemplateArgumentLocInfo ArgInfo;
1986       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1987     }
1988     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1989                                     &ExplicitArgs);
1990   }
1991   case LOLR_Raw:
1992   case LOLR_ErrorNoDiagnostic:
1993     llvm_unreachable("unexpected literal operator lookup result");
1994   case LOLR_Error:
1995     return ExprError();
1996   }
1997   llvm_unreachable("unexpected literal operator lookup result");
1998 }
1999 
2000 DeclRefExpr *
2001 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2002                        SourceLocation Loc,
2003                        const CXXScopeSpec *SS) {
2004   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2005   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2006 }
2007 
2008 DeclRefExpr *
2009 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2010                        const DeclarationNameInfo &NameInfo,
2011                        const CXXScopeSpec *SS, NamedDecl *FoundD,
2012                        SourceLocation TemplateKWLoc,
2013                        const TemplateArgumentListInfo *TemplateArgs) {
2014   NestedNameSpecifierLoc NNS =
2015       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2016   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2017                           TemplateArgs);
2018 }
2019 
2020 // CUDA/HIP: Check whether a captured reference variable is referencing a
2021 // host variable in a device or host device lambda.
2022 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2023                                                             VarDecl *VD) {
2024   if (!S.getLangOpts().CUDA || !VD->hasInit())
2025     return false;
2026   assert(VD->getType()->isReferenceType());
2027 
2028   // Check whether the reference variable is referencing a host variable.
2029   auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2030   if (!DRE)
2031     return false;
2032   auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2033   if (!Referee || !Referee->hasGlobalStorage() ||
2034       Referee->hasAttr<CUDADeviceAttr>())
2035     return false;
2036 
2037   // Check whether the current function is a device or host device lambda.
2038   // Check whether the reference variable is a capture by getDeclContext()
2039   // since refersToEnclosingVariableOrCapture() is not ready at this point.
2040   auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2041   if (MD && MD->getParent()->isLambda() &&
2042       MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2043       VD->getDeclContext() != MD)
2044     return true;
2045 
2046   return false;
2047 }
2048 
2049 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2050   // A declaration named in an unevaluated operand never constitutes an odr-use.
2051   if (isUnevaluatedContext())
2052     return NOUR_Unevaluated;
2053 
2054   // C++2a [basic.def.odr]p4:
2055   //   A variable x whose name appears as a potentially-evaluated expression e
2056   //   is odr-used by e unless [...] x is a reference that is usable in
2057   //   constant expressions.
2058   // CUDA/HIP:
2059   //   If a reference variable referencing a host variable is captured in a
2060   //   device or host device lambda, the value of the referee must be copied
2061   //   to the capture and the reference variable must be treated as odr-use
2062   //   since the value of the referee is not known at compile time and must
2063   //   be loaded from the captured.
2064   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2065     if (VD->getType()->isReferenceType() &&
2066         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2067         !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2068         VD->isUsableInConstantExpressions(Context))
2069       return NOUR_Constant;
2070   }
2071 
2072   // All remaining non-variable cases constitute an odr-use. For variables, we
2073   // need to wait and see how the expression is used.
2074   return NOUR_None;
2075 }
2076 
2077 /// BuildDeclRefExpr - Build an expression that references a
2078 /// declaration that does not require a closure capture.
2079 DeclRefExpr *
2080 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2081                        const DeclarationNameInfo &NameInfo,
2082                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2083                        SourceLocation TemplateKWLoc,
2084                        const TemplateArgumentListInfo *TemplateArgs) {
2085   bool RefersToCapturedVariable =
2086       isa<VarDecl>(D) &&
2087       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2088 
2089   DeclRefExpr *E = DeclRefExpr::Create(
2090       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2091       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2092   MarkDeclRefReferenced(E);
2093 
2094   // C++ [except.spec]p17:
2095   //   An exception-specification is considered to be needed when:
2096   //   - in an expression, the function is the unique lookup result or
2097   //     the selected member of a set of overloaded functions.
2098   //
2099   // We delay doing this until after we've built the function reference and
2100   // marked it as used so that:
2101   //  a) if the function is defaulted, we get errors from defining it before /
2102   //     instead of errors from computing its exception specification, and
2103   //  b) if the function is a defaulted comparison, we can use the body we
2104   //     build when defining it as input to the exception specification
2105   //     computation rather than computing a new body.
2106   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2107     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2108       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2109         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2110     }
2111   }
2112 
2113   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2114       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2115       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2116     getCurFunction()->recordUseOfWeak(E);
2117 
2118   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2119   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2120     FD = IFD->getAnonField();
2121   if (FD) {
2122     UnusedPrivateFields.remove(FD);
2123     // Just in case we're building an illegal pointer-to-member.
2124     if (FD->isBitField())
2125       E->setObjectKind(OK_BitField);
2126   }
2127 
2128   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2129   // designates a bit-field.
2130   if (auto *BD = dyn_cast<BindingDecl>(D))
2131     if (auto *BE = BD->getBinding())
2132       E->setObjectKind(BE->getObjectKind());
2133 
2134   return E;
2135 }
2136 
2137 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2138 /// possibly a list of template arguments.
2139 ///
2140 /// If this produces template arguments, it is permitted to call
2141 /// DecomposeTemplateName.
2142 ///
2143 /// This actually loses a lot of source location information for
2144 /// non-standard name kinds; we should consider preserving that in
2145 /// some way.
2146 void
2147 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2148                              TemplateArgumentListInfo &Buffer,
2149                              DeclarationNameInfo &NameInfo,
2150                              const TemplateArgumentListInfo *&TemplateArgs) {
2151   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2152     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2153     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2154 
2155     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2156                                        Id.TemplateId->NumArgs);
2157     translateTemplateArguments(TemplateArgsPtr, Buffer);
2158 
2159     TemplateName TName = Id.TemplateId->Template.get();
2160     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2161     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2162     TemplateArgs = &Buffer;
2163   } else {
2164     NameInfo = GetNameFromUnqualifiedId(Id);
2165     TemplateArgs = nullptr;
2166   }
2167 }
2168 
2169 static void emitEmptyLookupTypoDiagnostic(
2170     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2171     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2172     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2173   DeclContext *Ctx =
2174       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2175   if (!TC) {
2176     // Emit a special diagnostic for failed member lookups.
2177     // FIXME: computing the declaration context might fail here (?)
2178     if (Ctx)
2179       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2180                                                  << SS.getRange();
2181     else
2182       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2183     return;
2184   }
2185 
2186   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2187   bool DroppedSpecifier =
2188       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2189   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2190                         ? diag::note_implicit_param_decl
2191                         : diag::note_previous_decl;
2192   if (!Ctx)
2193     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2194                          SemaRef.PDiag(NoteID));
2195   else
2196     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2197                                  << Typo << Ctx << DroppedSpecifier
2198                                  << SS.getRange(),
2199                          SemaRef.PDiag(NoteID));
2200 }
2201 
2202 /// Diagnose a lookup that found results in an enclosing class during error
2203 /// recovery. This usually indicates that the results were found in a dependent
2204 /// base class that could not be searched as part of a template definition.
2205 /// Always issues a diagnostic (though this may be only a warning in MS
2206 /// compatibility mode).
2207 ///
2208 /// Return \c true if the error is unrecoverable, or \c false if the caller
2209 /// should attempt to recover using these lookup results.
2210 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2211   // During a default argument instantiation the CurContext points
2212   // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2213   // function parameter list, hence add an explicit check.
2214   bool isDefaultArgument =
2215       !CodeSynthesisContexts.empty() &&
2216       CodeSynthesisContexts.back().Kind ==
2217           CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2218   CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2219   bool isInstance = CurMethod && CurMethod->isInstance() &&
2220                     R.getNamingClass() == CurMethod->getParent() &&
2221                     !isDefaultArgument;
2222 
2223   // There are two ways we can find a class-scope declaration during template
2224   // instantiation that we did not find in the template definition: if it is a
2225   // member of a dependent base class, or if it is declared after the point of
2226   // use in the same class. Distinguish these by comparing the class in which
2227   // the member was found to the naming class of the lookup.
2228   unsigned DiagID = diag::err_found_in_dependent_base;
2229   unsigned NoteID = diag::note_member_declared_at;
2230   if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2231     DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2232                                       : diag::err_found_later_in_class;
2233   } else if (getLangOpts().MSVCCompat) {
2234     DiagID = diag::ext_found_in_dependent_base;
2235     NoteID = diag::note_dependent_member_use;
2236   }
2237 
2238   if (isInstance) {
2239     // Give a code modification hint to insert 'this->'.
2240     Diag(R.getNameLoc(), DiagID)
2241         << R.getLookupName()
2242         << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2243     CheckCXXThisCapture(R.getNameLoc());
2244   } else {
2245     // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2246     // they're not shadowed).
2247     Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2248   }
2249 
2250   for (NamedDecl *D : R)
2251     Diag(D->getLocation(), NoteID);
2252 
2253   // Return true if we are inside a default argument instantiation
2254   // and the found name refers to an instance member function, otherwise
2255   // the caller will try to create an implicit member call and this is wrong
2256   // for default arguments.
2257   //
2258   // FIXME: Is this special case necessary? We could allow the caller to
2259   // diagnose this.
2260   if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2261     Diag(R.getNameLoc(), diag::err_member_call_without_object);
2262     return true;
2263   }
2264 
2265   // Tell the callee to try to recover.
2266   return false;
2267 }
2268 
2269 /// Diagnose an empty lookup.
2270 ///
2271 /// \return false if new lookup candidates were found
2272 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2273                                CorrectionCandidateCallback &CCC,
2274                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2275                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2276   DeclarationName Name = R.getLookupName();
2277 
2278   unsigned diagnostic = diag::err_undeclared_var_use;
2279   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2280   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2281       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2282       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2283     diagnostic = diag::err_undeclared_use;
2284     diagnostic_suggest = diag::err_undeclared_use_suggest;
2285   }
2286 
2287   // If the original lookup was an unqualified lookup, fake an
2288   // unqualified lookup.  This is useful when (for example) the
2289   // original lookup would not have found something because it was a
2290   // dependent name.
2291   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2292   while (DC) {
2293     if (isa<CXXRecordDecl>(DC)) {
2294       LookupQualifiedName(R, DC);
2295 
2296       if (!R.empty()) {
2297         // Don't give errors about ambiguities in this lookup.
2298         R.suppressDiagnostics();
2299 
2300         // If there's a best viable function among the results, only mention
2301         // that one in the notes.
2302         OverloadCandidateSet Candidates(R.getNameLoc(),
2303                                         OverloadCandidateSet::CSK_Normal);
2304         AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2305         OverloadCandidateSet::iterator Best;
2306         if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2307             OR_Success) {
2308           R.clear();
2309           R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2310           R.resolveKind();
2311         }
2312 
2313         return DiagnoseDependentMemberLookup(R);
2314       }
2315 
2316       R.clear();
2317     }
2318 
2319     DC = DC->getLookupParent();
2320   }
2321 
2322   // We didn't find anything, so try to correct for a typo.
2323   TypoCorrection Corrected;
2324   if (S && Out) {
2325     SourceLocation TypoLoc = R.getNameLoc();
2326     assert(!ExplicitTemplateArgs &&
2327            "Diagnosing an empty lookup with explicit template args!");
2328     *Out = CorrectTypoDelayed(
2329         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2330         [=](const TypoCorrection &TC) {
2331           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2332                                         diagnostic, diagnostic_suggest);
2333         },
2334         nullptr, CTK_ErrorRecovery);
2335     if (*Out)
2336       return true;
2337   } else if (S &&
2338              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2339                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2340     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2341     bool DroppedSpecifier =
2342         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2343     R.setLookupName(Corrected.getCorrection());
2344 
2345     bool AcceptableWithRecovery = false;
2346     bool AcceptableWithoutRecovery = false;
2347     NamedDecl *ND = Corrected.getFoundDecl();
2348     if (ND) {
2349       if (Corrected.isOverloaded()) {
2350         OverloadCandidateSet OCS(R.getNameLoc(),
2351                                  OverloadCandidateSet::CSK_Normal);
2352         OverloadCandidateSet::iterator Best;
2353         for (NamedDecl *CD : Corrected) {
2354           if (FunctionTemplateDecl *FTD =
2355                    dyn_cast<FunctionTemplateDecl>(CD))
2356             AddTemplateOverloadCandidate(
2357                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2358                 Args, OCS);
2359           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2360             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2361               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2362                                    Args, OCS);
2363         }
2364         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2365         case OR_Success:
2366           ND = Best->FoundDecl;
2367           Corrected.setCorrectionDecl(ND);
2368           break;
2369         default:
2370           // FIXME: Arbitrarily pick the first declaration for the note.
2371           Corrected.setCorrectionDecl(ND);
2372           break;
2373         }
2374       }
2375       R.addDecl(ND);
2376       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2377         CXXRecordDecl *Record = nullptr;
2378         if (Corrected.getCorrectionSpecifier()) {
2379           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2380           Record = Ty->getAsCXXRecordDecl();
2381         }
2382         if (!Record)
2383           Record = cast<CXXRecordDecl>(
2384               ND->getDeclContext()->getRedeclContext());
2385         R.setNamingClass(Record);
2386       }
2387 
2388       auto *UnderlyingND = ND->getUnderlyingDecl();
2389       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2390                                isa<FunctionTemplateDecl>(UnderlyingND);
2391       // FIXME: If we ended up with a typo for a type name or
2392       // Objective-C class name, we're in trouble because the parser
2393       // is in the wrong place to recover. Suggest the typo
2394       // correction, but don't make it a fix-it since we're not going
2395       // to recover well anyway.
2396       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2397                                   getAsTypeTemplateDecl(UnderlyingND) ||
2398                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2399     } else {
2400       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2401       // because we aren't able to recover.
2402       AcceptableWithoutRecovery = true;
2403     }
2404 
2405     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2406       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2407                             ? diag::note_implicit_param_decl
2408                             : diag::note_previous_decl;
2409       if (SS.isEmpty())
2410         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2411                      PDiag(NoteID), AcceptableWithRecovery);
2412       else
2413         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2414                                   << Name << computeDeclContext(SS, false)
2415                                   << DroppedSpecifier << SS.getRange(),
2416                      PDiag(NoteID), AcceptableWithRecovery);
2417 
2418       // Tell the callee whether to try to recover.
2419       return !AcceptableWithRecovery;
2420     }
2421   }
2422   R.clear();
2423 
2424   // Emit a special diagnostic for failed member lookups.
2425   // FIXME: computing the declaration context might fail here (?)
2426   if (!SS.isEmpty()) {
2427     Diag(R.getNameLoc(), diag::err_no_member)
2428       << Name << computeDeclContext(SS, false)
2429       << SS.getRange();
2430     return true;
2431   }
2432 
2433   // Give up, we can't recover.
2434   Diag(R.getNameLoc(), diagnostic) << Name;
2435   return true;
2436 }
2437 
2438 /// In Microsoft mode, if we are inside a template class whose parent class has
2439 /// dependent base classes, and we can't resolve an unqualified identifier, then
2440 /// assume the identifier is a member of a dependent base class.  We can only
2441 /// recover successfully in static methods, instance methods, and other contexts
2442 /// where 'this' is available.  This doesn't precisely match MSVC's
2443 /// instantiation model, but it's close enough.
2444 static Expr *
2445 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2446                                DeclarationNameInfo &NameInfo,
2447                                SourceLocation TemplateKWLoc,
2448                                const TemplateArgumentListInfo *TemplateArgs) {
2449   // Only try to recover from lookup into dependent bases in static methods or
2450   // contexts where 'this' is available.
2451   QualType ThisType = S.getCurrentThisType();
2452   const CXXRecordDecl *RD = nullptr;
2453   if (!ThisType.isNull())
2454     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2455   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2456     RD = MD->getParent();
2457   if (!RD || !RD->hasAnyDependentBases())
2458     return nullptr;
2459 
2460   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2461   // is available, suggest inserting 'this->' as a fixit.
2462   SourceLocation Loc = NameInfo.getLoc();
2463   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2464   DB << NameInfo.getName() << RD;
2465 
2466   if (!ThisType.isNull()) {
2467     DB << FixItHint::CreateInsertion(Loc, "this->");
2468     return CXXDependentScopeMemberExpr::Create(
2469         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2470         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2471         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2472   }
2473 
2474   // Synthesize a fake NNS that points to the derived class.  This will
2475   // perform name lookup during template instantiation.
2476   CXXScopeSpec SS;
2477   auto *NNS =
2478       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2479   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2480   return DependentScopeDeclRefExpr::Create(
2481       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2482       TemplateArgs);
2483 }
2484 
2485 ExprResult
2486 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2487                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2488                         bool HasTrailingLParen, bool IsAddressOfOperand,
2489                         CorrectionCandidateCallback *CCC,
2490                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2491   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2492          "cannot be direct & operand and have a trailing lparen");
2493   if (SS.isInvalid())
2494     return ExprError();
2495 
2496   TemplateArgumentListInfo TemplateArgsBuffer;
2497 
2498   // Decompose the UnqualifiedId into the following data.
2499   DeclarationNameInfo NameInfo;
2500   const TemplateArgumentListInfo *TemplateArgs;
2501   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2502 
2503   DeclarationName Name = NameInfo.getName();
2504   IdentifierInfo *II = Name.getAsIdentifierInfo();
2505   SourceLocation NameLoc = NameInfo.getLoc();
2506 
2507   if (II && II->isEditorPlaceholder()) {
2508     // FIXME: When typed placeholders are supported we can create a typed
2509     // placeholder expression node.
2510     return ExprError();
2511   }
2512 
2513   // C++ [temp.dep.expr]p3:
2514   //   An id-expression is type-dependent if it contains:
2515   //     -- an identifier that was declared with a dependent type,
2516   //        (note: handled after lookup)
2517   //     -- a template-id that is dependent,
2518   //        (note: handled in BuildTemplateIdExpr)
2519   //     -- a conversion-function-id that specifies a dependent type,
2520   //     -- a nested-name-specifier that contains a class-name that
2521   //        names a dependent type.
2522   // Determine whether this is a member of an unknown specialization;
2523   // we need to handle these differently.
2524   bool DependentID = false;
2525   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2526       Name.getCXXNameType()->isDependentType()) {
2527     DependentID = true;
2528   } else if (SS.isSet()) {
2529     if (DeclContext *DC = computeDeclContext(SS, false)) {
2530       if (RequireCompleteDeclContext(SS, DC))
2531         return ExprError();
2532     } else {
2533       DependentID = true;
2534     }
2535   }
2536 
2537   if (DependentID)
2538     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2539                                       IsAddressOfOperand, TemplateArgs);
2540 
2541   // Perform the required lookup.
2542   LookupResult R(*this, NameInfo,
2543                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2544                      ? LookupObjCImplicitSelfParam
2545                      : LookupOrdinaryName);
2546   if (TemplateKWLoc.isValid() || TemplateArgs) {
2547     // Lookup the template name again to correctly establish the context in
2548     // which it was found. This is really unfortunate as we already did the
2549     // lookup to determine that it was a template name in the first place. If
2550     // this becomes a performance hit, we can work harder to preserve those
2551     // results until we get here but it's likely not worth it.
2552     bool MemberOfUnknownSpecialization;
2553     AssumedTemplateKind AssumedTemplate;
2554     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2555                            MemberOfUnknownSpecialization, TemplateKWLoc,
2556                            &AssumedTemplate))
2557       return ExprError();
2558 
2559     if (MemberOfUnknownSpecialization ||
2560         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2561       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2562                                         IsAddressOfOperand, TemplateArgs);
2563   } else {
2564     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2565     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2566 
2567     // If the result might be in a dependent base class, this is a dependent
2568     // id-expression.
2569     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2570       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2571                                         IsAddressOfOperand, TemplateArgs);
2572 
2573     // If this reference is in an Objective-C method, then we need to do
2574     // some special Objective-C lookup, too.
2575     if (IvarLookupFollowUp) {
2576       ExprResult E(LookupInObjCMethod(R, S, II, true));
2577       if (E.isInvalid())
2578         return ExprError();
2579 
2580       if (Expr *Ex = E.getAs<Expr>())
2581         return Ex;
2582     }
2583   }
2584 
2585   if (R.isAmbiguous())
2586     return ExprError();
2587 
2588   // This could be an implicitly declared function reference if the language
2589   // mode allows it as a feature.
2590   if (R.empty() && HasTrailingLParen && II &&
2591       getLangOpts().implicitFunctionsAllowed()) {
2592     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2593     if (D) R.addDecl(D);
2594   }
2595 
2596   // Determine whether this name might be a candidate for
2597   // argument-dependent lookup.
2598   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2599 
2600   if (R.empty() && !ADL) {
2601     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2602       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2603                                                    TemplateKWLoc, TemplateArgs))
2604         return E;
2605     }
2606 
2607     // Don't diagnose an empty lookup for inline assembly.
2608     if (IsInlineAsmIdentifier)
2609       return ExprError();
2610 
2611     // If this name wasn't predeclared and if this is not a function
2612     // call, diagnose the problem.
2613     TypoExpr *TE = nullptr;
2614     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2615                                                        : nullptr);
2616     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2617     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2618            "Typo correction callback misconfigured");
2619     if (CCC) {
2620       // Make sure the callback knows what the typo being diagnosed is.
2621       CCC->setTypoName(II);
2622       if (SS.isValid())
2623         CCC->setTypoNNS(SS.getScopeRep());
2624     }
2625     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2626     // a template name, but we happen to have always already looked up the name
2627     // before we get here if it must be a template name.
2628     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2629                             None, &TE)) {
2630       if (TE && KeywordReplacement) {
2631         auto &State = getTypoExprState(TE);
2632         auto BestTC = State.Consumer->getNextCorrection();
2633         if (BestTC.isKeyword()) {
2634           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2635           if (State.DiagHandler)
2636             State.DiagHandler(BestTC);
2637           KeywordReplacement->startToken();
2638           KeywordReplacement->setKind(II->getTokenID());
2639           KeywordReplacement->setIdentifierInfo(II);
2640           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2641           // Clean up the state associated with the TypoExpr, since it has
2642           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2643           clearDelayedTypo(TE);
2644           // Signal that a correction to a keyword was performed by returning a
2645           // valid-but-null ExprResult.
2646           return (Expr*)nullptr;
2647         }
2648         State.Consumer->resetCorrectionStream();
2649       }
2650       return TE ? TE : ExprError();
2651     }
2652 
2653     assert(!R.empty() &&
2654            "DiagnoseEmptyLookup returned false but added no results");
2655 
2656     // If we found an Objective-C instance variable, let
2657     // LookupInObjCMethod build the appropriate expression to
2658     // reference the ivar.
2659     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2660       R.clear();
2661       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2662       // In a hopelessly buggy code, Objective-C instance variable
2663       // lookup fails and no expression will be built to reference it.
2664       if (!E.isInvalid() && !E.get())
2665         return ExprError();
2666       return E;
2667     }
2668   }
2669 
2670   // This is guaranteed from this point on.
2671   assert(!R.empty() || ADL);
2672 
2673   // Check whether this might be a C++ implicit instance member access.
2674   // C++ [class.mfct.non-static]p3:
2675   //   When an id-expression that is not part of a class member access
2676   //   syntax and not used to form a pointer to member is used in the
2677   //   body of a non-static member function of class X, if name lookup
2678   //   resolves the name in the id-expression to a non-static non-type
2679   //   member of some class C, the id-expression is transformed into a
2680   //   class member access expression using (*this) as the
2681   //   postfix-expression to the left of the . operator.
2682   //
2683   // But we don't actually need to do this for '&' operands if R
2684   // resolved to a function or overloaded function set, because the
2685   // expression is ill-formed if it actually works out to be a
2686   // non-static member function:
2687   //
2688   // C++ [expr.ref]p4:
2689   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2690   //   [t]he expression can be used only as the left-hand operand of a
2691   //   member function call.
2692   //
2693   // There are other safeguards against such uses, but it's important
2694   // to get this right here so that we don't end up making a
2695   // spuriously dependent expression if we're inside a dependent
2696   // instance method.
2697   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2698     bool MightBeImplicitMember;
2699     if (!IsAddressOfOperand)
2700       MightBeImplicitMember = true;
2701     else if (!SS.isEmpty())
2702       MightBeImplicitMember = false;
2703     else if (R.isOverloadedResult())
2704       MightBeImplicitMember = false;
2705     else if (R.isUnresolvableResult())
2706       MightBeImplicitMember = true;
2707     else
2708       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2709                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2710                               isa<MSPropertyDecl>(R.getFoundDecl());
2711 
2712     if (MightBeImplicitMember)
2713       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2714                                              R, TemplateArgs, S);
2715   }
2716 
2717   if (TemplateArgs || TemplateKWLoc.isValid()) {
2718 
2719     // In C++1y, if this is a variable template id, then check it
2720     // in BuildTemplateIdExpr().
2721     // The single lookup result must be a variable template declaration.
2722     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2723         Id.TemplateId->Kind == TNK_Var_template) {
2724       assert(R.getAsSingle<VarTemplateDecl>() &&
2725              "There should only be one declaration found.");
2726     }
2727 
2728     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2729   }
2730 
2731   return BuildDeclarationNameExpr(SS, R, ADL);
2732 }
2733 
2734 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2735 /// declaration name, generally during template instantiation.
2736 /// There's a large number of things which don't need to be done along
2737 /// this path.
2738 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2739     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2740     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2741   DeclContext *DC = computeDeclContext(SS, false);
2742   if (!DC)
2743     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2744                                      NameInfo, /*TemplateArgs=*/nullptr);
2745 
2746   if (RequireCompleteDeclContext(SS, DC))
2747     return ExprError();
2748 
2749   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2750   LookupQualifiedName(R, DC);
2751 
2752   if (R.isAmbiguous())
2753     return ExprError();
2754 
2755   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2756     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2757                                      NameInfo, /*TemplateArgs=*/nullptr);
2758 
2759   if (R.empty()) {
2760     // Don't diagnose problems with invalid record decl, the secondary no_member
2761     // diagnostic during template instantiation is likely bogus, e.g. if a class
2762     // is invalid because it's derived from an invalid base class, then missing
2763     // members were likely supposed to be inherited.
2764     if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2765       if (CD->isInvalidDecl())
2766         return ExprError();
2767     Diag(NameInfo.getLoc(), diag::err_no_member)
2768       << NameInfo.getName() << DC << SS.getRange();
2769     return ExprError();
2770   }
2771 
2772   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2773     // Diagnose a missing typename if this resolved unambiguously to a type in
2774     // a dependent context.  If we can recover with a type, downgrade this to
2775     // a warning in Microsoft compatibility mode.
2776     unsigned DiagID = diag::err_typename_missing;
2777     if (RecoveryTSI && getLangOpts().MSVCCompat)
2778       DiagID = diag::ext_typename_missing;
2779     SourceLocation Loc = SS.getBeginLoc();
2780     auto D = Diag(Loc, DiagID);
2781     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2782       << SourceRange(Loc, NameInfo.getEndLoc());
2783 
2784     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2785     // context.
2786     if (!RecoveryTSI)
2787       return ExprError();
2788 
2789     // Only issue the fixit if we're prepared to recover.
2790     D << FixItHint::CreateInsertion(Loc, "typename ");
2791 
2792     // Recover by pretending this was an elaborated type.
2793     QualType Ty = Context.getTypeDeclType(TD);
2794     TypeLocBuilder TLB;
2795     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2796 
2797     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2798     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2799     QTL.setElaboratedKeywordLoc(SourceLocation());
2800     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2801 
2802     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2803 
2804     return ExprEmpty();
2805   }
2806 
2807   // Defend against this resolving to an implicit member access. We usually
2808   // won't get here if this might be a legitimate a class member (we end up in
2809   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2810   // a pointer-to-member or in an unevaluated context in C++11.
2811   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2812     return BuildPossibleImplicitMemberExpr(SS,
2813                                            /*TemplateKWLoc=*/SourceLocation(),
2814                                            R, /*TemplateArgs=*/nullptr, S);
2815 
2816   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2817 }
2818 
2819 /// The parser has read a name in, and Sema has detected that we're currently
2820 /// inside an ObjC method. Perform some additional checks and determine if we
2821 /// should form a reference to an ivar.
2822 ///
2823 /// Ideally, most of this would be done by lookup, but there's
2824 /// actually quite a lot of extra work involved.
2825 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2826                                         IdentifierInfo *II) {
2827   SourceLocation Loc = Lookup.getNameLoc();
2828   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2829 
2830   // Check for error condition which is already reported.
2831   if (!CurMethod)
2832     return DeclResult(true);
2833 
2834   // There are two cases to handle here.  1) scoped lookup could have failed,
2835   // in which case we should look for an ivar.  2) scoped lookup could have
2836   // found a decl, but that decl is outside the current instance method (i.e.
2837   // a global variable).  In these two cases, we do a lookup for an ivar with
2838   // this name, if the lookup sucedes, we replace it our current decl.
2839 
2840   // If we're in a class method, we don't normally want to look for
2841   // ivars.  But if we don't find anything else, and there's an
2842   // ivar, that's an error.
2843   bool IsClassMethod = CurMethod->isClassMethod();
2844 
2845   bool LookForIvars;
2846   if (Lookup.empty())
2847     LookForIvars = true;
2848   else if (IsClassMethod)
2849     LookForIvars = false;
2850   else
2851     LookForIvars = (Lookup.isSingleResult() &&
2852                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2853   ObjCInterfaceDecl *IFace = nullptr;
2854   if (LookForIvars) {
2855     IFace = CurMethod->getClassInterface();
2856     ObjCInterfaceDecl *ClassDeclared;
2857     ObjCIvarDecl *IV = nullptr;
2858     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2859       // Diagnose using an ivar in a class method.
2860       if (IsClassMethod) {
2861         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2862         return DeclResult(true);
2863       }
2864 
2865       // Diagnose the use of an ivar outside of the declaring class.
2866       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2867           !declaresSameEntity(ClassDeclared, IFace) &&
2868           !getLangOpts().DebuggerSupport)
2869         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2870 
2871       // Success.
2872       return IV;
2873     }
2874   } else if (CurMethod->isInstanceMethod()) {
2875     // We should warn if a local variable hides an ivar.
2876     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2877       ObjCInterfaceDecl *ClassDeclared;
2878       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2879         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2880             declaresSameEntity(IFace, ClassDeclared))
2881           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2882       }
2883     }
2884   } else if (Lookup.isSingleResult() &&
2885              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2886     // If accessing a stand-alone ivar in a class method, this is an error.
2887     if (const ObjCIvarDecl *IV =
2888             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2889       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2890       return DeclResult(true);
2891     }
2892   }
2893 
2894   // Didn't encounter an error, didn't find an ivar.
2895   return DeclResult(false);
2896 }
2897 
2898 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2899                                   ObjCIvarDecl *IV) {
2900   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2901   assert(CurMethod && CurMethod->isInstanceMethod() &&
2902          "should not reference ivar from this context");
2903 
2904   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2905   assert(IFace && "should not reference ivar from this context");
2906 
2907   // If we're referencing an invalid decl, just return this as a silent
2908   // error node.  The error diagnostic was already emitted on the decl.
2909   if (IV->isInvalidDecl())
2910     return ExprError();
2911 
2912   // Check if referencing a field with __attribute__((deprecated)).
2913   if (DiagnoseUseOfDecl(IV, Loc))
2914     return ExprError();
2915 
2916   // FIXME: This should use a new expr for a direct reference, don't
2917   // turn this into Self->ivar, just return a BareIVarExpr or something.
2918   IdentifierInfo &II = Context.Idents.get("self");
2919   UnqualifiedId SelfName;
2920   SelfName.setImplicitSelfParam(&II);
2921   CXXScopeSpec SelfScopeSpec;
2922   SourceLocation TemplateKWLoc;
2923   ExprResult SelfExpr =
2924       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2925                         /*HasTrailingLParen=*/false,
2926                         /*IsAddressOfOperand=*/false);
2927   if (SelfExpr.isInvalid())
2928     return ExprError();
2929 
2930   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2931   if (SelfExpr.isInvalid())
2932     return ExprError();
2933 
2934   MarkAnyDeclReferenced(Loc, IV, true);
2935 
2936   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2937   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2938       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2939     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2940 
2941   ObjCIvarRefExpr *Result = new (Context)
2942       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2943                       IV->getLocation(), SelfExpr.get(), true, true);
2944 
2945   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2946     if (!isUnevaluatedContext() &&
2947         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2948       getCurFunction()->recordUseOfWeak(Result);
2949   }
2950   if (getLangOpts().ObjCAutoRefCount)
2951     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2952       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2953 
2954   return Result;
2955 }
2956 
2957 /// The parser has read a name in, and Sema has detected that we're currently
2958 /// inside an ObjC method. Perform some additional checks and determine if we
2959 /// should form a reference to an ivar. If so, build an expression referencing
2960 /// that ivar.
2961 ExprResult
2962 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2963                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2964   // FIXME: Integrate this lookup step into LookupParsedName.
2965   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2966   if (Ivar.isInvalid())
2967     return ExprError();
2968   if (Ivar.isUsable())
2969     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2970                             cast<ObjCIvarDecl>(Ivar.get()));
2971 
2972   if (Lookup.empty() && II && AllowBuiltinCreation)
2973     LookupBuiltin(Lookup);
2974 
2975   // Sentinel value saying that we didn't do anything special.
2976   return ExprResult(false);
2977 }
2978 
2979 /// Cast a base object to a member's actual type.
2980 ///
2981 /// There are two relevant checks:
2982 ///
2983 /// C++ [class.access.base]p7:
2984 ///
2985 ///   If a class member access operator [...] is used to access a non-static
2986 ///   data member or non-static member function, the reference is ill-formed if
2987 ///   the left operand [...] cannot be implicitly converted to a pointer to the
2988 ///   naming class of the right operand.
2989 ///
2990 /// C++ [expr.ref]p7:
2991 ///
2992 ///   If E2 is a non-static data member or a non-static member function, the
2993 ///   program is ill-formed if the class of which E2 is directly a member is an
2994 ///   ambiguous base (11.8) of the naming class (11.9.3) of E2.
2995 ///
2996 /// Note that the latter check does not consider access; the access of the
2997 /// "real" base class is checked as appropriate when checking the access of the
2998 /// member name.
2999 ExprResult
3000 Sema::PerformObjectMemberConversion(Expr *From,
3001                                     NestedNameSpecifier *Qualifier,
3002                                     NamedDecl *FoundDecl,
3003                                     NamedDecl *Member) {
3004   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3005   if (!RD)
3006     return From;
3007 
3008   QualType DestRecordType;
3009   QualType DestType;
3010   QualType FromRecordType;
3011   QualType FromType = From->getType();
3012   bool PointerConversions = false;
3013   if (isa<FieldDecl>(Member)) {
3014     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3015     auto FromPtrType = FromType->getAs<PointerType>();
3016     DestRecordType = Context.getAddrSpaceQualType(
3017         DestRecordType, FromPtrType
3018                             ? FromType->getPointeeType().getAddressSpace()
3019                             : FromType.getAddressSpace());
3020 
3021     if (FromPtrType) {
3022       DestType = Context.getPointerType(DestRecordType);
3023       FromRecordType = FromPtrType->getPointeeType();
3024       PointerConversions = true;
3025     } else {
3026       DestType = DestRecordType;
3027       FromRecordType = FromType;
3028     }
3029   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
3030     if (Method->isStatic())
3031       return From;
3032 
3033     DestType = Method->getThisType();
3034     DestRecordType = DestType->getPointeeType();
3035 
3036     if (FromType->getAs<PointerType>()) {
3037       FromRecordType = FromType->getPointeeType();
3038       PointerConversions = true;
3039     } else {
3040       FromRecordType = FromType;
3041       DestType = DestRecordType;
3042     }
3043 
3044     LangAS FromAS = FromRecordType.getAddressSpace();
3045     LangAS DestAS = DestRecordType.getAddressSpace();
3046     if (FromAS != DestAS) {
3047       QualType FromRecordTypeWithoutAS =
3048           Context.removeAddrSpaceQualType(FromRecordType);
3049       QualType FromTypeWithDestAS =
3050           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3051       if (PointerConversions)
3052         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3053       From = ImpCastExprToType(From, FromTypeWithDestAS,
3054                                CK_AddressSpaceConversion, From->getValueKind())
3055                  .get();
3056     }
3057   } else {
3058     // No conversion necessary.
3059     return From;
3060   }
3061 
3062   if (DestType->isDependentType() || FromType->isDependentType())
3063     return From;
3064 
3065   // If the unqualified types are the same, no conversion is necessary.
3066   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3067     return From;
3068 
3069   SourceRange FromRange = From->getSourceRange();
3070   SourceLocation FromLoc = FromRange.getBegin();
3071 
3072   ExprValueKind VK = From->getValueKind();
3073 
3074   // C++ [class.member.lookup]p8:
3075   //   [...] Ambiguities can often be resolved by qualifying a name with its
3076   //   class name.
3077   //
3078   // If the member was a qualified name and the qualified referred to a
3079   // specific base subobject type, we'll cast to that intermediate type
3080   // first and then to the object in which the member is declared. That allows
3081   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3082   //
3083   //   class Base { public: int x; };
3084   //   class Derived1 : public Base { };
3085   //   class Derived2 : public Base { };
3086   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
3087   //
3088   //   void VeryDerived::f() {
3089   //     x = 17; // error: ambiguous base subobjects
3090   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
3091   //   }
3092   if (Qualifier && Qualifier->getAsType()) {
3093     QualType QType = QualType(Qualifier->getAsType(), 0);
3094     assert(QType->isRecordType() && "lookup done with non-record type");
3095 
3096     QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3097 
3098     // In C++98, the qualifier type doesn't actually have to be a base
3099     // type of the object type, in which case we just ignore it.
3100     // Otherwise build the appropriate casts.
3101     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3102       CXXCastPath BasePath;
3103       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3104                                        FromLoc, FromRange, &BasePath))
3105         return ExprError();
3106 
3107       if (PointerConversions)
3108         QType = Context.getPointerType(QType);
3109       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3110                                VK, &BasePath).get();
3111 
3112       FromType = QType;
3113       FromRecordType = QRecordType;
3114 
3115       // If the qualifier type was the same as the destination type,
3116       // we're done.
3117       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3118         return From;
3119     }
3120   }
3121 
3122   CXXCastPath BasePath;
3123   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3124                                    FromLoc, FromRange, &BasePath,
3125                                    /*IgnoreAccess=*/true))
3126     return ExprError();
3127 
3128   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3129                            VK, &BasePath);
3130 }
3131 
3132 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3133                                       const LookupResult &R,
3134                                       bool HasTrailingLParen) {
3135   // Only when used directly as the postfix-expression of a call.
3136   if (!HasTrailingLParen)
3137     return false;
3138 
3139   // Never if a scope specifier was provided.
3140   if (SS.isSet())
3141     return false;
3142 
3143   // Only in C++ or ObjC++.
3144   if (!getLangOpts().CPlusPlus)
3145     return false;
3146 
3147   // Turn off ADL when we find certain kinds of declarations during
3148   // normal lookup:
3149   for (NamedDecl *D : R) {
3150     // C++0x [basic.lookup.argdep]p3:
3151     //     -- a declaration of a class member
3152     // Since using decls preserve this property, we check this on the
3153     // original decl.
3154     if (D->isCXXClassMember())
3155       return false;
3156 
3157     // C++0x [basic.lookup.argdep]p3:
3158     //     -- a block-scope function declaration that is not a
3159     //        using-declaration
3160     // NOTE: we also trigger this for function templates (in fact, we
3161     // don't check the decl type at all, since all other decl types
3162     // turn off ADL anyway).
3163     if (isa<UsingShadowDecl>(D))
3164       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3165     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3166       return false;
3167 
3168     // C++0x [basic.lookup.argdep]p3:
3169     //     -- a declaration that is neither a function or a function
3170     //        template
3171     // And also for builtin functions.
3172     if (isa<FunctionDecl>(D)) {
3173       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3174 
3175       // But also builtin functions.
3176       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3177         return false;
3178     } else if (!isa<FunctionTemplateDecl>(D))
3179       return false;
3180   }
3181 
3182   return true;
3183 }
3184 
3185 
3186 /// Diagnoses obvious problems with the use of the given declaration
3187 /// as an expression.  This is only actually called for lookups that
3188 /// were not overloaded, and it doesn't promise that the declaration
3189 /// will in fact be used.
3190 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3191   if (D->isInvalidDecl())
3192     return true;
3193 
3194   if (isa<TypedefNameDecl>(D)) {
3195     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3196     return true;
3197   }
3198 
3199   if (isa<ObjCInterfaceDecl>(D)) {
3200     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3201     return true;
3202   }
3203 
3204   if (isa<NamespaceDecl>(D)) {
3205     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3206     return true;
3207   }
3208 
3209   return false;
3210 }
3211 
3212 // Certain multiversion types should be treated as overloaded even when there is
3213 // only one result.
3214 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3215   assert(R.isSingleResult() && "Expected only a single result");
3216   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3217   return FD &&
3218          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3219 }
3220 
3221 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3222                                           LookupResult &R, bool NeedsADL,
3223                                           bool AcceptInvalidDecl) {
3224   // If this is a single, fully-resolved result and we don't need ADL,
3225   // just build an ordinary singleton decl ref.
3226   if (!NeedsADL && R.isSingleResult() &&
3227       !R.getAsSingle<FunctionTemplateDecl>() &&
3228       !ShouldLookupResultBeMultiVersionOverload(R))
3229     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3230                                     R.getRepresentativeDecl(), nullptr,
3231                                     AcceptInvalidDecl);
3232 
3233   // We only need to check the declaration if there's exactly one
3234   // result, because in the overloaded case the results can only be
3235   // functions and function templates.
3236   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3237       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3238     return ExprError();
3239 
3240   // Otherwise, just build an unresolved lookup expression.  Suppress
3241   // any lookup-related diagnostics; we'll hash these out later, when
3242   // we've picked a target.
3243   R.suppressDiagnostics();
3244 
3245   UnresolvedLookupExpr *ULE
3246     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3247                                    SS.getWithLocInContext(Context),
3248                                    R.getLookupNameInfo(),
3249                                    NeedsADL, R.isOverloadedResult(),
3250                                    R.begin(), R.end());
3251 
3252   return ULE;
3253 }
3254 
3255 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3256                                                ValueDecl *var);
3257 
3258 /// Complete semantic analysis for a reference to the given declaration.
3259 ExprResult Sema::BuildDeclarationNameExpr(
3260     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3261     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3262     bool AcceptInvalidDecl) {
3263   assert(D && "Cannot refer to a NULL declaration");
3264   assert(!isa<FunctionTemplateDecl>(D) &&
3265          "Cannot refer unambiguously to a function template");
3266 
3267   SourceLocation Loc = NameInfo.getLoc();
3268   if (CheckDeclInExpr(*this, Loc, D)) {
3269     // Recovery from invalid cases (e.g. D is an invalid Decl).
3270     // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3271     // diagnostics, as invalid decls use int as a fallback type.
3272     return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3273   }
3274 
3275   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3276     // Specifically diagnose references to class templates that are missing
3277     // a template argument list.
3278     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3279     return ExprError();
3280   }
3281 
3282   // Make sure that we're referring to a value.
3283   if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3284     Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3285     Diag(D->getLocation(), diag::note_declared_at);
3286     return ExprError();
3287   }
3288 
3289   // Check whether this declaration can be used. Note that we suppress
3290   // this check when we're going to perform argument-dependent lookup
3291   // on this function name, because this might not be the function
3292   // that overload resolution actually selects.
3293   if (DiagnoseUseOfDecl(D, Loc))
3294     return ExprError();
3295 
3296   auto *VD = cast<ValueDecl>(D);
3297 
3298   // Only create DeclRefExpr's for valid Decl's.
3299   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3300     return ExprError();
3301 
3302   // Handle members of anonymous structs and unions.  If we got here,
3303   // and the reference is to a class member indirect field, then this
3304   // must be the subject of a pointer-to-member expression.
3305   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3306     if (!indirectField->isCXXClassMember())
3307       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3308                                                       indirectField);
3309 
3310   QualType type = VD->getType();
3311   if (type.isNull())
3312     return ExprError();
3313   ExprValueKind valueKind = VK_PRValue;
3314 
3315   // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3316   // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3317   // is expanded by some outer '...' in the context of the use.
3318   type = type.getNonPackExpansionType();
3319 
3320   switch (D->getKind()) {
3321     // Ignore all the non-ValueDecl kinds.
3322 #define ABSTRACT_DECL(kind)
3323 #define VALUE(type, base)
3324 #define DECL(type, base) case Decl::type:
3325 #include "clang/AST/DeclNodes.inc"
3326     llvm_unreachable("invalid value decl kind");
3327 
3328   // These shouldn't make it here.
3329   case Decl::ObjCAtDefsField:
3330     llvm_unreachable("forming non-member reference to ivar?");
3331 
3332   // Enum constants are always r-values and never references.
3333   // Unresolved using declarations are dependent.
3334   case Decl::EnumConstant:
3335   case Decl::UnresolvedUsingValue:
3336   case Decl::OMPDeclareReduction:
3337   case Decl::OMPDeclareMapper:
3338     valueKind = VK_PRValue;
3339     break;
3340 
3341   // Fields and indirect fields that got here must be for
3342   // pointer-to-member expressions; we just call them l-values for
3343   // internal consistency, because this subexpression doesn't really
3344   // exist in the high-level semantics.
3345   case Decl::Field:
3346   case Decl::IndirectField:
3347   case Decl::ObjCIvar:
3348     assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3349 
3350     // These can't have reference type in well-formed programs, but
3351     // for internal consistency we do this anyway.
3352     type = type.getNonReferenceType();
3353     valueKind = VK_LValue;
3354     break;
3355 
3356   // Non-type template parameters are either l-values or r-values
3357   // depending on the type.
3358   case Decl::NonTypeTemplateParm: {
3359     if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3360       type = reftype->getPointeeType();
3361       valueKind = VK_LValue; // even if the parameter is an r-value reference
3362       break;
3363     }
3364 
3365     // [expr.prim.id.unqual]p2:
3366     //   If the entity is a template parameter object for a template
3367     //   parameter of type T, the type of the expression is const T.
3368     //   [...] The expression is an lvalue if the entity is a [...] template
3369     //   parameter object.
3370     if (type->isRecordType()) {
3371       type = type.getUnqualifiedType().withConst();
3372       valueKind = VK_LValue;
3373       break;
3374     }
3375 
3376     // For non-references, we need to strip qualifiers just in case
3377     // the template parameter was declared as 'const int' or whatever.
3378     valueKind = VK_PRValue;
3379     type = type.getUnqualifiedType();
3380     break;
3381   }
3382 
3383   case Decl::Var:
3384   case Decl::VarTemplateSpecialization:
3385   case Decl::VarTemplatePartialSpecialization:
3386   case Decl::Decomposition:
3387   case Decl::OMPCapturedExpr:
3388     // In C, "extern void blah;" is valid and is an r-value.
3389     if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3390         type->isVoidType()) {
3391       valueKind = VK_PRValue;
3392       break;
3393     }
3394     LLVM_FALLTHROUGH;
3395 
3396   case Decl::ImplicitParam:
3397   case Decl::ParmVar: {
3398     // These are always l-values.
3399     valueKind = VK_LValue;
3400     type = type.getNonReferenceType();
3401 
3402     // FIXME: Does the addition of const really only apply in
3403     // potentially-evaluated contexts? Since the variable isn't actually
3404     // captured in an unevaluated context, it seems that the answer is no.
3405     if (!isUnevaluatedContext()) {
3406       QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3407       if (!CapturedType.isNull())
3408         type = CapturedType;
3409     }
3410 
3411     break;
3412   }
3413 
3414   case Decl::Binding: {
3415     // These are always lvalues.
3416     valueKind = VK_LValue;
3417     type = type.getNonReferenceType();
3418     // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3419     // decides how that's supposed to work.
3420     auto *BD = cast<BindingDecl>(VD);
3421     if (BD->getDeclContext() != CurContext) {
3422       auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3423       if (DD && DD->hasLocalStorage())
3424         diagnoseUncapturableValueReference(*this, Loc, BD);
3425     }
3426     break;
3427   }
3428 
3429   case Decl::Function: {
3430     if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3431       if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3432         type = Context.BuiltinFnTy;
3433         valueKind = VK_PRValue;
3434         break;
3435       }
3436     }
3437 
3438     const FunctionType *fty = type->castAs<FunctionType>();
3439 
3440     // If we're referring to a function with an __unknown_anytype
3441     // result type, make the entire expression __unknown_anytype.
3442     if (fty->getReturnType() == Context.UnknownAnyTy) {
3443       type = Context.UnknownAnyTy;
3444       valueKind = VK_PRValue;
3445       break;
3446     }
3447 
3448     // Functions are l-values in C++.
3449     if (getLangOpts().CPlusPlus) {
3450       valueKind = VK_LValue;
3451       break;
3452     }
3453 
3454     // C99 DR 316 says that, if a function type comes from a
3455     // function definition (without a prototype), that type is only
3456     // used for checking compatibility. Therefore, when referencing
3457     // the function, we pretend that we don't have the full function
3458     // type.
3459     if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3460       type = Context.getFunctionNoProtoType(fty->getReturnType(),
3461                                             fty->getExtInfo());
3462 
3463     // Functions are r-values in C.
3464     valueKind = VK_PRValue;
3465     break;
3466   }
3467 
3468   case Decl::CXXDeductionGuide:
3469     llvm_unreachable("building reference to deduction guide");
3470 
3471   case Decl::MSProperty:
3472   case Decl::MSGuid:
3473   case Decl::TemplateParamObject:
3474     // FIXME: Should MSGuidDecl and template parameter objects be subject to
3475     // capture in OpenMP, or duplicated between host and device?
3476     valueKind = VK_LValue;
3477     break;
3478 
3479   case Decl::UnnamedGlobalConstant:
3480     valueKind = VK_LValue;
3481     break;
3482 
3483   case Decl::CXXMethod:
3484     // If we're referring to a method with an __unknown_anytype
3485     // result type, make the entire expression __unknown_anytype.
3486     // This should only be possible with a type written directly.
3487     if (const FunctionProtoType *proto =
3488             dyn_cast<FunctionProtoType>(VD->getType()))
3489       if (proto->getReturnType() == Context.UnknownAnyTy) {
3490         type = Context.UnknownAnyTy;
3491         valueKind = VK_PRValue;
3492         break;
3493       }
3494 
3495     // C++ methods are l-values if static, r-values if non-static.
3496     if (cast<CXXMethodDecl>(VD)->isStatic()) {
3497       valueKind = VK_LValue;
3498       break;
3499     }
3500     LLVM_FALLTHROUGH;
3501 
3502   case Decl::CXXConversion:
3503   case Decl::CXXDestructor:
3504   case Decl::CXXConstructor:
3505     valueKind = VK_PRValue;
3506     break;
3507   }
3508 
3509   return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3510                           /*FIXME: TemplateKWLoc*/ SourceLocation(),
3511                           TemplateArgs);
3512 }
3513 
3514 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3515                                     SmallString<32> &Target) {
3516   Target.resize(CharByteWidth * (Source.size() + 1));
3517   char *ResultPtr = &Target[0];
3518   const llvm::UTF8 *ErrorPtr;
3519   bool success =
3520       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3521   (void)success;
3522   assert(success);
3523   Target.resize(ResultPtr - &Target[0]);
3524 }
3525 
3526 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3527                                      PredefinedExpr::IdentKind IK) {
3528   // Pick the current block, lambda, captured statement or function.
3529   Decl *currentDecl = nullptr;
3530   if (const BlockScopeInfo *BSI = getCurBlock())
3531     currentDecl = BSI->TheDecl;
3532   else if (const LambdaScopeInfo *LSI = getCurLambda())
3533     currentDecl = LSI->CallOperator;
3534   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3535     currentDecl = CSI->TheCapturedDecl;
3536   else
3537     currentDecl = getCurFunctionOrMethodDecl();
3538 
3539   if (!currentDecl) {
3540     Diag(Loc, diag::ext_predef_outside_function);
3541     currentDecl = Context.getTranslationUnitDecl();
3542   }
3543 
3544   QualType ResTy;
3545   StringLiteral *SL = nullptr;
3546   if (cast<DeclContext>(currentDecl)->isDependentContext())
3547     ResTy = Context.DependentTy;
3548   else {
3549     // Pre-defined identifiers are of type char[x], where x is the length of
3550     // the string.
3551     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3552     unsigned Length = Str.length();
3553 
3554     llvm::APInt LengthI(32, Length + 1);
3555     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3556       ResTy =
3557           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3558       SmallString<32> RawChars;
3559       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3560                               Str, RawChars);
3561       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3562                                            ArrayType::Normal,
3563                                            /*IndexTypeQuals*/ 0);
3564       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3565                                  /*Pascal*/ false, ResTy, Loc);
3566     } else {
3567       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3568       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3569                                            ArrayType::Normal,
3570                                            /*IndexTypeQuals*/ 0);
3571       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3572                                  /*Pascal*/ false, ResTy, Loc);
3573     }
3574   }
3575 
3576   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3577 }
3578 
3579 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3580                                                SourceLocation LParen,
3581                                                SourceLocation RParen,
3582                                                TypeSourceInfo *TSI) {
3583   return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3584 }
3585 
3586 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3587                                                SourceLocation LParen,
3588                                                SourceLocation RParen,
3589                                                ParsedType ParsedTy) {
3590   TypeSourceInfo *TSI = nullptr;
3591   QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3592 
3593   if (Ty.isNull())
3594     return ExprError();
3595   if (!TSI)
3596     TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3597 
3598   return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3599 }
3600 
3601 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3602   PredefinedExpr::IdentKind IK;
3603 
3604   switch (Kind) {
3605   default: llvm_unreachable("Unknown simple primary expr!");
3606   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3607   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3608   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3609   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3610   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3611   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3612   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3613   }
3614 
3615   return BuildPredefinedExpr(Loc, IK);
3616 }
3617 
3618 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3619   SmallString<16> CharBuffer;
3620   bool Invalid = false;
3621   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3622   if (Invalid)
3623     return ExprError();
3624 
3625   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3626                             PP, Tok.getKind());
3627   if (Literal.hadError())
3628     return ExprError();
3629 
3630   QualType Ty;
3631   if (Literal.isWide())
3632     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3633   else if (Literal.isUTF8() && getLangOpts().C2x)
3634     Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x
3635   else if (Literal.isUTF8() && getLangOpts().Char8)
3636     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3637   else if (Literal.isUTF16())
3638     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3639   else if (Literal.isUTF32())
3640     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3641   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3642     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3643   else
3644     Ty = Context.CharTy; // 'x' -> char in C++;
3645                          // u8'x' -> char in C11-C17 and in C++ without char8_t.
3646 
3647   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3648   if (Literal.isWide())
3649     Kind = CharacterLiteral::Wide;
3650   else if (Literal.isUTF16())
3651     Kind = CharacterLiteral::UTF16;
3652   else if (Literal.isUTF32())
3653     Kind = CharacterLiteral::UTF32;
3654   else if (Literal.isUTF8())
3655     Kind = CharacterLiteral::UTF8;
3656 
3657   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3658                                              Tok.getLocation());
3659 
3660   if (Literal.getUDSuffix().empty())
3661     return Lit;
3662 
3663   // We're building a user-defined literal.
3664   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3665   SourceLocation UDSuffixLoc =
3666     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3667 
3668   // Make sure we're allowed user-defined literals here.
3669   if (!UDLScope)
3670     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3671 
3672   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3673   //   operator "" X (ch)
3674   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3675                                         Lit, Tok.getLocation());
3676 }
3677 
3678 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3679   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3680   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3681                                 Context.IntTy, Loc);
3682 }
3683 
3684 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3685                                   QualType Ty, SourceLocation Loc) {
3686   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3687 
3688   using llvm::APFloat;
3689   APFloat Val(Format);
3690 
3691   APFloat::opStatus result = Literal.GetFloatValue(Val);
3692 
3693   // Overflow is always an error, but underflow is only an error if
3694   // we underflowed to zero (APFloat reports denormals as underflow).
3695   if ((result & APFloat::opOverflow) ||
3696       ((result & APFloat::opUnderflow) && Val.isZero())) {
3697     unsigned diagnostic;
3698     SmallString<20> buffer;
3699     if (result & APFloat::opOverflow) {
3700       diagnostic = diag::warn_float_overflow;
3701       APFloat::getLargest(Format).toString(buffer);
3702     } else {
3703       diagnostic = diag::warn_float_underflow;
3704       APFloat::getSmallest(Format).toString(buffer);
3705     }
3706 
3707     S.Diag(Loc, diagnostic)
3708       << Ty
3709       << StringRef(buffer.data(), buffer.size());
3710   }
3711 
3712   bool isExact = (result == APFloat::opOK);
3713   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3714 }
3715 
3716 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3717   assert(E && "Invalid expression");
3718 
3719   if (E->isValueDependent())
3720     return false;
3721 
3722   QualType QT = E->getType();
3723   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3724     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3725     return true;
3726   }
3727 
3728   llvm::APSInt ValueAPS;
3729   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3730 
3731   if (R.isInvalid())
3732     return true;
3733 
3734   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3735   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3736     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3737         << toString(ValueAPS, 10) << ValueIsPositive;
3738     return true;
3739   }
3740 
3741   return false;
3742 }
3743 
3744 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3745   // Fast path for a single digit (which is quite common).  A single digit
3746   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3747   if (Tok.getLength() == 1) {
3748     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3749     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3750   }
3751 
3752   SmallString<128> SpellingBuffer;
3753   // NumericLiteralParser wants to overread by one character.  Add padding to
3754   // the buffer in case the token is copied to the buffer.  If getSpelling()
3755   // returns a StringRef to the memory buffer, it should have a null char at
3756   // the EOF, so it is also safe.
3757   SpellingBuffer.resize(Tok.getLength() + 1);
3758 
3759   // Get the spelling of the token, which eliminates trigraphs, etc.
3760   bool Invalid = false;
3761   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3762   if (Invalid)
3763     return ExprError();
3764 
3765   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3766                                PP.getSourceManager(), PP.getLangOpts(),
3767                                PP.getTargetInfo(), PP.getDiagnostics());
3768   if (Literal.hadError)
3769     return ExprError();
3770 
3771   if (Literal.hasUDSuffix()) {
3772     // We're building a user-defined literal.
3773     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3774     SourceLocation UDSuffixLoc =
3775       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3776 
3777     // Make sure we're allowed user-defined literals here.
3778     if (!UDLScope)
3779       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3780 
3781     QualType CookedTy;
3782     if (Literal.isFloatingLiteral()) {
3783       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3784       // long double, the literal is treated as a call of the form
3785       //   operator "" X (f L)
3786       CookedTy = Context.LongDoubleTy;
3787     } else {
3788       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3789       // unsigned long long, the literal is treated as a call of the form
3790       //   operator "" X (n ULL)
3791       CookedTy = Context.UnsignedLongLongTy;
3792     }
3793 
3794     DeclarationName OpName =
3795       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3796     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3797     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3798 
3799     SourceLocation TokLoc = Tok.getLocation();
3800 
3801     // Perform literal operator lookup to determine if we're building a raw
3802     // literal or a cooked one.
3803     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3804     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3805                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3806                                   /*AllowStringTemplatePack*/ false,
3807                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3808     case LOLR_ErrorNoDiagnostic:
3809       // Lookup failure for imaginary constants isn't fatal, there's still the
3810       // GNU extension producing _Complex types.
3811       break;
3812     case LOLR_Error:
3813       return ExprError();
3814     case LOLR_Cooked: {
3815       Expr *Lit;
3816       if (Literal.isFloatingLiteral()) {
3817         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3818       } else {
3819         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3820         if (Literal.GetIntegerValue(ResultVal))
3821           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3822               << /* Unsigned */ 1;
3823         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3824                                      Tok.getLocation());
3825       }
3826       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3827     }
3828 
3829     case LOLR_Raw: {
3830       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3831       // literal is treated as a call of the form
3832       //   operator "" X ("n")
3833       unsigned Length = Literal.getUDSuffixOffset();
3834       QualType StrTy = Context.getConstantArrayType(
3835           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3836           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3837       Expr *Lit = StringLiteral::Create(
3838           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3839           /*Pascal*/false, StrTy, &TokLoc, 1);
3840       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3841     }
3842 
3843     case LOLR_Template: {
3844       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3845       // template), L is treated as a call fo the form
3846       //   operator "" X <'c1', 'c2', ... 'ck'>()
3847       // where n is the source character sequence c1 c2 ... ck.
3848       TemplateArgumentListInfo ExplicitArgs;
3849       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3850       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3851       llvm::APSInt Value(CharBits, CharIsUnsigned);
3852       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3853         Value = TokSpelling[I];
3854         TemplateArgument Arg(Context, Value, Context.CharTy);
3855         TemplateArgumentLocInfo ArgInfo;
3856         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3857       }
3858       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3859                                       &ExplicitArgs);
3860     }
3861     case LOLR_StringTemplatePack:
3862       llvm_unreachable("unexpected literal operator lookup result");
3863     }
3864   }
3865 
3866   Expr *Res;
3867 
3868   if (Literal.isFixedPointLiteral()) {
3869     QualType Ty;
3870 
3871     if (Literal.isAccum) {
3872       if (Literal.isHalf) {
3873         Ty = Context.ShortAccumTy;
3874       } else if (Literal.isLong) {
3875         Ty = Context.LongAccumTy;
3876       } else {
3877         Ty = Context.AccumTy;
3878       }
3879     } else if (Literal.isFract) {
3880       if (Literal.isHalf) {
3881         Ty = Context.ShortFractTy;
3882       } else if (Literal.isLong) {
3883         Ty = Context.LongFractTy;
3884       } else {
3885         Ty = Context.FractTy;
3886       }
3887     }
3888 
3889     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3890 
3891     bool isSigned = !Literal.isUnsigned;
3892     unsigned scale = Context.getFixedPointScale(Ty);
3893     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3894 
3895     llvm::APInt Val(bit_width, 0, isSigned);
3896     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3897     bool ValIsZero = Val.isZero() && !Overflowed;
3898 
3899     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3900     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3901       // Clause 6.4.4 - The value of a constant shall be in the range of
3902       // representable values for its type, with exception for constants of a
3903       // fract type with a value of exactly 1; such a constant shall denote
3904       // the maximal value for the type.
3905       --Val;
3906     else if (Val.ugt(MaxVal) || Overflowed)
3907       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3908 
3909     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3910                                               Tok.getLocation(), scale);
3911   } else if (Literal.isFloatingLiteral()) {
3912     QualType Ty;
3913     if (Literal.isHalf){
3914       if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3915         Ty = Context.HalfTy;
3916       else {
3917         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3918         return ExprError();
3919       }
3920     } else if (Literal.isFloat)
3921       Ty = Context.FloatTy;
3922     else if (Literal.isLong)
3923       Ty = Context.LongDoubleTy;
3924     else if (Literal.isFloat16)
3925       Ty = Context.Float16Ty;
3926     else if (Literal.isFloat128)
3927       Ty = Context.Float128Ty;
3928     else
3929       Ty = Context.DoubleTy;
3930 
3931     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3932 
3933     if (Ty == Context.DoubleTy) {
3934       if (getLangOpts().SinglePrecisionConstants) {
3935         if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3936           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3937         }
3938       } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3939                                              "cl_khr_fp64", getLangOpts())) {
3940         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3941         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3942             << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3943         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3944       }
3945     }
3946   } else if (!Literal.isIntegerLiteral()) {
3947     return ExprError();
3948   } else {
3949     QualType Ty;
3950 
3951     // 'long long' is a C99 or C++11 feature.
3952     if (!getLangOpts().C99 && Literal.isLongLong) {
3953       if (getLangOpts().CPlusPlus)
3954         Diag(Tok.getLocation(),
3955              getLangOpts().CPlusPlus11 ?
3956              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3957       else
3958         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3959     }
3960 
3961     // 'z/uz' literals are a C++2b feature.
3962     if (Literal.isSizeT)
3963       Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3964                                   ? getLangOpts().CPlusPlus2b
3965                                         ? diag::warn_cxx20_compat_size_t_suffix
3966                                         : diag::ext_cxx2b_size_t_suffix
3967                                   : diag::err_cxx2b_size_t_suffix);
3968 
3969     // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3970     // but we do not currently support the suffix in C++ mode because it's not
3971     // entirely clear whether WG21 will prefer this suffix to return a library
3972     // type such as std::bit_int instead of returning a _BitInt.
3973     if (Literal.isBitInt && !getLangOpts().CPlusPlus)
3974       PP.Diag(Tok.getLocation(), getLangOpts().C2x
3975                                      ? diag::warn_c2x_compat_bitint_suffix
3976                                      : diag::ext_c2x_bitint_suffix);
3977 
3978     // Get the value in the widest-possible width. What is "widest" depends on
3979     // whether the literal is a bit-precise integer or not. For a bit-precise
3980     // integer type, try to scan the source to determine how many bits are
3981     // needed to represent the value. This may seem a bit expensive, but trying
3982     // to get the integer value from an overly-wide APInt is *extremely*
3983     // expensive, so the naive approach of assuming
3984     // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3985     unsigned BitsNeeded =
3986         Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3987                                Literal.getLiteralDigits(), Literal.getRadix())
3988                          : Context.getTargetInfo().getIntMaxTWidth();
3989     llvm::APInt ResultVal(BitsNeeded, 0);
3990 
3991     if (Literal.GetIntegerValue(ResultVal)) {
3992       // If this value didn't fit into uintmax_t, error and force to ull.
3993       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3994           << /* Unsigned */ 1;
3995       Ty = Context.UnsignedLongLongTy;
3996       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3997              "long long is not intmax_t?");
3998     } else {
3999       // If this value fits into a ULL, try to figure out what else it fits into
4000       // according to the rules of C99 6.4.4.1p5.
4001 
4002       // Octal, Hexadecimal, and integers with a U suffix are allowed to
4003       // be an unsigned int.
4004       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4005 
4006       // Check from smallest to largest, picking the smallest type we can.
4007       unsigned Width = 0;
4008 
4009       // Microsoft specific integer suffixes are explicitly sized.
4010       if (Literal.MicrosoftInteger) {
4011         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4012           Width = 8;
4013           Ty = Context.CharTy;
4014         } else {
4015           Width = Literal.MicrosoftInteger;
4016           Ty = Context.getIntTypeForBitwidth(Width,
4017                                              /*Signed=*/!Literal.isUnsigned);
4018         }
4019       }
4020 
4021       // Bit-precise integer literals are automagically-sized based on the
4022       // width required by the literal.
4023       if (Literal.isBitInt) {
4024         // The signed version has one more bit for the sign value. There are no
4025         // zero-width bit-precise integers, even if the literal value is 0.
4026         Width = std::max(ResultVal.getActiveBits(), 1u) +
4027                 (Literal.isUnsigned ? 0u : 1u);
4028 
4029         // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4030         // and reset the type to the largest supported width.
4031         unsigned int MaxBitIntWidth =
4032             Context.getTargetInfo().getMaxBitIntWidth();
4033         if (Width > MaxBitIntWidth) {
4034           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4035               << Literal.isUnsigned;
4036           Width = MaxBitIntWidth;
4037         }
4038 
4039         // Reset the result value to the smaller APInt and select the correct
4040         // type to be used. Note, we zext even for signed values because the
4041         // literal itself is always an unsigned value (a preceeding - is a
4042         // unary operator, not part of the literal).
4043         ResultVal = ResultVal.zextOrTrunc(Width);
4044         Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4045       }
4046 
4047       // Check C++2b size_t literals.
4048       if (Literal.isSizeT) {
4049         assert(!Literal.MicrosoftInteger &&
4050                "size_t literals can't be Microsoft literals");
4051         unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4052             Context.getTargetInfo().getSizeType());
4053 
4054         // Does it fit in size_t?
4055         if (ResultVal.isIntN(SizeTSize)) {
4056           // Does it fit in ssize_t?
4057           if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4058             Ty = Context.getSignedSizeType();
4059           else if (AllowUnsigned)
4060             Ty = Context.getSizeType();
4061           Width = SizeTSize;
4062         }
4063       }
4064 
4065       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4066           !Literal.isSizeT) {
4067         // Are int/unsigned possibilities?
4068         unsigned IntSize = Context.getTargetInfo().getIntWidth();
4069 
4070         // Does it fit in a unsigned int?
4071         if (ResultVal.isIntN(IntSize)) {
4072           // Does it fit in a signed int?
4073           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4074             Ty = Context.IntTy;
4075           else if (AllowUnsigned)
4076             Ty = Context.UnsignedIntTy;
4077           Width = IntSize;
4078         }
4079       }
4080 
4081       // Are long/unsigned long possibilities?
4082       if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4083         unsigned LongSize = Context.getTargetInfo().getLongWidth();
4084 
4085         // Does it fit in a unsigned long?
4086         if (ResultVal.isIntN(LongSize)) {
4087           // Does it fit in a signed long?
4088           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4089             Ty = Context.LongTy;
4090           else if (AllowUnsigned)
4091             Ty = Context.UnsignedLongTy;
4092           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4093           // is compatible.
4094           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4095             const unsigned LongLongSize =
4096                 Context.getTargetInfo().getLongLongWidth();
4097             Diag(Tok.getLocation(),
4098                  getLangOpts().CPlusPlus
4099                      ? Literal.isLong
4100                            ? diag::warn_old_implicitly_unsigned_long_cxx
4101                            : /*C++98 UB*/ diag::
4102                                  ext_old_implicitly_unsigned_long_cxx
4103                      : diag::warn_old_implicitly_unsigned_long)
4104                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4105                                             : /*will be ill-formed*/ 1);
4106             Ty = Context.UnsignedLongTy;
4107           }
4108           Width = LongSize;
4109         }
4110       }
4111 
4112       // Check long long if needed.
4113       if (Ty.isNull() && !Literal.isSizeT) {
4114         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4115 
4116         // Does it fit in a unsigned long long?
4117         if (ResultVal.isIntN(LongLongSize)) {
4118           // Does it fit in a signed long long?
4119           // To be compatible with MSVC, hex integer literals ending with the
4120           // LL or i64 suffix are always signed in Microsoft mode.
4121           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4122               (getLangOpts().MSVCCompat && Literal.isLongLong)))
4123             Ty = Context.LongLongTy;
4124           else if (AllowUnsigned)
4125             Ty = Context.UnsignedLongLongTy;
4126           Width = LongLongSize;
4127         }
4128       }
4129 
4130       // If we still couldn't decide a type, we either have 'size_t' literal
4131       // that is out of range, or a decimal literal that does not fit in a
4132       // signed long long and has no U suffix.
4133       if (Ty.isNull()) {
4134         if (Literal.isSizeT)
4135           Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4136               << Literal.isUnsigned;
4137         else
4138           Diag(Tok.getLocation(),
4139                diag::ext_integer_literal_too_large_for_signed);
4140         Ty = Context.UnsignedLongLongTy;
4141         Width = Context.getTargetInfo().getLongLongWidth();
4142       }
4143 
4144       if (ResultVal.getBitWidth() != Width)
4145         ResultVal = ResultVal.trunc(Width);
4146     }
4147     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4148   }
4149 
4150   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4151   if (Literal.isImaginary) {
4152     Res = new (Context) ImaginaryLiteral(Res,
4153                                         Context.getComplexType(Res->getType()));
4154 
4155     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4156   }
4157   return Res;
4158 }
4159 
4160 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4161   assert(E && "ActOnParenExpr() missing expr");
4162   QualType ExprTy = E->getType();
4163   if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4164       !E->isLValue() && ExprTy->hasFloatingRepresentation())
4165     return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4166   return new (Context) ParenExpr(L, R, E);
4167 }
4168 
4169 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4170                                          SourceLocation Loc,
4171                                          SourceRange ArgRange) {
4172   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4173   // scalar or vector data type argument..."
4174   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4175   // type (C99 6.2.5p18) or void.
4176   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4177     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4178       << T << ArgRange;
4179     return true;
4180   }
4181 
4182   assert((T->isVoidType() || !T->isIncompleteType()) &&
4183          "Scalar types should always be complete");
4184   return false;
4185 }
4186 
4187 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4188                                            SourceLocation Loc,
4189                                            SourceRange ArgRange,
4190                                            UnaryExprOrTypeTrait TraitKind) {
4191   // Invalid types must be hard errors for SFINAE in C++.
4192   if (S.LangOpts.CPlusPlus)
4193     return true;
4194 
4195   // C99 6.5.3.4p1:
4196   if (T->isFunctionType() &&
4197       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4198        TraitKind == UETT_PreferredAlignOf)) {
4199     // sizeof(function)/alignof(function) is allowed as an extension.
4200     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4201         << getTraitSpelling(TraitKind) << ArgRange;
4202     return false;
4203   }
4204 
4205   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4206   // this is an error (OpenCL v1.1 s6.3.k)
4207   if (T->isVoidType()) {
4208     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4209                                         : diag::ext_sizeof_alignof_void_type;
4210     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4211     return false;
4212   }
4213 
4214   return true;
4215 }
4216 
4217 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4218                                              SourceLocation Loc,
4219                                              SourceRange ArgRange,
4220                                              UnaryExprOrTypeTrait TraitKind) {
4221   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4222   // runtime doesn't allow it.
4223   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4224     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4225       << T << (TraitKind == UETT_SizeOf)
4226       << ArgRange;
4227     return true;
4228   }
4229 
4230   return false;
4231 }
4232 
4233 /// Check whether E is a pointer from a decayed array type (the decayed
4234 /// pointer type is equal to T) and emit a warning if it is.
4235 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4236                                      Expr *E) {
4237   // Don't warn if the operation changed the type.
4238   if (T != E->getType())
4239     return;
4240 
4241   // Now look for array decays.
4242   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4243   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4244     return;
4245 
4246   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4247                                              << ICE->getType()
4248                                              << ICE->getSubExpr()->getType();
4249 }
4250 
4251 /// Check the constraints on expression operands to unary type expression
4252 /// and type traits.
4253 ///
4254 /// Completes any types necessary and validates the constraints on the operand
4255 /// expression. The logic mostly mirrors the type-based overload, but may modify
4256 /// the expression as it completes the type for that expression through template
4257 /// instantiation, etc.
4258 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4259                                             UnaryExprOrTypeTrait ExprKind) {
4260   QualType ExprTy = E->getType();
4261   assert(!ExprTy->isReferenceType());
4262 
4263   bool IsUnevaluatedOperand =
4264       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4265        ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4266   if (IsUnevaluatedOperand) {
4267     ExprResult Result = CheckUnevaluatedOperand(E);
4268     if (Result.isInvalid())
4269       return true;
4270     E = Result.get();
4271   }
4272 
4273   // The operand for sizeof and alignof is in an unevaluated expression context,
4274   // so side effects could result in unintended consequences.
4275   // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4276   // used to build SFINAE gadgets.
4277   // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4278   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4279       !E->isInstantiationDependent() &&
4280       !E->getType()->isVariableArrayType() &&
4281       E->HasSideEffects(Context, false))
4282     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4283 
4284   if (ExprKind == UETT_VecStep)
4285     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4286                                         E->getSourceRange());
4287 
4288   // Explicitly list some types as extensions.
4289   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4290                                       E->getSourceRange(), ExprKind))
4291     return false;
4292 
4293   // 'alignof' applied to an expression only requires the base element type of
4294   // the expression to be complete. 'sizeof' requires the expression's type to
4295   // be complete (and will attempt to complete it if it's an array of unknown
4296   // bound).
4297   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4298     if (RequireCompleteSizedType(
4299             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4300             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4301             getTraitSpelling(ExprKind), E->getSourceRange()))
4302       return true;
4303   } else {
4304     if (RequireCompleteSizedExprType(
4305             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4306             getTraitSpelling(ExprKind), E->getSourceRange()))
4307       return true;
4308   }
4309 
4310   // Completing the expression's type may have changed it.
4311   ExprTy = E->getType();
4312   assert(!ExprTy->isReferenceType());
4313 
4314   if (ExprTy->isFunctionType()) {
4315     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4316         << getTraitSpelling(ExprKind) << E->getSourceRange();
4317     return true;
4318   }
4319 
4320   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4321                                        E->getSourceRange(), ExprKind))
4322     return true;
4323 
4324   if (ExprKind == UETT_SizeOf) {
4325     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4326       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4327         QualType OType = PVD->getOriginalType();
4328         QualType Type = PVD->getType();
4329         if (Type->isPointerType() && OType->isArrayType()) {
4330           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4331             << Type << OType;
4332           Diag(PVD->getLocation(), diag::note_declared_at);
4333         }
4334       }
4335     }
4336 
4337     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4338     // decays into a pointer and returns an unintended result. This is most
4339     // likely a typo for "sizeof(array) op x".
4340     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4341       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4342                                BO->getLHS());
4343       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4344                                BO->getRHS());
4345     }
4346   }
4347 
4348   return false;
4349 }
4350 
4351 /// Check the constraints on operands to unary expression and type
4352 /// traits.
4353 ///
4354 /// This will complete any types necessary, and validate the various constraints
4355 /// on those operands.
4356 ///
4357 /// The UsualUnaryConversions() function is *not* called by this routine.
4358 /// C99 6.3.2.1p[2-4] all state:
4359 ///   Except when it is the operand of the sizeof operator ...
4360 ///
4361 /// C++ [expr.sizeof]p4
4362 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4363 ///   standard conversions are not applied to the operand of sizeof.
4364 ///
4365 /// This policy is followed for all of the unary trait expressions.
4366 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4367                                             SourceLocation OpLoc,
4368                                             SourceRange ExprRange,
4369                                             UnaryExprOrTypeTrait ExprKind) {
4370   if (ExprType->isDependentType())
4371     return false;
4372 
4373   // C++ [expr.sizeof]p2:
4374   //     When applied to a reference or a reference type, the result
4375   //     is the size of the referenced type.
4376   // C++11 [expr.alignof]p3:
4377   //     When alignof is applied to a reference type, the result
4378   //     shall be the alignment of the referenced type.
4379   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4380     ExprType = Ref->getPointeeType();
4381 
4382   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4383   //   When alignof or _Alignof is applied to an array type, the result
4384   //   is the alignment of the element type.
4385   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4386       ExprKind == UETT_OpenMPRequiredSimdAlign)
4387     ExprType = Context.getBaseElementType(ExprType);
4388 
4389   if (ExprKind == UETT_VecStep)
4390     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4391 
4392   // Explicitly list some types as extensions.
4393   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4394                                       ExprKind))
4395     return false;
4396 
4397   if (RequireCompleteSizedType(
4398           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4399           getTraitSpelling(ExprKind), ExprRange))
4400     return true;
4401 
4402   if (ExprType->isFunctionType()) {
4403     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4404         << getTraitSpelling(ExprKind) << ExprRange;
4405     return true;
4406   }
4407 
4408   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4409                                        ExprKind))
4410     return true;
4411 
4412   return false;
4413 }
4414 
4415 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4416   // Cannot know anything else if the expression is dependent.
4417   if (E->isTypeDependent())
4418     return false;
4419 
4420   if (E->getObjectKind() == OK_BitField) {
4421     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4422        << 1 << E->getSourceRange();
4423     return true;
4424   }
4425 
4426   ValueDecl *D = nullptr;
4427   Expr *Inner = E->IgnoreParens();
4428   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4429     D = DRE->getDecl();
4430   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4431     D = ME->getMemberDecl();
4432   }
4433 
4434   // If it's a field, require the containing struct to have a
4435   // complete definition so that we can compute the layout.
4436   //
4437   // This can happen in C++11 onwards, either by naming the member
4438   // in a way that is not transformed into a member access expression
4439   // (in an unevaluated operand, for instance), or by naming the member
4440   // in a trailing-return-type.
4441   //
4442   // For the record, since __alignof__ on expressions is a GCC
4443   // extension, GCC seems to permit this but always gives the
4444   // nonsensical answer 0.
4445   //
4446   // We don't really need the layout here --- we could instead just
4447   // directly check for all the appropriate alignment-lowing
4448   // attributes --- but that would require duplicating a lot of
4449   // logic that just isn't worth duplicating for such a marginal
4450   // use-case.
4451   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4452     // Fast path this check, since we at least know the record has a
4453     // definition if we can find a member of it.
4454     if (!FD->getParent()->isCompleteDefinition()) {
4455       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4456         << E->getSourceRange();
4457       return true;
4458     }
4459 
4460     // Otherwise, if it's a field, and the field doesn't have
4461     // reference type, then it must have a complete type (or be a
4462     // flexible array member, which we explicitly want to
4463     // white-list anyway), which makes the following checks trivial.
4464     if (!FD->getType()->isReferenceType())
4465       return false;
4466   }
4467 
4468   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4469 }
4470 
4471 bool Sema::CheckVecStepExpr(Expr *E) {
4472   E = E->IgnoreParens();
4473 
4474   // Cannot know anything else if the expression is dependent.
4475   if (E->isTypeDependent())
4476     return false;
4477 
4478   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4479 }
4480 
4481 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4482                                         CapturingScopeInfo *CSI) {
4483   assert(T->isVariablyModifiedType());
4484   assert(CSI != nullptr);
4485 
4486   // We're going to walk down into the type and look for VLA expressions.
4487   do {
4488     const Type *Ty = T.getTypePtr();
4489     switch (Ty->getTypeClass()) {
4490 #define TYPE(Class, Base)
4491 #define ABSTRACT_TYPE(Class, Base)
4492 #define NON_CANONICAL_TYPE(Class, Base)
4493 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4494 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4495 #include "clang/AST/TypeNodes.inc"
4496       T = QualType();
4497       break;
4498     // These types are never variably-modified.
4499     case Type::Builtin:
4500     case Type::Complex:
4501     case Type::Vector:
4502     case Type::ExtVector:
4503     case Type::ConstantMatrix:
4504     case Type::Record:
4505     case Type::Enum:
4506     case Type::Elaborated:
4507     case Type::TemplateSpecialization:
4508     case Type::ObjCObject:
4509     case Type::ObjCInterface:
4510     case Type::ObjCObjectPointer:
4511     case Type::ObjCTypeParam:
4512     case Type::Pipe:
4513     case Type::BitInt:
4514       llvm_unreachable("type class is never variably-modified!");
4515     case Type::Adjusted:
4516       T = cast<AdjustedType>(Ty)->getOriginalType();
4517       break;
4518     case Type::Decayed:
4519       T = cast<DecayedType>(Ty)->getPointeeType();
4520       break;
4521     case Type::Pointer:
4522       T = cast<PointerType>(Ty)->getPointeeType();
4523       break;
4524     case Type::BlockPointer:
4525       T = cast<BlockPointerType>(Ty)->getPointeeType();
4526       break;
4527     case Type::LValueReference:
4528     case Type::RValueReference:
4529       T = cast<ReferenceType>(Ty)->getPointeeType();
4530       break;
4531     case Type::MemberPointer:
4532       T = cast<MemberPointerType>(Ty)->getPointeeType();
4533       break;
4534     case Type::ConstantArray:
4535     case Type::IncompleteArray:
4536       // Losing element qualification here is fine.
4537       T = cast<ArrayType>(Ty)->getElementType();
4538       break;
4539     case Type::VariableArray: {
4540       // Losing element qualification here is fine.
4541       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4542 
4543       // Unknown size indication requires no size computation.
4544       // Otherwise, evaluate and record it.
4545       auto Size = VAT->getSizeExpr();
4546       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4547           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4548         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4549 
4550       T = VAT->getElementType();
4551       break;
4552     }
4553     case Type::FunctionProto:
4554     case Type::FunctionNoProto:
4555       T = cast<FunctionType>(Ty)->getReturnType();
4556       break;
4557     case Type::Paren:
4558     case Type::TypeOf:
4559     case Type::UnaryTransform:
4560     case Type::Attributed:
4561     case Type::BTFTagAttributed:
4562     case Type::SubstTemplateTypeParm:
4563     case Type::MacroQualified:
4564       // Keep walking after single level desugaring.
4565       T = T.getSingleStepDesugaredType(Context);
4566       break;
4567     case Type::Typedef:
4568       T = cast<TypedefType>(Ty)->desugar();
4569       break;
4570     case Type::Decltype:
4571       T = cast<DecltypeType>(Ty)->desugar();
4572       break;
4573     case Type::Using:
4574       T = cast<UsingType>(Ty)->desugar();
4575       break;
4576     case Type::Auto:
4577     case Type::DeducedTemplateSpecialization:
4578       T = cast<DeducedType>(Ty)->getDeducedType();
4579       break;
4580     case Type::TypeOfExpr:
4581       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4582       break;
4583     case Type::Atomic:
4584       T = cast<AtomicType>(Ty)->getValueType();
4585       break;
4586     }
4587   } while (!T.isNull() && T->isVariablyModifiedType());
4588 }
4589 
4590 /// Build a sizeof or alignof expression given a type operand.
4591 ExprResult
4592 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4593                                      SourceLocation OpLoc,
4594                                      UnaryExprOrTypeTrait ExprKind,
4595                                      SourceRange R) {
4596   if (!TInfo)
4597     return ExprError();
4598 
4599   QualType T = TInfo->getType();
4600 
4601   if (!T->isDependentType() &&
4602       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4603     return ExprError();
4604 
4605   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4606     if (auto *TT = T->getAs<TypedefType>()) {
4607       for (auto I = FunctionScopes.rbegin(),
4608                 E = std::prev(FunctionScopes.rend());
4609            I != E; ++I) {
4610         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4611         if (CSI == nullptr)
4612           break;
4613         DeclContext *DC = nullptr;
4614         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4615           DC = LSI->CallOperator;
4616         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4617           DC = CRSI->TheCapturedDecl;
4618         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4619           DC = BSI->TheDecl;
4620         if (DC) {
4621           if (DC->containsDecl(TT->getDecl()))
4622             break;
4623           captureVariablyModifiedType(Context, T, CSI);
4624         }
4625       }
4626     }
4627   }
4628 
4629   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4630   if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4631       TInfo->getType()->isVariablyModifiedType())
4632     TInfo = TransformToPotentiallyEvaluated(TInfo);
4633 
4634   return new (Context) UnaryExprOrTypeTraitExpr(
4635       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4636 }
4637 
4638 /// Build a sizeof or alignof expression given an expression
4639 /// operand.
4640 ExprResult
4641 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4642                                      UnaryExprOrTypeTrait ExprKind) {
4643   ExprResult PE = CheckPlaceholderExpr(E);
4644   if (PE.isInvalid())
4645     return ExprError();
4646 
4647   E = PE.get();
4648 
4649   // Verify that the operand is valid.
4650   bool isInvalid = false;
4651   if (E->isTypeDependent()) {
4652     // Delay type-checking for type-dependent expressions.
4653   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4654     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4655   } else if (ExprKind == UETT_VecStep) {
4656     isInvalid = CheckVecStepExpr(E);
4657   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4658       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4659       isInvalid = true;
4660   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4661     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4662     isInvalid = true;
4663   } else {
4664     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4665   }
4666 
4667   if (isInvalid)
4668     return ExprError();
4669 
4670   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4671     PE = TransformToPotentiallyEvaluated(E);
4672     if (PE.isInvalid()) return ExprError();
4673     E = PE.get();
4674   }
4675 
4676   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4677   return new (Context) UnaryExprOrTypeTraitExpr(
4678       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4679 }
4680 
4681 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4682 /// expr and the same for @c alignof and @c __alignof
4683 /// Note that the ArgRange is invalid if isType is false.
4684 ExprResult
4685 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4686                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4687                                     void *TyOrEx, SourceRange ArgRange) {
4688   // If error parsing type, ignore.
4689   if (!TyOrEx) return ExprError();
4690 
4691   if (IsType) {
4692     TypeSourceInfo *TInfo;
4693     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4694     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4695   }
4696 
4697   Expr *ArgEx = (Expr *)TyOrEx;
4698   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4699   return Result;
4700 }
4701 
4702 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4703                                      bool IsReal) {
4704   if (V.get()->isTypeDependent())
4705     return S.Context.DependentTy;
4706 
4707   // _Real and _Imag are only l-values for normal l-values.
4708   if (V.get()->getObjectKind() != OK_Ordinary) {
4709     V = S.DefaultLvalueConversion(V.get());
4710     if (V.isInvalid())
4711       return QualType();
4712   }
4713 
4714   // These operators return the element type of a complex type.
4715   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4716     return CT->getElementType();
4717 
4718   // Otherwise they pass through real integer and floating point types here.
4719   if (V.get()->getType()->isArithmeticType())
4720     return V.get()->getType();
4721 
4722   // Test for placeholders.
4723   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4724   if (PR.isInvalid()) return QualType();
4725   if (PR.get() != V.get()) {
4726     V = PR;
4727     return CheckRealImagOperand(S, V, Loc, IsReal);
4728   }
4729 
4730   // Reject anything else.
4731   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4732     << (IsReal ? "__real" : "__imag");
4733   return QualType();
4734 }
4735 
4736 
4737 
4738 ExprResult
4739 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4740                           tok::TokenKind Kind, Expr *Input) {
4741   UnaryOperatorKind Opc;
4742   switch (Kind) {
4743   default: llvm_unreachable("Unknown unary op!");
4744   case tok::plusplus:   Opc = UO_PostInc; break;
4745   case tok::minusminus: Opc = UO_PostDec; break;
4746   }
4747 
4748   // Since this might is a postfix expression, get rid of ParenListExprs.
4749   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4750   if (Result.isInvalid()) return ExprError();
4751   Input = Result.get();
4752 
4753   return BuildUnaryOp(S, OpLoc, Opc, Input);
4754 }
4755 
4756 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4757 ///
4758 /// \return true on error
4759 static bool checkArithmeticOnObjCPointer(Sema &S,
4760                                          SourceLocation opLoc,
4761                                          Expr *op) {
4762   assert(op->getType()->isObjCObjectPointerType());
4763   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4764       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4765     return false;
4766 
4767   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4768     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4769     << op->getSourceRange();
4770   return true;
4771 }
4772 
4773 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4774   auto *BaseNoParens = Base->IgnoreParens();
4775   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4776     return MSProp->getPropertyDecl()->getType()->isArrayType();
4777   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4778 }
4779 
4780 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4781 // Typically this is DependentTy, but can sometimes be more precise.
4782 //
4783 // There are cases when we could determine a non-dependent type:
4784 //  - LHS and RHS may have non-dependent types despite being type-dependent
4785 //    (e.g. unbounded array static members of the current instantiation)
4786 //  - one may be a dependent-sized array with known element type
4787 //  - one may be a dependent-typed valid index (enum in current instantiation)
4788 //
4789 // We *always* return a dependent type, in such cases it is DependentTy.
4790 // This avoids creating type-dependent expressions with non-dependent types.
4791 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4792 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4793                                                const ASTContext &Ctx) {
4794   assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4795   QualType LTy = LHS->getType(), RTy = RHS->getType();
4796   QualType Result = Ctx.DependentTy;
4797   if (RTy->isIntegralOrUnscopedEnumerationType()) {
4798     if (const PointerType *PT = LTy->getAs<PointerType>())
4799       Result = PT->getPointeeType();
4800     else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4801       Result = AT->getElementType();
4802   } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4803     if (const PointerType *PT = RTy->getAs<PointerType>())
4804       Result = PT->getPointeeType();
4805     else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4806       Result = AT->getElementType();
4807   }
4808   // Ensure we return a dependent type.
4809   return Result->isDependentType() ? Result : Ctx.DependentTy;
4810 }
4811 
4812 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4813 
4814 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4815                                          SourceLocation lbLoc,
4816                                          MultiExprArg ArgExprs,
4817                                          SourceLocation rbLoc) {
4818 
4819   if (base && !base->getType().isNull() &&
4820       base->hasPlaceholderType(BuiltinType::OMPArraySection))
4821     return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4822                                     SourceLocation(), /*Length*/ nullptr,
4823                                     /*Stride=*/nullptr, rbLoc);
4824 
4825   // Since this might be a postfix expression, get rid of ParenListExprs.
4826   if (isa<ParenListExpr>(base)) {
4827     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4828     if (result.isInvalid())
4829       return ExprError();
4830     base = result.get();
4831   }
4832 
4833   // Check if base and idx form a MatrixSubscriptExpr.
4834   //
4835   // Helper to check for comma expressions, which are not allowed as indices for
4836   // matrix subscript expressions.
4837   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4838     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4839       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4840           << SourceRange(base->getBeginLoc(), rbLoc);
4841       return true;
4842     }
4843     return false;
4844   };
4845   // The matrix subscript operator ([][])is considered a single operator.
4846   // Separating the index expressions by parenthesis is not allowed.
4847   if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4848       !isa<MatrixSubscriptExpr>(base)) {
4849     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4850         << SourceRange(base->getBeginLoc(), rbLoc);
4851     return ExprError();
4852   }
4853   // If the base is a MatrixSubscriptExpr, try to create a new
4854   // MatrixSubscriptExpr.
4855   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4856   if (matSubscriptE) {
4857     assert(ArgExprs.size() == 1);
4858     if (CheckAndReportCommaError(ArgExprs.front()))
4859       return ExprError();
4860 
4861     assert(matSubscriptE->isIncomplete() &&
4862            "base has to be an incomplete matrix subscript");
4863     return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4864                                             matSubscriptE->getRowIdx(),
4865                                             ArgExprs.front(), rbLoc);
4866   }
4867 
4868   // Handle any non-overload placeholder types in the base and index
4869   // expressions.  We can't handle overloads here because the other
4870   // operand might be an overloadable type, in which case the overload
4871   // resolution for the operator overload should get the first crack
4872   // at the overload.
4873   bool IsMSPropertySubscript = false;
4874   if (base->getType()->isNonOverloadPlaceholderType()) {
4875     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4876     if (!IsMSPropertySubscript) {
4877       ExprResult result = CheckPlaceholderExpr(base);
4878       if (result.isInvalid())
4879         return ExprError();
4880       base = result.get();
4881     }
4882   }
4883 
4884   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4885   if (base->getType()->isMatrixType()) {
4886     assert(ArgExprs.size() == 1);
4887     if (CheckAndReportCommaError(ArgExprs.front()))
4888       return ExprError();
4889 
4890     return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4891                                             rbLoc);
4892   }
4893 
4894   if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4895     Expr *idx = ArgExprs[0];
4896     if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4897         (isa<CXXOperatorCallExpr>(idx) &&
4898          cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4899       Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4900           << SourceRange(base->getBeginLoc(), rbLoc);
4901     }
4902   }
4903 
4904   if (ArgExprs.size() == 1 &&
4905       ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4906     ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4907     if (result.isInvalid())
4908       return ExprError();
4909     ArgExprs[0] = result.get();
4910   } else {
4911     if (checkArgsForPlaceholders(*this, ArgExprs))
4912       return ExprError();
4913   }
4914 
4915   // Build an unanalyzed expression if either operand is type-dependent.
4916   if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4917       (base->isTypeDependent() ||
4918        Expr::hasAnyTypeDependentArguments(ArgExprs))) {
4919     return new (Context) ArraySubscriptExpr(
4920         base, ArgExprs.front(),
4921         getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4922         VK_LValue, OK_Ordinary, rbLoc);
4923   }
4924 
4925   // MSDN, property (C++)
4926   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4927   // This attribute can also be used in the declaration of an empty array in a
4928   // class or structure definition. For example:
4929   // __declspec(property(get=GetX, put=PutX)) int x[];
4930   // The above statement indicates that x[] can be used with one or more array
4931   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4932   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4933   if (IsMSPropertySubscript) {
4934     assert(ArgExprs.size() == 1);
4935     // Build MS property subscript expression if base is MS property reference
4936     // or MS property subscript.
4937     return new (Context)
4938         MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4939                                 VK_LValue, OK_Ordinary, rbLoc);
4940   }
4941 
4942   // Use C++ overloaded-operator rules if either operand has record
4943   // type.  The spec says to do this if either type is *overloadable*,
4944   // but enum types can't declare subscript operators or conversion
4945   // operators, so there's nothing interesting for overload resolution
4946   // to do if there aren't any record types involved.
4947   //
4948   // ObjC pointers have their own subscripting logic that is not tied
4949   // to overload resolution and so should not take this path.
4950   if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4951       ((base->getType()->isRecordType() ||
4952         (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) {
4953     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4954   }
4955 
4956   ExprResult Res =
4957       CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4958 
4959   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4960     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4961 
4962   return Res;
4963 }
4964 
4965 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4966   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4967   InitializationKind Kind =
4968       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4969   InitializationSequence InitSeq(*this, Entity, Kind, E);
4970   return InitSeq.Perform(*this, Entity, Kind, E);
4971 }
4972 
4973 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4974                                                   Expr *ColumnIdx,
4975                                                   SourceLocation RBLoc) {
4976   ExprResult BaseR = CheckPlaceholderExpr(Base);
4977   if (BaseR.isInvalid())
4978     return BaseR;
4979   Base = BaseR.get();
4980 
4981   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4982   if (RowR.isInvalid())
4983     return RowR;
4984   RowIdx = RowR.get();
4985 
4986   if (!ColumnIdx)
4987     return new (Context) MatrixSubscriptExpr(
4988         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4989 
4990   // Build an unanalyzed expression if any of the operands is type-dependent.
4991   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4992       ColumnIdx->isTypeDependent())
4993     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4994                                              Context.DependentTy, RBLoc);
4995 
4996   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4997   if (ColumnR.isInvalid())
4998     return ColumnR;
4999   ColumnIdx = ColumnR.get();
5000 
5001   // Check that IndexExpr is an integer expression. If it is a constant
5002   // expression, check that it is less than Dim (= the number of elements in the
5003   // corresponding dimension).
5004   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5005                           bool IsColumnIdx) -> Expr * {
5006     if (!IndexExpr->getType()->isIntegerType() &&
5007         !IndexExpr->isTypeDependent()) {
5008       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5009           << IsColumnIdx;
5010       return nullptr;
5011     }
5012 
5013     if (Optional<llvm::APSInt> Idx =
5014             IndexExpr->getIntegerConstantExpr(Context)) {
5015       if ((*Idx < 0 || *Idx >= Dim)) {
5016         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5017             << IsColumnIdx << Dim;
5018         return nullptr;
5019       }
5020     }
5021 
5022     ExprResult ConvExpr =
5023         tryConvertExprToType(IndexExpr, Context.getSizeType());
5024     assert(!ConvExpr.isInvalid() &&
5025            "should be able to convert any integer type to size type");
5026     return ConvExpr.get();
5027   };
5028 
5029   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5030   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5031   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5032   if (!RowIdx || !ColumnIdx)
5033     return ExprError();
5034 
5035   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5036                                            MTy->getElementType(), RBLoc);
5037 }
5038 
5039 void Sema::CheckAddressOfNoDeref(const Expr *E) {
5040   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5041   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5042 
5043   // For expressions like `&(*s).b`, the base is recorded and what should be
5044   // checked.
5045   const MemberExpr *Member = nullptr;
5046   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5047     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5048 
5049   LastRecord.PossibleDerefs.erase(StrippedExpr);
5050 }
5051 
5052 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5053   if (isUnevaluatedContext())
5054     return;
5055 
5056   QualType ResultTy = E->getType();
5057   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5058 
5059   // Bail if the element is an array since it is not memory access.
5060   if (isa<ArrayType>(ResultTy))
5061     return;
5062 
5063   if (ResultTy->hasAttr(attr::NoDeref)) {
5064     LastRecord.PossibleDerefs.insert(E);
5065     return;
5066   }
5067 
5068   // Check if the base type is a pointer to a member access of a struct
5069   // marked with noderef.
5070   const Expr *Base = E->getBase();
5071   QualType BaseTy = Base->getType();
5072   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5073     // Not a pointer access
5074     return;
5075 
5076   const MemberExpr *Member = nullptr;
5077   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5078          Member->isArrow())
5079     Base = Member->getBase();
5080 
5081   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5082     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5083       LastRecord.PossibleDerefs.insert(E);
5084   }
5085 }
5086 
5087 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5088                                           Expr *LowerBound,
5089                                           SourceLocation ColonLocFirst,
5090                                           SourceLocation ColonLocSecond,
5091                                           Expr *Length, Expr *Stride,
5092                                           SourceLocation RBLoc) {
5093   if (Base->hasPlaceholderType() &&
5094       !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5095     ExprResult Result = CheckPlaceholderExpr(Base);
5096     if (Result.isInvalid())
5097       return ExprError();
5098     Base = Result.get();
5099   }
5100   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5101     ExprResult Result = CheckPlaceholderExpr(LowerBound);
5102     if (Result.isInvalid())
5103       return ExprError();
5104     Result = DefaultLvalueConversion(Result.get());
5105     if (Result.isInvalid())
5106       return ExprError();
5107     LowerBound = Result.get();
5108   }
5109   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5110     ExprResult Result = CheckPlaceholderExpr(Length);
5111     if (Result.isInvalid())
5112       return ExprError();
5113     Result = DefaultLvalueConversion(Result.get());
5114     if (Result.isInvalid())
5115       return ExprError();
5116     Length = Result.get();
5117   }
5118   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5119     ExprResult Result = CheckPlaceholderExpr(Stride);
5120     if (Result.isInvalid())
5121       return ExprError();
5122     Result = DefaultLvalueConversion(Result.get());
5123     if (Result.isInvalid())
5124       return ExprError();
5125     Stride = Result.get();
5126   }
5127 
5128   // Build an unanalyzed expression if either operand is type-dependent.
5129   if (Base->isTypeDependent() ||
5130       (LowerBound &&
5131        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5132       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5133       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5134     return new (Context) OMPArraySectionExpr(
5135         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5136         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5137   }
5138 
5139   // Perform default conversions.
5140   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5141   QualType ResultTy;
5142   if (OriginalTy->isAnyPointerType()) {
5143     ResultTy = OriginalTy->getPointeeType();
5144   } else if (OriginalTy->isArrayType()) {
5145     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5146   } else {
5147     return ExprError(
5148         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5149         << Base->getSourceRange());
5150   }
5151   // C99 6.5.2.1p1
5152   if (LowerBound) {
5153     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5154                                                       LowerBound);
5155     if (Res.isInvalid())
5156       return ExprError(Diag(LowerBound->getExprLoc(),
5157                             diag::err_omp_typecheck_section_not_integer)
5158                        << 0 << LowerBound->getSourceRange());
5159     LowerBound = Res.get();
5160 
5161     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5162         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5163       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5164           << 0 << LowerBound->getSourceRange();
5165   }
5166   if (Length) {
5167     auto Res =
5168         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5169     if (Res.isInvalid())
5170       return ExprError(Diag(Length->getExprLoc(),
5171                             diag::err_omp_typecheck_section_not_integer)
5172                        << 1 << Length->getSourceRange());
5173     Length = Res.get();
5174 
5175     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5176         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5177       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5178           << 1 << Length->getSourceRange();
5179   }
5180   if (Stride) {
5181     ExprResult Res =
5182         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5183     if (Res.isInvalid())
5184       return ExprError(Diag(Stride->getExprLoc(),
5185                             diag::err_omp_typecheck_section_not_integer)
5186                        << 1 << Stride->getSourceRange());
5187     Stride = Res.get();
5188 
5189     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5190         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5191       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5192           << 1 << Stride->getSourceRange();
5193   }
5194 
5195   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5196   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5197   // type. Note that functions are not objects, and that (in C99 parlance)
5198   // incomplete types are not object types.
5199   if (ResultTy->isFunctionType()) {
5200     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5201         << ResultTy << Base->getSourceRange();
5202     return ExprError();
5203   }
5204 
5205   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5206                           diag::err_omp_section_incomplete_type, Base))
5207     return ExprError();
5208 
5209   if (LowerBound && !OriginalTy->isAnyPointerType()) {
5210     Expr::EvalResult Result;
5211     if (LowerBound->EvaluateAsInt(Result, Context)) {
5212       // OpenMP 5.0, [2.1.5 Array Sections]
5213       // The array section must be a subset of the original array.
5214       llvm::APSInt LowerBoundValue = Result.Val.getInt();
5215       if (LowerBoundValue.isNegative()) {
5216         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5217             << LowerBound->getSourceRange();
5218         return ExprError();
5219       }
5220     }
5221   }
5222 
5223   if (Length) {
5224     Expr::EvalResult Result;
5225     if (Length->EvaluateAsInt(Result, Context)) {
5226       // OpenMP 5.0, [2.1.5 Array Sections]
5227       // The length must evaluate to non-negative integers.
5228       llvm::APSInt LengthValue = Result.Val.getInt();
5229       if (LengthValue.isNegative()) {
5230         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5231             << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5232             << Length->getSourceRange();
5233         return ExprError();
5234       }
5235     }
5236   } else if (ColonLocFirst.isValid() &&
5237              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5238                                       !OriginalTy->isVariableArrayType()))) {
5239     // OpenMP 5.0, [2.1.5 Array Sections]
5240     // When the size of the array dimension is not known, the length must be
5241     // specified explicitly.
5242     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5243         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5244     return ExprError();
5245   }
5246 
5247   if (Stride) {
5248     Expr::EvalResult Result;
5249     if (Stride->EvaluateAsInt(Result, Context)) {
5250       // OpenMP 5.0, [2.1.5 Array Sections]
5251       // The stride must evaluate to a positive integer.
5252       llvm::APSInt StrideValue = Result.Val.getInt();
5253       if (!StrideValue.isStrictlyPositive()) {
5254         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5255             << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5256             << Stride->getSourceRange();
5257         return ExprError();
5258       }
5259     }
5260   }
5261 
5262   if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5263     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5264     if (Result.isInvalid())
5265       return ExprError();
5266     Base = Result.get();
5267   }
5268   return new (Context) OMPArraySectionExpr(
5269       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5270       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5271 }
5272 
5273 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5274                                           SourceLocation RParenLoc,
5275                                           ArrayRef<Expr *> Dims,
5276                                           ArrayRef<SourceRange> Brackets) {
5277   if (Base->hasPlaceholderType()) {
5278     ExprResult Result = CheckPlaceholderExpr(Base);
5279     if (Result.isInvalid())
5280       return ExprError();
5281     Result = DefaultLvalueConversion(Result.get());
5282     if (Result.isInvalid())
5283       return ExprError();
5284     Base = Result.get();
5285   }
5286   QualType BaseTy = Base->getType();
5287   // Delay analysis of the types/expressions if instantiation/specialization is
5288   // required.
5289   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5290     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5291                                        LParenLoc, RParenLoc, Dims, Brackets);
5292   if (!BaseTy->isPointerType() ||
5293       (!Base->isTypeDependent() &&
5294        BaseTy->getPointeeType()->isIncompleteType()))
5295     return ExprError(Diag(Base->getExprLoc(),
5296                           diag::err_omp_non_pointer_type_array_shaping_base)
5297                      << Base->getSourceRange());
5298 
5299   SmallVector<Expr *, 4> NewDims;
5300   bool ErrorFound = false;
5301   for (Expr *Dim : Dims) {
5302     if (Dim->hasPlaceholderType()) {
5303       ExprResult Result = CheckPlaceholderExpr(Dim);
5304       if (Result.isInvalid()) {
5305         ErrorFound = true;
5306         continue;
5307       }
5308       Result = DefaultLvalueConversion(Result.get());
5309       if (Result.isInvalid()) {
5310         ErrorFound = true;
5311         continue;
5312       }
5313       Dim = Result.get();
5314     }
5315     if (!Dim->isTypeDependent()) {
5316       ExprResult Result =
5317           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5318       if (Result.isInvalid()) {
5319         ErrorFound = true;
5320         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5321             << Dim->getSourceRange();
5322         continue;
5323       }
5324       Dim = Result.get();
5325       Expr::EvalResult EvResult;
5326       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5327         // OpenMP 5.0, [2.1.4 Array Shaping]
5328         // Each si is an integral type expression that must evaluate to a
5329         // positive integer.
5330         llvm::APSInt Value = EvResult.Val.getInt();
5331         if (!Value.isStrictlyPositive()) {
5332           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5333               << toString(Value, /*Radix=*/10, /*Signed=*/true)
5334               << Dim->getSourceRange();
5335           ErrorFound = true;
5336           continue;
5337         }
5338       }
5339     }
5340     NewDims.push_back(Dim);
5341   }
5342   if (ErrorFound)
5343     return ExprError();
5344   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5345                                      LParenLoc, RParenLoc, NewDims, Brackets);
5346 }
5347 
5348 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5349                                       SourceLocation LLoc, SourceLocation RLoc,
5350                                       ArrayRef<OMPIteratorData> Data) {
5351   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5352   bool IsCorrect = true;
5353   for (const OMPIteratorData &D : Data) {
5354     TypeSourceInfo *TInfo = nullptr;
5355     SourceLocation StartLoc;
5356     QualType DeclTy;
5357     if (!D.Type.getAsOpaquePtr()) {
5358       // OpenMP 5.0, 2.1.6 Iterators
5359       // In an iterator-specifier, if the iterator-type is not specified then
5360       // the type of that iterator is of int type.
5361       DeclTy = Context.IntTy;
5362       StartLoc = D.DeclIdentLoc;
5363     } else {
5364       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5365       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5366     }
5367 
5368     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5369                              DeclTy->containsUnexpandedParameterPack() ||
5370                              DeclTy->isInstantiationDependentType();
5371     if (!IsDeclTyDependent) {
5372       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5373         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5374         // The iterator-type must be an integral or pointer type.
5375         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5376             << DeclTy;
5377         IsCorrect = false;
5378         continue;
5379       }
5380       if (DeclTy.isConstant(Context)) {
5381         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5382         // The iterator-type must not be const qualified.
5383         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5384             << DeclTy;
5385         IsCorrect = false;
5386         continue;
5387       }
5388     }
5389 
5390     // Iterator declaration.
5391     assert(D.DeclIdent && "Identifier expected.");
5392     // Always try to create iterator declarator to avoid extra error messages
5393     // about unknown declarations use.
5394     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5395                                D.DeclIdent, DeclTy, TInfo, SC_None);
5396     VD->setImplicit();
5397     if (S) {
5398       // Check for conflicting previous declaration.
5399       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5400       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5401                             ForVisibleRedeclaration);
5402       Previous.suppressDiagnostics();
5403       LookupName(Previous, S);
5404 
5405       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5406                            /*AllowInlineNamespace=*/false);
5407       if (!Previous.empty()) {
5408         NamedDecl *Old = Previous.getRepresentativeDecl();
5409         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5410         Diag(Old->getLocation(), diag::note_previous_definition);
5411       } else {
5412         PushOnScopeChains(VD, S);
5413       }
5414     } else {
5415       CurContext->addDecl(VD);
5416     }
5417     Expr *Begin = D.Range.Begin;
5418     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5419       ExprResult BeginRes =
5420           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5421       Begin = BeginRes.get();
5422     }
5423     Expr *End = D.Range.End;
5424     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5425       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5426       End = EndRes.get();
5427     }
5428     Expr *Step = D.Range.Step;
5429     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5430       if (!Step->getType()->isIntegralType(Context)) {
5431         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5432             << Step << Step->getSourceRange();
5433         IsCorrect = false;
5434         continue;
5435       }
5436       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5437       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5438       // If the step expression of a range-specification equals zero, the
5439       // behavior is unspecified.
5440       if (Result && Result->isZero()) {
5441         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5442             << Step << Step->getSourceRange();
5443         IsCorrect = false;
5444         continue;
5445       }
5446     }
5447     if (!Begin || !End || !IsCorrect) {
5448       IsCorrect = false;
5449       continue;
5450     }
5451     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5452     IDElem.IteratorDecl = VD;
5453     IDElem.AssignmentLoc = D.AssignLoc;
5454     IDElem.Range.Begin = Begin;
5455     IDElem.Range.End = End;
5456     IDElem.Range.Step = Step;
5457     IDElem.ColonLoc = D.ColonLoc;
5458     IDElem.SecondColonLoc = D.SecColonLoc;
5459   }
5460   if (!IsCorrect) {
5461     // Invalidate all created iterator declarations if error is found.
5462     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5463       if (Decl *ID = D.IteratorDecl)
5464         ID->setInvalidDecl();
5465     }
5466     return ExprError();
5467   }
5468   SmallVector<OMPIteratorHelperData, 4> Helpers;
5469   if (!CurContext->isDependentContext()) {
5470     // Build number of ityeration for each iteration range.
5471     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5472     // ((Begini-Stepi-1-Endi) / -Stepi);
5473     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5474       // (Endi - Begini)
5475       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5476                                           D.Range.Begin);
5477       if(!Res.isUsable()) {
5478         IsCorrect = false;
5479         continue;
5480       }
5481       ExprResult St, St1;
5482       if (D.Range.Step) {
5483         St = D.Range.Step;
5484         // (Endi - Begini) + Stepi
5485         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5486         if (!Res.isUsable()) {
5487           IsCorrect = false;
5488           continue;
5489         }
5490         // (Endi - Begini) + Stepi - 1
5491         Res =
5492             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5493                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5494         if (!Res.isUsable()) {
5495           IsCorrect = false;
5496           continue;
5497         }
5498         // ((Endi - Begini) + Stepi - 1) / Stepi
5499         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5500         if (!Res.isUsable()) {
5501           IsCorrect = false;
5502           continue;
5503         }
5504         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5505         // (Begini - Endi)
5506         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5507                                              D.Range.Begin, D.Range.End);
5508         if (!Res1.isUsable()) {
5509           IsCorrect = false;
5510           continue;
5511         }
5512         // (Begini - Endi) - Stepi
5513         Res1 =
5514             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5515         if (!Res1.isUsable()) {
5516           IsCorrect = false;
5517           continue;
5518         }
5519         // (Begini - Endi) - Stepi - 1
5520         Res1 =
5521             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5522                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5523         if (!Res1.isUsable()) {
5524           IsCorrect = false;
5525           continue;
5526         }
5527         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5528         Res1 =
5529             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5530         if (!Res1.isUsable()) {
5531           IsCorrect = false;
5532           continue;
5533         }
5534         // Stepi > 0.
5535         ExprResult CmpRes =
5536             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5537                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5538         if (!CmpRes.isUsable()) {
5539           IsCorrect = false;
5540           continue;
5541         }
5542         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5543                                  Res.get(), Res1.get());
5544         if (!Res.isUsable()) {
5545           IsCorrect = false;
5546           continue;
5547         }
5548       }
5549       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5550       if (!Res.isUsable()) {
5551         IsCorrect = false;
5552         continue;
5553       }
5554 
5555       // Build counter update.
5556       // Build counter.
5557       auto *CounterVD =
5558           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5559                           D.IteratorDecl->getBeginLoc(), nullptr,
5560                           Res.get()->getType(), nullptr, SC_None);
5561       CounterVD->setImplicit();
5562       ExprResult RefRes =
5563           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5564                            D.IteratorDecl->getBeginLoc());
5565       // Build counter update.
5566       // I = Begini + counter * Stepi;
5567       ExprResult UpdateRes;
5568       if (D.Range.Step) {
5569         UpdateRes = CreateBuiltinBinOp(
5570             D.AssignmentLoc, BO_Mul,
5571             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5572       } else {
5573         UpdateRes = DefaultLvalueConversion(RefRes.get());
5574       }
5575       if (!UpdateRes.isUsable()) {
5576         IsCorrect = false;
5577         continue;
5578       }
5579       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5580                                      UpdateRes.get());
5581       if (!UpdateRes.isUsable()) {
5582         IsCorrect = false;
5583         continue;
5584       }
5585       ExprResult VDRes =
5586           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5587                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5588                            D.IteratorDecl->getBeginLoc());
5589       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5590                                      UpdateRes.get());
5591       if (!UpdateRes.isUsable()) {
5592         IsCorrect = false;
5593         continue;
5594       }
5595       UpdateRes =
5596           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5597       if (!UpdateRes.isUsable()) {
5598         IsCorrect = false;
5599         continue;
5600       }
5601       ExprResult CounterUpdateRes =
5602           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5603       if (!CounterUpdateRes.isUsable()) {
5604         IsCorrect = false;
5605         continue;
5606       }
5607       CounterUpdateRes =
5608           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5609       if (!CounterUpdateRes.isUsable()) {
5610         IsCorrect = false;
5611         continue;
5612       }
5613       OMPIteratorHelperData &HD = Helpers.emplace_back();
5614       HD.CounterVD = CounterVD;
5615       HD.Upper = Res.get();
5616       HD.Update = UpdateRes.get();
5617       HD.CounterUpdate = CounterUpdateRes.get();
5618     }
5619   } else {
5620     Helpers.assign(ID.size(), {});
5621   }
5622   if (!IsCorrect) {
5623     // Invalidate all created iterator declarations if error is found.
5624     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5625       if (Decl *ID = D.IteratorDecl)
5626         ID->setInvalidDecl();
5627     }
5628     return ExprError();
5629   }
5630   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5631                                  LLoc, RLoc, ID, Helpers);
5632 }
5633 
5634 ExprResult
5635 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5636                                       Expr *Idx, SourceLocation RLoc) {
5637   Expr *LHSExp = Base;
5638   Expr *RHSExp = Idx;
5639 
5640   ExprValueKind VK = VK_LValue;
5641   ExprObjectKind OK = OK_Ordinary;
5642 
5643   // Per C++ core issue 1213, the result is an xvalue if either operand is
5644   // a non-lvalue array, and an lvalue otherwise.
5645   if (getLangOpts().CPlusPlus11) {
5646     for (auto *Op : {LHSExp, RHSExp}) {
5647       Op = Op->IgnoreImplicit();
5648       if (Op->getType()->isArrayType() && !Op->isLValue())
5649         VK = VK_XValue;
5650     }
5651   }
5652 
5653   // Perform default conversions.
5654   if (!LHSExp->getType()->getAs<VectorType>()) {
5655     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5656     if (Result.isInvalid())
5657       return ExprError();
5658     LHSExp = Result.get();
5659   }
5660   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5661   if (Result.isInvalid())
5662     return ExprError();
5663   RHSExp = Result.get();
5664 
5665   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5666 
5667   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5668   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5669   // in the subscript position. As a result, we need to derive the array base
5670   // and index from the expression types.
5671   Expr *BaseExpr, *IndexExpr;
5672   QualType ResultType;
5673   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5674     BaseExpr = LHSExp;
5675     IndexExpr = RHSExp;
5676     ResultType =
5677         getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5678   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5679     BaseExpr = LHSExp;
5680     IndexExpr = RHSExp;
5681     ResultType = PTy->getPointeeType();
5682   } else if (const ObjCObjectPointerType *PTy =
5683                LHSTy->getAs<ObjCObjectPointerType>()) {
5684     BaseExpr = LHSExp;
5685     IndexExpr = RHSExp;
5686 
5687     // Use custom logic if this should be the pseudo-object subscript
5688     // expression.
5689     if (!LangOpts.isSubscriptPointerArithmetic())
5690       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5691                                           nullptr);
5692 
5693     ResultType = PTy->getPointeeType();
5694   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5695      // Handle the uncommon case of "123[Ptr]".
5696     BaseExpr = RHSExp;
5697     IndexExpr = LHSExp;
5698     ResultType = PTy->getPointeeType();
5699   } else if (const ObjCObjectPointerType *PTy =
5700                RHSTy->getAs<ObjCObjectPointerType>()) {
5701      // Handle the uncommon case of "123[Ptr]".
5702     BaseExpr = RHSExp;
5703     IndexExpr = LHSExp;
5704     ResultType = PTy->getPointeeType();
5705     if (!LangOpts.isSubscriptPointerArithmetic()) {
5706       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5707         << ResultType << BaseExpr->getSourceRange();
5708       return ExprError();
5709     }
5710   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5711     BaseExpr = LHSExp;    // vectors: V[123]
5712     IndexExpr = RHSExp;
5713     // We apply C++ DR1213 to vector subscripting too.
5714     if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5715       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5716       if (Materialized.isInvalid())
5717         return ExprError();
5718       LHSExp = Materialized.get();
5719     }
5720     VK = LHSExp->getValueKind();
5721     if (VK != VK_PRValue)
5722       OK = OK_VectorComponent;
5723 
5724     ResultType = VTy->getElementType();
5725     QualType BaseType = BaseExpr->getType();
5726     Qualifiers BaseQuals = BaseType.getQualifiers();
5727     Qualifiers MemberQuals = ResultType.getQualifiers();
5728     Qualifiers Combined = BaseQuals + MemberQuals;
5729     if (Combined != MemberQuals)
5730       ResultType = Context.getQualifiedType(ResultType, Combined);
5731   } else if (LHSTy->isBuiltinType() &&
5732              LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) {
5733     const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5734     if (BTy->isSVEBool())
5735       return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5736                        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5737 
5738     BaseExpr = LHSExp;
5739     IndexExpr = RHSExp;
5740     if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5741       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5742       if (Materialized.isInvalid())
5743         return ExprError();
5744       LHSExp = Materialized.get();
5745     }
5746     VK = LHSExp->getValueKind();
5747     if (VK != VK_PRValue)
5748       OK = OK_VectorComponent;
5749 
5750     ResultType = BTy->getSveEltType(Context);
5751 
5752     QualType BaseType = BaseExpr->getType();
5753     Qualifiers BaseQuals = BaseType.getQualifiers();
5754     Qualifiers MemberQuals = ResultType.getQualifiers();
5755     Qualifiers Combined = BaseQuals + MemberQuals;
5756     if (Combined != MemberQuals)
5757       ResultType = Context.getQualifiedType(ResultType, Combined);
5758   } else if (LHSTy->isArrayType()) {
5759     // If we see an array that wasn't promoted by
5760     // DefaultFunctionArrayLvalueConversion, it must be an array that
5761     // wasn't promoted because of the C90 rule that doesn't
5762     // allow promoting non-lvalue arrays.  Warn, then
5763     // force the promotion here.
5764     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5765         << LHSExp->getSourceRange();
5766     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5767                                CK_ArrayToPointerDecay).get();
5768     LHSTy = LHSExp->getType();
5769 
5770     BaseExpr = LHSExp;
5771     IndexExpr = RHSExp;
5772     ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5773   } else if (RHSTy->isArrayType()) {
5774     // Same as previous, except for 123[f().a] case
5775     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5776         << RHSExp->getSourceRange();
5777     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5778                                CK_ArrayToPointerDecay).get();
5779     RHSTy = RHSExp->getType();
5780 
5781     BaseExpr = RHSExp;
5782     IndexExpr = LHSExp;
5783     ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5784   } else {
5785     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5786        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5787   }
5788   // C99 6.5.2.1p1
5789   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5790     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5791                      << IndexExpr->getSourceRange());
5792 
5793   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5794        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5795          && !IndexExpr->isTypeDependent())
5796     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5797 
5798   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5799   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5800   // type. Note that Functions are not objects, and that (in C99 parlance)
5801   // incomplete types are not object types.
5802   if (ResultType->isFunctionType()) {
5803     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5804         << ResultType << BaseExpr->getSourceRange();
5805     return ExprError();
5806   }
5807 
5808   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5809     // GNU extension: subscripting on pointer to void
5810     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5811       << BaseExpr->getSourceRange();
5812 
5813     // C forbids expressions of unqualified void type from being l-values.
5814     // See IsCForbiddenLValueType.
5815     if (!ResultType.hasQualifiers())
5816       VK = VK_PRValue;
5817   } else if (!ResultType->isDependentType() &&
5818              RequireCompleteSizedType(
5819                  LLoc, ResultType,
5820                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5821     return ExprError();
5822 
5823   assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5824          !ResultType.isCForbiddenLValueType());
5825 
5826   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5827       FunctionScopes.size() > 1) {
5828     if (auto *TT =
5829             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5830       for (auto I = FunctionScopes.rbegin(),
5831                 E = std::prev(FunctionScopes.rend());
5832            I != E; ++I) {
5833         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5834         if (CSI == nullptr)
5835           break;
5836         DeclContext *DC = nullptr;
5837         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5838           DC = LSI->CallOperator;
5839         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5840           DC = CRSI->TheCapturedDecl;
5841         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5842           DC = BSI->TheDecl;
5843         if (DC) {
5844           if (DC->containsDecl(TT->getDecl()))
5845             break;
5846           captureVariablyModifiedType(
5847               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5848         }
5849       }
5850     }
5851   }
5852 
5853   return new (Context)
5854       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5855 }
5856 
5857 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5858                                   ParmVarDecl *Param) {
5859   if (Param->hasUnparsedDefaultArg()) {
5860     // If we've already cleared out the location for the default argument,
5861     // that means we're parsing it right now.
5862     if (!UnparsedDefaultArgLocs.count(Param)) {
5863       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5864       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5865       Param->setInvalidDecl();
5866       return true;
5867     }
5868 
5869     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5870         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5871     Diag(UnparsedDefaultArgLocs[Param],
5872          diag::note_default_argument_declared_here);
5873     return true;
5874   }
5875 
5876   if (Param->hasUninstantiatedDefaultArg() &&
5877       InstantiateDefaultArgument(CallLoc, FD, Param))
5878     return true;
5879 
5880   assert(Param->hasInit() && "default argument but no initializer?");
5881 
5882   // If the default expression creates temporaries, we need to
5883   // push them to the current stack of expression temporaries so they'll
5884   // be properly destroyed.
5885   // FIXME: We should really be rebuilding the default argument with new
5886   // bound temporaries; see the comment in PR5810.
5887   // We don't need to do that with block decls, though, because
5888   // blocks in default argument expression can never capture anything.
5889   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5890     // Set the "needs cleanups" bit regardless of whether there are
5891     // any explicit objects.
5892     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5893 
5894     // Append all the objects to the cleanup list.  Right now, this
5895     // should always be a no-op, because blocks in default argument
5896     // expressions should never be able to capture anything.
5897     assert(!Init->getNumObjects() &&
5898            "default argument expression has capturing blocks?");
5899   }
5900 
5901   // We already type-checked the argument, so we know it works.
5902   // Just mark all of the declarations in this potentially-evaluated expression
5903   // as being "referenced".
5904   EnterExpressionEvaluationContext EvalContext(
5905       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5906   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5907                                    /*SkipLocalVariables=*/true);
5908   return false;
5909 }
5910 
5911 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5912                                         FunctionDecl *FD, ParmVarDecl *Param) {
5913   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5914   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5915     return ExprError();
5916   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5917 }
5918 
5919 Sema::VariadicCallType
5920 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5921                           Expr *Fn) {
5922   if (Proto && Proto->isVariadic()) {
5923     if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5924       return VariadicConstructor;
5925     else if (Fn && Fn->getType()->isBlockPointerType())
5926       return VariadicBlock;
5927     else if (FDecl) {
5928       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5929         if (Method->isInstance())
5930           return VariadicMethod;
5931     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5932       return VariadicMethod;
5933     return VariadicFunction;
5934   }
5935   return VariadicDoesNotApply;
5936 }
5937 
5938 namespace {
5939 class FunctionCallCCC final : public FunctionCallFilterCCC {
5940 public:
5941   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5942                   unsigned NumArgs, MemberExpr *ME)
5943       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5944         FunctionName(FuncName) {}
5945 
5946   bool ValidateCandidate(const TypoCorrection &candidate) override {
5947     if (!candidate.getCorrectionSpecifier() ||
5948         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5949       return false;
5950     }
5951 
5952     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5953   }
5954 
5955   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5956     return std::make_unique<FunctionCallCCC>(*this);
5957   }
5958 
5959 private:
5960   const IdentifierInfo *const FunctionName;
5961 };
5962 }
5963 
5964 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5965                                                FunctionDecl *FDecl,
5966                                                ArrayRef<Expr *> Args) {
5967   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5968   DeclarationName FuncName = FDecl->getDeclName();
5969   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5970 
5971   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5972   if (TypoCorrection Corrected = S.CorrectTypo(
5973           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5974           S.getScopeForContext(S.CurContext), nullptr, CCC,
5975           Sema::CTK_ErrorRecovery)) {
5976     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5977       if (Corrected.isOverloaded()) {
5978         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5979         OverloadCandidateSet::iterator Best;
5980         for (NamedDecl *CD : Corrected) {
5981           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5982             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5983                                    OCS);
5984         }
5985         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5986         case OR_Success:
5987           ND = Best->FoundDecl;
5988           Corrected.setCorrectionDecl(ND);
5989           break;
5990         default:
5991           break;
5992         }
5993       }
5994       ND = ND->getUnderlyingDecl();
5995       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5996         return Corrected;
5997     }
5998   }
5999   return TypoCorrection();
6000 }
6001 
6002 /// ConvertArgumentsForCall - Converts the arguments specified in
6003 /// Args/NumArgs to the parameter types of the function FDecl with
6004 /// function prototype Proto. Call is the call expression itself, and
6005 /// Fn is the function expression. For a C++ member function, this
6006 /// routine does not attempt to convert the object argument. Returns
6007 /// true if the call is ill-formed.
6008 bool
6009 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6010                               FunctionDecl *FDecl,
6011                               const FunctionProtoType *Proto,
6012                               ArrayRef<Expr *> Args,
6013                               SourceLocation RParenLoc,
6014                               bool IsExecConfig) {
6015   // Bail out early if calling a builtin with custom typechecking.
6016   if (FDecl)
6017     if (unsigned ID = FDecl->getBuiltinID())
6018       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
6019         return false;
6020 
6021   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6022   // assignment, to the types of the corresponding parameter, ...
6023   unsigned NumParams = Proto->getNumParams();
6024   bool Invalid = false;
6025   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6026   unsigned FnKind = Fn->getType()->isBlockPointerType()
6027                        ? 1 /* block */
6028                        : (IsExecConfig ? 3 /* kernel function (exec config) */
6029                                        : 0 /* function */);
6030 
6031   // If too few arguments are available (and we don't have default
6032   // arguments for the remaining parameters), don't make the call.
6033   if (Args.size() < NumParams) {
6034     if (Args.size() < MinArgs) {
6035       TypoCorrection TC;
6036       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6037         unsigned diag_id =
6038             MinArgs == NumParams && !Proto->isVariadic()
6039                 ? diag::err_typecheck_call_too_few_args_suggest
6040                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6041         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
6042                                         << static_cast<unsigned>(Args.size())
6043                                         << TC.getCorrectionRange());
6044       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
6045         Diag(RParenLoc,
6046              MinArgs == NumParams && !Proto->isVariadic()
6047                  ? diag::err_typecheck_call_too_few_args_one
6048                  : diag::err_typecheck_call_too_few_args_at_least_one)
6049             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
6050       else
6051         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6052                             ? diag::err_typecheck_call_too_few_args
6053                             : diag::err_typecheck_call_too_few_args_at_least)
6054             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
6055             << Fn->getSourceRange();
6056 
6057       // Emit the location of the prototype.
6058       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6059         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6060 
6061       return true;
6062     }
6063     // We reserve space for the default arguments when we create
6064     // the call expression, before calling ConvertArgumentsForCall.
6065     assert((Call->getNumArgs() == NumParams) &&
6066            "We should have reserved space for the default arguments before!");
6067   }
6068 
6069   // If too many are passed and not variadic, error on the extras and drop
6070   // them.
6071   if (Args.size() > NumParams) {
6072     if (!Proto->isVariadic()) {
6073       TypoCorrection TC;
6074       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6075         unsigned diag_id =
6076             MinArgs == NumParams && !Proto->isVariadic()
6077                 ? diag::err_typecheck_call_too_many_args_suggest
6078                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6079         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
6080                                         << static_cast<unsigned>(Args.size())
6081                                         << TC.getCorrectionRange());
6082       } else if (NumParams == 1 && FDecl &&
6083                  FDecl->getParamDecl(0)->getDeclName())
6084         Diag(Args[NumParams]->getBeginLoc(),
6085              MinArgs == NumParams
6086                  ? diag::err_typecheck_call_too_many_args_one
6087                  : diag::err_typecheck_call_too_many_args_at_most_one)
6088             << FnKind << FDecl->getParamDecl(0)
6089             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
6090             << SourceRange(Args[NumParams]->getBeginLoc(),
6091                            Args.back()->getEndLoc());
6092       else
6093         Diag(Args[NumParams]->getBeginLoc(),
6094              MinArgs == NumParams
6095                  ? diag::err_typecheck_call_too_many_args
6096                  : diag::err_typecheck_call_too_many_args_at_most)
6097             << FnKind << NumParams << static_cast<unsigned>(Args.size())
6098             << Fn->getSourceRange()
6099             << SourceRange(Args[NumParams]->getBeginLoc(),
6100                            Args.back()->getEndLoc());
6101 
6102       // Emit the location of the prototype.
6103       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6104         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6105 
6106       // This deletes the extra arguments.
6107       Call->shrinkNumArgs(NumParams);
6108       return true;
6109     }
6110   }
6111   SmallVector<Expr *, 8> AllArgs;
6112   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6113 
6114   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6115                                    AllArgs, CallType);
6116   if (Invalid)
6117     return true;
6118   unsigned TotalNumArgs = AllArgs.size();
6119   for (unsigned i = 0; i < TotalNumArgs; ++i)
6120     Call->setArg(i, AllArgs[i]);
6121 
6122   Call->computeDependence();
6123   return false;
6124 }
6125 
6126 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6127                                   const FunctionProtoType *Proto,
6128                                   unsigned FirstParam, ArrayRef<Expr *> Args,
6129                                   SmallVectorImpl<Expr *> &AllArgs,
6130                                   VariadicCallType CallType, bool AllowExplicit,
6131                                   bool IsListInitialization) {
6132   unsigned NumParams = Proto->getNumParams();
6133   bool Invalid = false;
6134   size_t ArgIx = 0;
6135   // Continue to check argument types (even if we have too few/many args).
6136   for (unsigned i = FirstParam; i < NumParams; i++) {
6137     QualType ProtoArgType = Proto->getParamType(i);
6138 
6139     Expr *Arg;
6140     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6141     if (ArgIx < Args.size()) {
6142       Arg = Args[ArgIx++];
6143 
6144       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6145                               diag::err_call_incomplete_argument, Arg))
6146         return true;
6147 
6148       // Strip the unbridged-cast placeholder expression off, if applicable.
6149       bool CFAudited = false;
6150       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6151           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6152           (!Param || !Param->hasAttr<CFConsumedAttr>()))
6153         Arg = stripARCUnbridgedCast(Arg);
6154       else if (getLangOpts().ObjCAutoRefCount &&
6155                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6156                (!Param || !Param->hasAttr<CFConsumedAttr>()))
6157         CFAudited = true;
6158 
6159       if (Proto->getExtParameterInfo(i).isNoEscape() &&
6160           ProtoArgType->isBlockPointerType())
6161         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6162           BE->getBlockDecl()->setDoesNotEscape();
6163 
6164       InitializedEntity Entity =
6165           Param ? InitializedEntity::InitializeParameter(Context, Param,
6166                                                          ProtoArgType)
6167                 : InitializedEntity::InitializeParameter(
6168                       Context, ProtoArgType, Proto->isParamConsumed(i));
6169 
6170       // Remember that parameter belongs to a CF audited API.
6171       if (CFAudited)
6172         Entity.setParameterCFAudited();
6173 
6174       ExprResult ArgE = PerformCopyInitialization(
6175           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6176       if (ArgE.isInvalid())
6177         return true;
6178 
6179       Arg = ArgE.getAs<Expr>();
6180     } else {
6181       assert(Param && "can't use default arguments without a known callee");
6182 
6183       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6184       if (ArgExpr.isInvalid())
6185         return true;
6186 
6187       Arg = ArgExpr.getAs<Expr>();
6188     }
6189 
6190     // Check for array bounds violations for each argument to the call. This
6191     // check only triggers warnings when the argument isn't a more complex Expr
6192     // with its own checking, such as a BinaryOperator.
6193     CheckArrayAccess(Arg);
6194 
6195     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6196     CheckStaticArrayArgument(CallLoc, Param, Arg);
6197 
6198     AllArgs.push_back(Arg);
6199   }
6200 
6201   // If this is a variadic call, handle args passed through "...".
6202   if (CallType != VariadicDoesNotApply) {
6203     // Assume that extern "C" functions with variadic arguments that
6204     // return __unknown_anytype aren't *really* variadic.
6205     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6206         FDecl->isExternC()) {
6207       for (Expr *A : Args.slice(ArgIx)) {
6208         QualType paramType; // ignored
6209         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6210         Invalid |= arg.isInvalid();
6211         AllArgs.push_back(arg.get());
6212       }
6213 
6214     // Otherwise do argument promotion, (C99 6.5.2.2p7).
6215     } else {
6216       for (Expr *A : Args.slice(ArgIx)) {
6217         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6218         Invalid |= Arg.isInvalid();
6219         AllArgs.push_back(Arg.get());
6220       }
6221     }
6222 
6223     // Check for array bounds violations.
6224     for (Expr *A : Args.slice(ArgIx))
6225       CheckArrayAccess(A);
6226   }
6227   return Invalid;
6228 }
6229 
6230 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6231   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6232   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6233     TL = DTL.getOriginalLoc();
6234   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6235     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6236       << ATL.getLocalSourceRange();
6237 }
6238 
6239 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6240 /// array parameter, check that it is non-null, and that if it is formed by
6241 /// array-to-pointer decay, the underlying array is sufficiently large.
6242 ///
6243 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6244 /// array type derivation, then for each call to the function, the value of the
6245 /// corresponding actual argument shall provide access to the first element of
6246 /// an array with at least as many elements as specified by the size expression.
6247 void
6248 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6249                                ParmVarDecl *Param,
6250                                const Expr *ArgExpr) {
6251   // Static array parameters are not supported in C++.
6252   if (!Param || getLangOpts().CPlusPlus)
6253     return;
6254 
6255   QualType OrigTy = Param->getOriginalType();
6256 
6257   const ArrayType *AT = Context.getAsArrayType(OrigTy);
6258   if (!AT || AT->getSizeModifier() != ArrayType::Static)
6259     return;
6260 
6261   if (ArgExpr->isNullPointerConstant(Context,
6262                                      Expr::NPC_NeverValueDependent)) {
6263     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6264     DiagnoseCalleeStaticArrayParam(*this, Param);
6265     return;
6266   }
6267 
6268   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6269   if (!CAT)
6270     return;
6271 
6272   const ConstantArrayType *ArgCAT =
6273     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6274   if (!ArgCAT)
6275     return;
6276 
6277   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6278                                              ArgCAT->getElementType())) {
6279     if (ArgCAT->getSize().ult(CAT->getSize())) {
6280       Diag(CallLoc, diag::warn_static_array_too_small)
6281           << ArgExpr->getSourceRange()
6282           << (unsigned)ArgCAT->getSize().getZExtValue()
6283           << (unsigned)CAT->getSize().getZExtValue() << 0;
6284       DiagnoseCalleeStaticArrayParam(*this, Param);
6285     }
6286     return;
6287   }
6288 
6289   Optional<CharUnits> ArgSize =
6290       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6291   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6292   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6293     Diag(CallLoc, diag::warn_static_array_too_small)
6294         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6295         << (unsigned)ParmSize->getQuantity() << 1;
6296     DiagnoseCalleeStaticArrayParam(*this, Param);
6297   }
6298 }
6299 
6300 /// Given a function expression of unknown-any type, try to rebuild it
6301 /// to have a function type.
6302 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6303 
6304 /// Is the given type a placeholder that we need to lower out
6305 /// immediately during argument processing?
6306 static bool isPlaceholderToRemoveAsArg(QualType type) {
6307   // Placeholders are never sugared.
6308   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6309   if (!placeholder) return false;
6310 
6311   switch (placeholder->getKind()) {
6312   // Ignore all the non-placeholder types.
6313 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6314   case BuiltinType::Id:
6315 #include "clang/Basic/OpenCLImageTypes.def"
6316 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6317   case BuiltinType::Id:
6318 #include "clang/Basic/OpenCLExtensionTypes.def"
6319   // In practice we'll never use this, since all SVE types are sugared
6320   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6321 #define SVE_TYPE(Name, Id, SingletonId) \
6322   case BuiltinType::Id:
6323 #include "clang/Basic/AArch64SVEACLETypes.def"
6324 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6325   case BuiltinType::Id:
6326 #include "clang/Basic/PPCTypes.def"
6327 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6328 #include "clang/Basic/RISCVVTypes.def"
6329 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6330 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6331 #include "clang/AST/BuiltinTypes.def"
6332     return false;
6333 
6334   // We cannot lower out overload sets; they might validly be resolved
6335   // by the call machinery.
6336   case BuiltinType::Overload:
6337     return false;
6338 
6339   // Unbridged casts in ARC can be handled in some call positions and
6340   // should be left in place.
6341   case BuiltinType::ARCUnbridgedCast:
6342     return false;
6343 
6344   // Pseudo-objects should be converted as soon as possible.
6345   case BuiltinType::PseudoObject:
6346     return true;
6347 
6348   // The debugger mode could theoretically but currently does not try
6349   // to resolve unknown-typed arguments based on known parameter types.
6350   case BuiltinType::UnknownAny:
6351     return true;
6352 
6353   // These are always invalid as call arguments and should be reported.
6354   case BuiltinType::BoundMember:
6355   case BuiltinType::BuiltinFn:
6356   case BuiltinType::IncompleteMatrixIdx:
6357   case BuiltinType::OMPArraySection:
6358   case BuiltinType::OMPArrayShaping:
6359   case BuiltinType::OMPIterator:
6360     return true;
6361 
6362   }
6363   llvm_unreachable("bad builtin type kind");
6364 }
6365 
6366 /// Check an argument list for placeholders that we won't try to
6367 /// handle later.
6368 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6369   // Apply this processing to all the arguments at once instead of
6370   // dying at the first failure.
6371   bool hasInvalid = false;
6372   for (size_t i = 0, e = args.size(); i != e; i++) {
6373     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6374       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6375       if (result.isInvalid()) hasInvalid = true;
6376       else args[i] = result.get();
6377     }
6378   }
6379   return hasInvalid;
6380 }
6381 
6382 /// If a builtin function has a pointer argument with no explicit address
6383 /// space, then it should be able to accept a pointer to any address
6384 /// space as input.  In order to do this, we need to replace the
6385 /// standard builtin declaration with one that uses the same address space
6386 /// as the call.
6387 ///
6388 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6389 ///                  it does not contain any pointer arguments without
6390 ///                  an address space qualifer.  Otherwise the rewritten
6391 ///                  FunctionDecl is returned.
6392 /// TODO: Handle pointer return types.
6393 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6394                                                 FunctionDecl *FDecl,
6395                                                 MultiExprArg ArgExprs) {
6396 
6397   QualType DeclType = FDecl->getType();
6398   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6399 
6400   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6401       ArgExprs.size() < FT->getNumParams())
6402     return nullptr;
6403 
6404   bool NeedsNewDecl = false;
6405   unsigned i = 0;
6406   SmallVector<QualType, 8> OverloadParams;
6407 
6408   for (QualType ParamType : FT->param_types()) {
6409 
6410     // Convert array arguments to pointer to simplify type lookup.
6411     ExprResult ArgRes =
6412         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6413     if (ArgRes.isInvalid())
6414       return nullptr;
6415     Expr *Arg = ArgRes.get();
6416     QualType ArgType = Arg->getType();
6417     if (!ParamType->isPointerType() ||
6418         ParamType.hasAddressSpace() ||
6419         !ArgType->isPointerType() ||
6420         !ArgType->getPointeeType().hasAddressSpace()) {
6421       OverloadParams.push_back(ParamType);
6422       continue;
6423     }
6424 
6425     QualType PointeeType = ParamType->getPointeeType();
6426     if (PointeeType.hasAddressSpace())
6427       continue;
6428 
6429     NeedsNewDecl = true;
6430     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6431 
6432     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6433     OverloadParams.push_back(Context.getPointerType(PointeeType));
6434   }
6435 
6436   if (!NeedsNewDecl)
6437     return nullptr;
6438 
6439   FunctionProtoType::ExtProtoInfo EPI;
6440   EPI.Variadic = FT->isVariadic();
6441   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6442                                                 OverloadParams, EPI);
6443   DeclContext *Parent = FDecl->getParent();
6444   FunctionDecl *OverloadDecl = FunctionDecl::Create(
6445       Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6446       FDecl->getIdentifier(), OverloadTy,
6447       /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6448       false,
6449       /*hasPrototype=*/true);
6450   SmallVector<ParmVarDecl*, 16> Params;
6451   FT = cast<FunctionProtoType>(OverloadTy);
6452   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6453     QualType ParamType = FT->getParamType(i);
6454     ParmVarDecl *Parm =
6455         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6456                                 SourceLocation(), nullptr, ParamType,
6457                                 /*TInfo=*/nullptr, SC_None, nullptr);
6458     Parm->setScopeInfo(0, i);
6459     Params.push_back(Parm);
6460   }
6461   OverloadDecl->setParams(Params);
6462   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6463   return OverloadDecl;
6464 }
6465 
6466 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6467                                     FunctionDecl *Callee,
6468                                     MultiExprArg ArgExprs) {
6469   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6470   // similar attributes) really don't like it when functions are called with an
6471   // invalid number of args.
6472   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6473                          /*PartialOverloading=*/false) &&
6474       !Callee->isVariadic())
6475     return;
6476   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6477     return;
6478 
6479   if (const EnableIfAttr *Attr =
6480           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6481     S.Diag(Fn->getBeginLoc(),
6482            isa<CXXMethodDecl>(Callee)
6483                ? diag::err_ovl_no_viable_member_function_in_call
6484                : diag::err_ovl_no_viable_function_in_call)
6485         << Callee << Callee->getSourceRange();
6486     S.Diag(Callee->getLocation(),
6487            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6488         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6489     return;
6490   }
6491 }
6492 
6493 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6494     const UnresolvedMemberExpr *const UME, Sema &S) {
6495 
6496   const auto GetFunctionLevelDCIfCXXClass =
6497       [](Sema &S) -> const CXXRecordDecl * {
6498     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6499     if (!DC || !DC->getParent())
6500       return nullptr;
6501 
6502     // If the call to some member function was made from within a member
6503     // function body 'M' return return 'M's parent.
6504     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6505       return MD->getParent()->getCanonicalDecl();
6506     // else the call was made from within a default member initializer of a
6507     // class, so return the class.
6508     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6509       return RD->getCanonicalDecl();
6510     return nullptr;
6511   };
6512   // If our DeclContext is neither a member function nor a class (in the
6513   // case of a lambda in a default member initializer), we can't have an
6514   // enclosing 'this'.
6515 
6516   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6517   if (!CurParentClass)
6518     return false;
6519 
6520   // The naming class for implicit member functions call is the class in which
6521   // name lookup starts.
6522   const CXXRecordDecl *const NamingClass =
6523       UME->getNamingClass()->getCanonicalDecl();
6524   assert(NamingClass && "Must have naming class even for implicit access");
6525 
6526   // If the unresolved member functions were found in a 'naming class' that is
6527   // related (either the same or derived from) to the class that contains the
6528   // member function that itself contained the implicit member access.
6529 
6530   return CurParentClass == NamingClass ||
6531          CurParentClass->isDerivedFrom(NamingClass);
6532 }
6533 
6534 static void
6535 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6536     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6537 
6538   if (!UME)
6539     return;
6540 
6541   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6542   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6543   // already been captured, or if this is an implicit member function call (if
6544   // it isn't, an attempt to capture 'this' should already have been made).
6545   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6546       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6547     return;
6548 
6549   // Check if the naming class in which the unresolved members were found is
6550   // related (same as or is a base of) to the enclosing class.
6551 
6552   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6553     return;
6554 
6555 
6556   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6557   // If the enclosing function is not dependent, then this lambda is
6558   // capture ready, so if we can capture this, do so.
6559   if (!EnclosingFunctionCtx->isDependentContext()) {
6560     // If the current lambda and all enclosing lambdas can capture 'this' -
6561     // then go ahead and capture 'this' (since our unresolved overload set
6562     // contains at least one non-static member function).
6563     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6564       S.CheckCXXThisCapture(CallLoc);
6565   } else if (S.CurContext->isDependentContext()) {
6566     // ... since this is an implicit member reference, that might potentially
6567     // involve a 'this' capture, mark 'this' for potential capture in
6568     // enclosing lambdas.
6569     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6570       CurLSI->addPotentialThisCapture(CallLoc);
6571   }
6572 }
6573 
6574 // Once a call is fully resolved, warn for unqualified calls to specific
6575 // C++ standard functions, like move and forward.
6576 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) {
6577   // We are only checking unary move and forward so exit early here.
6578   if (Call->getNumArgs() != 1)
6579     return;
6580 
6581   Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6582   if (!E || isa<UnresolvedLookupExpr>(E))
6583     return;
6584   DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
6585   if (!DRE || !DRE->getLocation().isValid())
6586     return;
6587 
6588   if (DRE->getQualifier())
6589     return;
6590 
6591   const FunctionDecl *FD = Call->getDirectCallee();
6592   if (!FD)
6593     return;
6594 
6595   // Only warn for some functions deemed more frequent or problematic.
6596   unsigned BuiltinID = FD->getBuiltinID();
6597   if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6598     return;
6599 
6600   S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6601       << FD->getQualifiedNameAsString()
6602       << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6603 }
6604 
6605 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6606                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6607                                Expr *ExecConfig) {
6608   ExprResult Call =
6609       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6610                     /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6611   if (Call.isInvalid())
6612     return Call;
6613 
6614   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6615   // language modes.
6616   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6617     if (ULE->hasExplicitTemplateArgs() &&
6618         ULE->decls_begin() == ULE->decls_end()) {
6619       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6620                                  ? diag::warn_cxx17_compat_adl_only_template_id
6621                                  : diag::ext_adl_only_template_id)
6622           << ULE->getName();
6623     }
6624   }
6625 
6626   if (LangOpts.OpenMP)
6627     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6628                            ExecConfig);
6629   if (LangOpts.CPlusPlus) {
6630     CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6631     if (CE)
6632       DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
6633   }
6634   return Call;
6635 }
6636 
6637 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6638 /// This provides the location of the left/right parens and a list of comma
6639 /// locations.
6640 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6641                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6642                                Expr *ExecConfig, bool IsExecConfig,
6643                                bool AllowRecovery) {
6644   // Since this might be a postfix expression, get rid of ParenListExprs.
6645   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6646   if (Result.isInvalid()) return ExprError();
6647   Fn = Result.get();
6648 
6649   if (checkArgsForPlaceholders(*this, ArgExprs))
6650     return ExprError();
6651 
6652   if (getLangOpts().CPlusPlus) {
6653     // If this is a pseudo-destructor expression, build the call immediately.
6654     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6655       if (!ArgExprs.empty()) {
6656         // Pseudo-destructor calls should not have any arguments.
6657         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6658             << FixItHint::CreateRemoval(
6659                    SourceRange(ArgExprs.front()->getBeginLoc(),
6660                                ArgExprs.back()->getEndLoc()));
6661       }
6662 
6663       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6664                               VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6665     }
6666     if (Fn->getType() == Context.PseudoObjectTy) {
6667       ExprResult result = CheckPlaceholderExpr(Fn);
6668       if (result.isInvalid()) return ExprError();
6669       Fn = result.get();
6670     }
6671 
6672     // Determine whether this is a dependent call inside a C++ template,
6673     // in which case we won't do any semantic analysis now.
6674     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6675       if (ExecConfig) {
6676         return CUDAKernelCallExpr::Create(Context, Fn,
6677                                           cast<CallExpr>(ExecConfig), ArgExprs,
6678                                           Context.DependentTy, VK_PRValue,
6679                                           RParenLoc, CurFPFeatureOverrides());
6680       } else {
6681 
6682         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6683             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6684             Fn->getBeginLoc());
6685 
6686         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6687                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6688       }
6689     }
6690 
6691     // Determine whether this is a call to an object (C++ [over.call.object]).
6692     if (Fn->getType()->isRecordType())
6693       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6694                                           RParenLoc);
6695 
6696     if (Fn->getType() == Context.UnknownAnyTy) {
6697       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6698       if (result.isInvalid()) return ExprError();
6699       Fn = result.get();
6700     }
6701 
6702     if (Fn->getType() == Context.BoundMemberTy) {
6703       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6704                                        RParenLoc, ExecConfig, IsExecConfig,
6705                                        AllowRecovery);
6706     }
6707   }
6708 
6709   // Check for overloaded calls.  This can happen even in C due to extensions.
6710   if (Fn->getType() == Context.OverloadTy) {
6711     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6712 
6713     // We aren't supposed to apply this logic if there's an '&' involved.
6714     if (!find.HasFormOfMemberPointer) {
6715       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6716         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6717                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6718       OverloadExpr *ovl = find.Expression;
6719       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6720         return BuildOverloadedCallExpr(
6721             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6722             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6723       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6724                                        RParenLoc, ExecConfig, IsExecConfig,
6725                                        AllowRecovery);
6726     }
6727   }
6728 
6729   // If we're directly calling a function, get the appropriate declaration.
6730   if (Fn->getType() == Context.UnknownAnyTy) {
6731     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6732     if (result.isInvalid()) return ExprError();
6733     Fn = result.get();
6734   }
6735 
6736   Expr *NakedFn = Fn->IgnoreParens();
6737 
6738   bool CallingNDeclIndirectly = false;
6739   NamedDecl *NDecl = nullptr;
6740   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6741     if (UnOp->getOpcode() == UO_AddrOf) {
6742       CallingNDeclIndirectly = true;
6743       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6744     }
6745   }
6746 
6747   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6748     NDecl = DRE->getDecl();
6749 
6750     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6751     if (FDecl && FDecl->getBuiltinID()) {
6752       // Rewrite the function decl for this builtin by replacing parameters
6753       // with no explicit address space with the address space of the arguments
6754       // in ArgExprs.
6755       if ((FDecl =
6756                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6757         NDecl = FDecl;
6758         Fn = DeclRefExpr::Create(
6759             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6760             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6761             nullptr, DRE->isNonOdrUse());
6762       }
6763     }
6764   } else if (isa<MemberExpr>(NakedFn))
6765     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6766 
6767   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6768     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6769                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6770       return ExprError();
6771 
6772     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6773 
6774     // If this expression is a call to a builtin function in HIP device
6775     // compilation, allow a pointer-type argument to default address space to be
6776     // passed as a pointer-type parameter to a non-default address space.
6777     // If Arg is declared in the default address space and Param is declared
6778     // in a non-default address space, perform an implicit address space cast to
6779     // the parameter type.
6780     if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6781         FD->getBuiltinID()) {
6782       for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6783         ParmVarDecl *Param = FD->getParamDecl(Idx);
6784         if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6785             !ArgExprs[Idx]->getType()->isPointerType())
6786           continue;
6787 
6788         auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6789         auto ArgTy = ArgExprs[Idx]->getType();
6790         auto ArgPtTy = ArgTy->getPointeeType();
6791         auto ArgAS = ArgPtTy.getAddressSpace();
6792 
6793         // Add address space cast if target address spaces are different
6794         bool NeedImplicitASC =
6795           ParamAS != LangAS::Default &&       // Pointer params in generic AS don't need special handling.
6796           ( ArgAS == LangAS::Default  ||      // We do allow implicit conversion from generic AS
6797                                               // or from specific AS which has target AS matching that of Param.
6798           getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
6799         if (!NeedImplicitASC)
6800           continue;
6801 
6802         // First, ensure that the Arg is an RValue.
6803         if (ArgExprs[Idx]->isGLValue()) {
6804           ArgExprs[Idx] = ImplicitCastExpr::Create(
6805               Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6806               nullptr, VK_PRValue, FPOptionsOverride());
6807         }
6808 
6809         // Construct a new arg type with address space of Param
6810         Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6811         ArgPtQuals.setAddressSpace(ParamAS);
6812         auto NewArgPtTy =
6813             Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6814         auto NewArgTy =
6815             Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6816                                      ArgTy.getQualifiers());
6817 
6818         // Finally perform an implicit address space cast
6819         ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6820                                           CK_AddressSpaceConversion)
6821                             .get();
6822       }
6823     }
6824   }
6825 
6826   if (Context.isDependenceAllowed() &&
6827       (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6828     assert(!getLangOpts().CPlusPlus);
6829     assert((Fn->containsErrors() ||
6830             llvm::any_of(ArgExprs,
6831                          [](clang::Expr *E) { return E->containsErrors(); })) &&
6832            "should only occur in error-recovery path.");
6833     QualType ReturnType =
6834         llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6835             ? cast<FunctionDecl>(NDecl)->getCallResultType()
6836             : Context.DependentTy;
6837     return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6838                             Expr::getValueKindForType(ReturnType), RParenLoc,
6839                             CurFPFeatureOverrides());
6840   }
6841   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6842                                ExecConfig, IsExecConfig);
6843 }
6844 
6845 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6846 //  with the specified CallArgs
6847 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6848                                  MultiExprArg CallArgs) {
6849   StringRef Name = Context.BuiltinInfo.getName(Id);
6850   LookupResult R(*this, &Context.Idents.get(Name), Loc,
6851                  Sema::LookupOrdinaryName);
6852   LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6853 
6854   auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6855   assert(BuiltInDecl && "failed to find builtin declaration");
6856 
6857   ExprResult DeclRef =
6858       BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6859   assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6860 
6861   ExprResult Call =
6862       BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6863 
6864   assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6865   return Call.get();
6866 }
6867 
6868 /// Parse a __builtin_astype expression.
6869 ///
6870 /// __builtin_astype( value, dst type )
6871 ///
6872 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6873                                  SourceLocation BuiltinLoc,
6874                                  SourceLocation RParenLoc) {
6875   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6876   return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6877 }
6878 
6879 /// Create a new AsTypeExpr node (bitcast) from the arguments.
6880 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6881                                  SourceLocation BuiltinLoc,
6882                                  SourceLocation RParenLoc) {
6883   ExprValueKind VK = VK_PRValue;
6884   ExprObjectKind OK = OK_Ordinary;
6885   QualType SrcTy = E->getType();
6886   if (!SrcTy->isDependentType() &&
6887       Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6888     return ExprError(
6889         Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6890         << DestTy << SrcTy << E->getSourceRange());
6891   return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6892 }
6893 
6894 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6895 /// provided arguments.
6896 ///
6897 /// __builtin_convertvector( value, dst type )
6898 ///
6899 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6900                                         SourceLocation BuiltinLoc,
6901                                         SourceLocation RParenLoc) {
6902   TypeSourceInfo *TInfo;
6903   GetTypeFromParser(ParsedDestTy, &TInfo);
6904   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6905 }
6906 
6907 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6908 /// i.e. an expression not of \p OverloadTy.  The expression should
6909 /// unary-convert to an expression of function-pointer or
6910 /// block-pointer type.
6911 ///
6912 /// \param NDecl the declaration being called, if available
6913 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6914                                        SourceLocation LParenLoc,
6915                                        ArrayRef<Expr *> Args,
6916                                        SourceLocation RParenLoc, Expr *Config,
6917                                        bool IsExecConfig, ADLCallKind UsesADL) {
6918   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6919   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6920 
6921   // Functions with 'interrupt' attribute cannot be called directly.
6922   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6923     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6924     return ExprError();
6925   }
6926 
6927   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6928   // so there's some risk when calling out to non-interrupt handler functions
6929   // that the callee might not preserve them. This is easy to diagnose here,
6930   // but can be very challenging to debug.
6931   // Likewise, X86 interrupt handlers may only call routines with attribute
6932   // no_caller_saved_registers since there is no efficient way to
6933   // save and restore the non-GPR state.
6934   if (auto *Caller = getCurFunctionDecl()) {
6935     if (Caller->hasAttr<ARMInterruptAttr>()) {
6936       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6937       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6938         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6939         if (FDecl)
6940           Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6941       }
6942     }
6943     if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6944         ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6945       Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6946       if (FDecl)
6947         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6948     }
6949   }
6950 
6951   // Promote the function operand.
6952   // We special-case function promotion here because we only allow promoting
6953   // builtin functions to function pointers in the callee of a call.
6954   ExprResult Result;
6955   QualType ResultTy;
6956   if (BuiltinID &&
6957       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6958     // Extract the return type from the (builtin) function pointer type.
6959     // FIXME Several builtins still have setType in
6960     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6961     // Builtins.def to ensure they are correct before removing setType calls.
6962     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6963     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6964     ResultTy = FDecl->getCallResultType();
6965   } else {
6966     Result = CallExprUnaryConversions(Fn);
6967     ResultTy = Context.BoolTy;
6968   }
6969   if (Result.isInvalid())
6970     return ExprError();
6971   Fn = Result.get();
6972 
6973   // Check for a valid function type, but only if it is not a builtin which
6974   // requires custom type checking. These will be handled by
6975   // CheckBuiltinFunctionCall below just after creation of the call expression.
6976   const FunctionType *FuncT = nullptr;
6977   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6978   retry:
6979     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6980       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6981       // have type pointer to function".
6982       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6983       if (!FuncT)
6984         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6985                          << Fn->getType() << Fn->getSourceRange());
6986     } else if (const BlockPointerType *BPT =
6987                    Fn->getType()->getAs<BlockPointerType>()) {
6988       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6989     } else {
6990       // Handle calls to expressions of unknown-any type.
6991       if (Fn->getType() == Context.UnknownAnyTy) {
6992         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6993         if (rewrite.isInvalid())
6994           return ExprError();
6995         Fn = rewrite.get();
6996         goto retry;
6997       }
6998 
6999       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7000                        << Fn->getType() << Fn->getSourceRange());
7001     }
7002   }
7003 
7004   // Get the number of parameters in the function prototype, if any.
7005   // We will allocate space for max(Args.size(), NumParams) arguments
7006   // in the call expression.
7007   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7008   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7009 
7010   CallExpr *TheCall;
7011   if (Config) {
7012     assert(UsesADL == ADLCallKind::NotADL &&
7013            "CUDAKernelCallExpr should not use ADL");
7014     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7015                                          Args, ResultTy, VK_PRValue, RParenLoc,
7016                                          CurFPFeatureOverrides(), NumParams);
7017   } else {
7018     TheCall =
7019         CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7020                          CurFPFeatureOverrides(), NumParams, UsesADL);
7021   }
7022 
7023   if (!Context.isDependenceAllowed()) {
7024     // Forget about the nulled arguments since typo correction
7025     // do not handle them well.
7026     TheCall->shrinkNumArgs(Args.size());
7027     // C cannot always handle TypoExpr nodes in builtin calls and direct
7028     // function calls as their argument checking don't necessarily handle
7029     // dependent types properly, so make sure any TypoExprs have been
7030     // dealt with.
7031     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
7032     if (!Result.isUsable()) return ExprError();
7033     CallExpr *TheOldCall = TheCall;
7034     TheCall = dyn_cast<CallExpr>(Result.get());
7035     bool CorrectedTypos = TheCall != TheOldCall;
7036     if (!TheCall) return Result;
7037     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7038 
7039     // A new call expression node was created if some typos were corrected.
7040     // However it may not have been constructed with enough storage. In this
7041     // case, rebuild the node with enough storage. The waste of space is
7042     // immaterial since this only happens when some typos were corrected.
7043     if (CorrectedTypos && Args.size() < NumParams) {
7044       if (Config)
7045         TheCall = CUDAKernelCallExpr::Create(
7046             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
7047             RParenLoc, CurFPFeatureOverrides(), NumParams);
7048       else
7049         TheCall =
7050             CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7051                              CurFPFeatureOverrides(), NumParams, UsesADL);
7052     }
7053     // We can now handle the nulled arguments for the default arguments.
7054     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
7055   }
7056 
7057   // Bail out early if calling a builtin with custom type checking.
7058   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
7059     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7060 
7061   if (getLangOpts().CUDA) {
7062     if (Config) {
7063       // CUDA: Kernel calls must be to global functions
7064       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7065         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7066             << FDecl << Fn->getSourceRange());
7067 
7068       // CUDA: Kernel function must have 'void' return type
7069       if (!FuncT->getReturnType()->isVoidType() &&
7070           !FuncT->getReturnType()->getAs<AutoType>() &&
7071           !FuncT->getReturnType()->isInstantiationDependentType())
7072         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7073             << Fn->getType() << Fn->getSourceRange());
7074     } else {
7075       // CUDA: Calls to global functions must be configured
7076       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7077         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7078             << FDecl << Fn->getSourceRange());
7079     }
7080   }
7081 
7082   // Check for a valid return type
7083   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7084                           FDecl))
7085     return ExprError();
7086 
7087   // We know the result type of the call, set it.
7088   TheCall->setType(FuncT->getCallResultType(Context));
7089   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7090 
7091   if (Proto) {
7092     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7093                                 IsExecConfig))
7094       return ExprError();
7095   } else {
7096     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7097 
7098     if (FDecl) {
7099       // Check if we have too few/too many template arguments, based
7100       // on our knowledge of the function definition.
7101       const FunctionDecl *Def = nullptr;
7102       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7103         Proto = Def->getType()->getAs<FunctionProtoType>();
7104        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7105           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7106           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7107       }
7108 
7109       // If the function we're calling isn't a function prototype, but we have
7110       // a function prototype from a prior declaratiom, use that prototype.
7111       if (!FDecl->hasPrototype())
7112         Proto = FDecl->getType()->getAs<FunctionProtoType>();
7113     }
7114 
7115     // If we still haven't found a prototype to use but there are arguments to
7116     // the call, diagnose this as calling a function without a prototype.
7117     // However, if we found a function declaration, check to see if
7118     // -Wdeprecated-non-prototype was disabled where the function was declared.
7119     // If so, we will silence the diagnostic here on the assumption that this
7120     // interface is intentional and the user knows what they're doing. We will
7121     // also silence the diagnostic if there is a function declaration but it
7122     // was implicitly defined (the user already gets diagnostics about the
7123     // creation of the implicit function declaration, so the additional warning
7124     // is not helpful).
7125     if (!Proto && !Args.empty() &&
7126         (!FDecl || (!FDecl->isImplicit() &&
7127                     !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7128                                      FDecl->getLocation()))))
7129       Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7130           << (FDecl != nullptr) << FDecl;
7131 
7132     // Promote the arguments (C99 6.5.2.2p6).
7133     for (unsigned i = 0, e = Args.size(); i != e; i++) {
7134       Expr *Arg = Args[i];
7135 
7136       if (Proto && i < Proto->getNumParams()) {
7137         InitializedEntity Entity = InitializedEntity::InitializeParameter(
7138             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7139         ExprResult ArgE =
7140             PerformCopyInitialization(Entity, SourceLocation(), Arg);
7141         if (ArgE.isInvalid())
7142           return true;
7143 
7144         Arg = ArgE.getAs<Expr>();
7145 
7146       } else {
7147         ExprResult ArgE = DefaultArgumentPromotion(Arg);
7148 
7149         if (ArgE.isInvalid())
7150           return true;
7151 
7152         Arg = ArgE.getAs<Expr>();
7153       }
7154 
7155       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7156                               diag::err_call_incomplete_argument, Arg))
7157         return ExprError();
7158 
7159       TheCall->setArg(i, Arg);
7160     }
7161     TheCall->computeDependence();
7162   }
7163 
7164   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7165     if (!Method->isStatic())
7166       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7167         << Fn->getSourceRange());
7168 
7169   // Check for sentinels
7170   if (NDecl)
7171     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7172 
7173   // Warn for unions passing across security boundary (CMSE).
7174   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7175     for (unsigned i = 0, e = Args.size(); i != e; i++) {
7176       if (const auto *RT =
7177               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7178         if (RT->getDecl()->isOrContainsUnion())
7179           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7180               << 0 << i;
7181       }
7182     }
7183   }
7184 
7185   // Do special checking on direct calls to functions.
7186   if (FDecl) {
7187     if (CheckFunctionCall(FDecl, TheCall, Proto))
7188       return ExprError();
7189 
7190     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7191 
7192     if (BuiltinID)
7193       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7194   } else if (NDecl) {
7195     if (CheckPointerCall(NDecl, TheCall, Proto))
7196       return ExprError();
7197   } else {
7198     if (CheckOtherCall(TheCall, Proto))
7199       return ExprError();
7200   }
7201 
7202   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7203 }
7204 
7205 ExprResult
7206 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7207                            SourceLocation RParenLoc, Expr *InitExpr) {
7208   assert(Ty && "ActOnCompoundLiteral(): missing type");
7209   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7210 
7211   TypeSourceInfo *TInfo;
7212   QualType literalType = GetTypeFromParser(Ty, &TInfo);
7213   if (!TInfo)
7214     TInfo = Context.getTrivialTypeSourceInfo(literalType);
7215 
7216   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7217 }
7218 
7219 ExprResult
7220 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7221                                SourceLocation RParenLoc, Expr *LiteralExpr) {
7222   QualType literalType = TInfo->getType();
7223 
7224   if (literalType->isArrayType()) {
7225     if (RequireCompleteSizedType(
7226             LParenLoc, Context.getBaseElementType(literalType),
7227             diag::err_array_incomplete_or_sizeless_type,
7228             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7229       return ExprError();
7230     if (literalType->isVariableArrayType()) {
7231       if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7232                                            diag::err_variable_object_no_init)) {
7233         return ExprError();
7234       }
7235     }
7236   } else if (!literalType->isDependentType() &&
7237              RequireCompleteType(LParenLoc, literalType,
7238                diag::err_typecheck_decl_incomplete_type,
7239                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7240     return ExprError();
7241 
7242   InitializedEntity Entity
7243     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7244   InitializationKind Kind
7245     = InitializationKind::CreateCStyleCast(LParenLoc,
7246                                            SourceRange(LParenLoc, RParenLoc),
7247                                            /*InitList=*/true);
7248   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7249   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7250                                       &literalType);
7251   if (Result.isInvalid())
7252     return ExprError();
7253   LiteralExpr = Result.get();
7254 
7255   bool isFileScope = !CurContext->isFunctionOrMethod();
7256 
7257   // In C, compound literals are l-values for some reason.
7258   // For GCC compatibility, in C++, file-scope array compound literals with
7259   // constant initializers are also l-values, and compound literals are
7260   // otherwise prvalues.
7261   //
7262   // (GCC also treats C++ list-initialized file-scope array prvalues with
7263   // constant initializers as l-values, but that's non-conforming, so we don't
7264   // follow it there.)
7265   //
7266   // FIXME: It would be better to handle the lvalue cases as materializing and
7267   // lifetime-extending a temporary object, but our materialized temporaries
7268   // representation only supports lifetime extension from a variable, not "out
7269   // of thin air".
7270   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7271   // is bound to the result of applying array-to-pointer decay to the compound
7272   // literal.
7273   // FIXME: GCC supports compound literals of reference type, which should
7274   // obviously have a value kind derived from the kind of reference involved.
7275   ExprValueKind VK =
7276       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7277           ? VK_PRValue
7278           : VK_LValue;
7279 
7280   if (isFileScope)
7281     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7282       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7283         Expr *Init = ILE->getInit(i);
7284         ILE->setInit(i, ConstantExpr::Create(Context, Init));
7285       }
7286 
7287   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7288                                               VK, LiteralExpr, isFileScope);
7289   if (isFileScope) {
7290     if (!LiteralExpr->isTypeDependent() &&
7291         !LiteralExpr->isValueDependent() &&
7292         !literalType->isDependentType()) // C99 6.5.2.5p3
7293       if (CheckForConstantInitializer(LiteralExpr, literalType))
7294         return ExprError();
7295   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7296              literalType.getAddressSpace() != LangAS::Default) {
7297     // Embedded-C extensions to C99 6.5.2.5:
7298     //   "If the compound literal occurs inside the body of a function, the
7299     //   type name shall not be qualified by an address-space qualifier."
7300     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7301       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7302     return ExprError();
7303   }
7304 
7305   if (!isFileScope && !getLangOpts().CPlusPlus) {
7306     // Compound literals that have automatic storage duration are destroyed at
7307     // the end of the scope in C; in C++, they're just temporaries.
7308 
7309     // Emit diagnostics if it is or contains a C union type that is non-trivial
7310     // to destruct.
7311     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7312       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7313                             NTCUC_CompoundLiteral, NTCUK_Destruct);
7314 
7315     // Diagnose jumps that enter or exit the lifetime of the compound literal.
7316     if (literalType.isDestructedType()) {
7317       Cleanup.setExprNeedsCleanups(true);
7318       ExprCleanupObjects.push_back(E);
7319       getCurFunction()->setHasBranchProtectedScope();
7320     }
7321   }
7322 
7323   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7324       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7325     checkNonTrivialCUnionInInitializer(E->getInitializer(),
7326                                        E->getInitializer()->getExprLoc());
7327 
7328   return MaybeBindToTemporary(E);
7329 }
7330 
7331 ExprResult
7332 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7333                     SourceLocation RBraceLoc) {
7334   // Only produce each kind of designated initialization diagnostic once.
7335   SourceLocation FirstDesignator;
7336   bool DiagnosedArrayDesignator = false;
7337   bool DiagnosedNestedDesignator = false;
7338   bool DiagnosedMixedDesignator = false;
7339 
7340   // Check that any designated initializers are syntactically valid in the
7341   // current language mode.
7342   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7343     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7344       if (FirstDesignator.isInvalid())
7345         FirstDesignator = DIE->getBeginLoc();
7346 
7347       if (!getLangOpts().CPlusPlus)
7348         break;
7349 
7350       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7351         DiagnosedNestedDesignator = true;
7352         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7353           << DIE->getDesignatorsSourceRange();
7354       }
7355 
7356       for (auto &Desig : DIE->designators()) {
7357         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7358           DiagnosedArrayDesignator = true;
7359           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7360             << Desig.getSourceRange();
7361         }
7362       }
7363 
7364       if (!DiagnosedMixedDesignator &&
7365           !isa<DesignatedInitExpr>(InitArgList[0])) {
7366         DiagnosedMixedDesignator = true;
7367         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7368           << DIE->getSourceRange();
7369         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7370           << InitArgList[0]->getSourceRange();
7371       }
7372     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7373                isa<DesignatedInitExpr>(InitArgList[0])) {
7374       DiagnosedMixedDesignator = true;
7375       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7376       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7377         << DIE->getSourceRange();
7378       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7379         << InitArgList[I]->getSourceRange();
7380     }
7381   }
7382 
7383   if (FirstDesignator.isValid()) {
7384     // Only diagnose designated initiaization as a C++20 extension if we didn't
7385     // already diagnose use of (non-C++20) C99 designator syntax.
7386     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7387         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7388       Diag(FirstDesignator, getLangOpts().CPlusPlus20
7389                                 ? diag::warn_cxx17_compat_designated_init
7390                                 : diag::ext_cxx_designated_init);
7391     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7392       Diag(FirstDesignator, diag::ext_designated_init);
7393     }
7394   }
7395 
7396   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7397 }
7398 
7399 ExprResult
7400 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7401                     SourceLocation RBraceLoc) {
7402   // Semantic analysis for initializers is done by ActOnDeclarator() and
7403   // CheckInitializer() - it requires knowledge of the object being initialized.
7404 
7405   // Immediately handle non-overload placeholders.  Overloads can be
7406   // resolved contextually, but everything else here can't.
7407   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7408     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7409       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7410 
7411       // Ignore failures; dropping the entire initializer list because
7412       // of one failure would be terrible for indexing/etc.
7413       if (result.isInvalid()) continue;
7414 
7415       InitArgList[I] = result.get();
7416     }
7417   }
7418 
7419   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7420                                                RBraceLoc);
7421   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7422   return E;
7423 }
7424 
7425 /// Do an explicit extend of the given block pointer if we're in ARC.
7426 void Sema::maybeExtendBlockObject(ExprResult &E) {
7427   assert(E.get()->getType()->isBlockPointerType());
7428   assert(E.get()->isPRValue());
7429 
7430   // Only do this in an r-value context.
7431   if (!getLangOpts().ObjCAutoRefCount) return;
7432 
7433   E = ImplicitCastExpr::Create(
7434       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7435       /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7436   Cleanup.setExprNeedsCleanups(true);
7437 }
7438 
7439 /// Prepare a conversion of the given expression to an ObjC object
7440 /// pointer type.
7441 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7442   QualType type = E.get()->getType();
7443   if (type->isObjCObjectPointerType()) {
7444     return CK_BitCast;
7445   } else if (type->isBlockPointerType()) {
7446     maybeExtendBlockObject(E);
7447     return CK_BlockPointerToObjCPointerCast;
7448   } else {
7449     assert(type->isPointerType());
7450     return CK_CPointerToObjCPointerCast;
7451   }
7452 }
7453 
7454 /// Prepares for a scalar cast, performing all the necessary stages
7455 /// except the final cast and returning the kind required.
7456 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7457   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7458   // Also, callers should have filtered out the invalid cases with
7459   // pointers.  Everything else should be possible.
7460 
7461   QualType SrcTy = Src.get()->getType();
7462   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7463     return CK_NoOp;
7464 
7465   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7466   case Type::STK_MemberPointer:
7467     llvm_unreachable("member pointer type in C");
7468 
7469   case Type::STK_CPointer:
7470   case Type::STK_BlockPointer:
7471   case Type::STK_ObjCObjectPointer:
7472     switch (DestTy->getScalarTypeKind()) {
7473     case Type::STK_CPointer: {
7474       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7475       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7476       if (SrcAS != DestAS)
7477         return CK_AddressSpaceConversion;
7478       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7479         return CK_NoOp;
7480       return CK_BitCast;
7481     }
7482     case Type::STK_BlockPointer:
7483       return (SrcKind == Type::STK_BlockPointer
7484                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7485     case Type::STK_ObjCObjectPointer:
7486       if (SrcKind == Type::STK_ObjCObjectPointer)
7487         return CK_BitCast;
7488       if (SrcKind == Type::STK_CPointer)
7489         return CK_CPointerToObjCPointerCast;
7490       maybeExtendBlockObject(Src);
7491       return CK_BlockPointerToObjCPointerCast;
7492     case Type::STK_Bool:
7493       return CK_PointerToBoolean;
7494     case Type::STK_Integral:
7495       return CK_PointerToIntegral;
7496     case Type::STK_Floating:
7497     case Type::STK_FloatingComplex:
7498     case Type::STK_IntegralComplex:
7499     case Type::STK_MemberPointer:
7500     case Type::STK_FixedPoint:
7501       llvm_unreachable("illegal cast from pointer");
7502     }
7503     llvm_unreachable("Should have returned before this");
7504 
7505   case Type::STK_FixedPoint:
7506     switch (DestTy->getScalarTypeKind()) {
7507     case Type::STK_FixedPoint:
7508       return CK_FixedPointCast;
7509     case Type::STK_Bool:
7510       return CK_FixedPointToBoolean;
7511     case Type::STK_Integral:
7512       return CK_FixedPointToIntegral;
7513     case Type::STK_Floating:
7514       return CK_FixedPointToFloating;
7515     case Type::STK_IntegralComplex:
7516     case Type::STK_FloatingComplex:
7517       Diag(Src.get()->getExprLoc(),
7518            diag::err_unimplemented_conversion_with_fixed_point_type)
7519           << DestTy;
7520       return CK_IntegralCast;
7521     case Type::STK_CPointer:
7522     case Type::STK_ObjCObjectPointer:
7523     case Type::STK_BlockPointer:
7524     case Type::STK_MemberPointer:
7525       llvm_unreachable("illegal cast to pointer type");
7526     }
7527     llvm_unreachable("Should have returned before this");
7528 
7529   case Type::STK_Bool: // casting from bool is like casting from an integer
7530   case Type::STK_Integral:
7531     switch (DestTy->getScalarTypeKind()) {
7532     case Type::STK_CPointer:
7533     case Type::STK_ObjCObjectPointer:
7534     case Type::STK_BlockPointer:
7535       if (Src.get()->isNullPointerConstant(Context,
7536                                            Expr::NPC_ValueDependentIsNull))
7537         return CK_NullToPointer;
7538       return CK_IntegralToPointer;
7539     case Type::STK_Bool:
7540       return CK_IntegralToBoolean;
7541     case Type::STK_Integral:
7542       return CK_IntegralCast;
7543     case Type::STK_Floating:
7544       return CK_IntegralToFloating;
7545     case Type::STK_IntegralComplex:
7546       Src = ImpCastExprToType(Src.get(),
7547                       DestTy->castAs<ComplexType>()->getElementType(),
7548                       CK_IntegralCast);
7549       return CK_IntegralRealToComplex;
7550     case Type::STK_FloatingComplex:
7551       Src = ImpCastExprToType(Src.get(),
7552                       DestTy->castAs<ComplexType>()->getElementType(),
7553                       CK_IntegralToFloating);
7554       return CK_FloatingRealToComplex;
7555     case Type::STK_MemberPointer:
7556       llvm_unreachable("member pointer type in C");
7557     case Type::STK_FixedPoint:
7558       return CK_IntegralToFixedPoint;
7559     }
7560     llvm_unreachable("Should have returned before this");
7561 
7562   case Type::STK_Floating:
7563     switch (DestTy->getScalarTypeKind()) {
7564     case Type::STK_Floating:
7565       return CK_FloatingCast;
7566     case Type::STK_Bool:
7567       return CK_FloatingToBoolean;
7568     case Type::STK_Integral:
7569       return CK_FloatingToIntegral;
7570     case Type::STK_FloatingComplex:
7571       Src = ImpCastExprToType(Src.get(),
7572                               DestTy->castAs<ComplexType>()->getElementType(),
7573                               CK_FloatingCast);
7574       return CK_FloatingRealToComplex;
7575     case Type::STK_IntegralComplex:
7576       Src = ImpCastExprToType(Src.get(),
7577                               DestTy->castAs<ComplexType>()->getElementType(),
7578                               CK_FloatingToIntegral);
7579       return CK_IntegralRealToComplex;
7580     case Type::STK_CPointer:
7581     case Type::STK_ObjCObjectPointer:
7582     case Type::STK_BlockPointer:
7583       llvm_unreachable("valid float->pointer cast?");
7584     case Type::STK_MemberPointer:
7585       llvm_unreachable("member pointer type in C");
7586     case Type::STK_FixedPoint:
7587       return CK_FloatingToFixedPoint;
7588     }
7589     llvm_unreachable("Should have returned before this");
7590 
7591   case Type::STK_FloatingComplex:
7592     switch (DestTy->getScalarTypeKind()) {
7593     case Type::STK_FloatingComplex:
7594       return CK_FloatingComplexCast;
7595     case Type::STK_IntegralComplex:
7596       return CK_FloatingComplexToIntegralComplex;
7597     case Type::STK_Floating: {
7598       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7599       if (Context.hasSameType(ET, DestTy))
7600         return CK_FloatingComplexToReal;
7601       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7602       return CK_FloatingCast;
7603     }
7604     case Type::STK_Bool:
7605       return CK_FloatingComplexToBoolean;
7606     case Type::STK_Integral:
7607       Src = ImpCastExprToType(Src.get(),
7608                               SrcTy->castAs<ComplexType>()->getElementType(),
7609                               CK_FloatingComplexToReal);
7610       return CK_FloatingToIntegral;
7611     case Type::STK_CPointer:
7612     case Type::STK_ObjCObjectPointer:
7613     case Type::STK_BlockPointer:
7614       llvm_unreachable("valid complex float->pointer cast?");
7615     case Type::STK_MemberPointer:
7616       llvm_unreachable("member pointer type in C");
7617     case Type::STK_FixedPoint:
7618       Diag(Src.get()->getExprLoc(),
7619            diag::err_unimplemented_conversion_with_fixed_point_type)
7620           << SrcTy;
7621       return CK_IntegralCast;
7622     }
7623     llvm_unreachable("Should have returned before this");
7624 
7625   case Type::STK_IntegralComplex:
7626     switch (DestTy->getScalarTypeKind()) {
7627     case Type::STK_FloatingComplex:
7628       return CK_IntegralComplexToFloatingComplex;
7629     case Type::STK_IntegralComplex:
7630       return CK_IntegralComplexCast;
7631     case Type::STK_Integral: {
7632       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7633       if (Context.hasSameType(ET, DestTy))
7634         return CK_IntegralComplexToReal;
7635       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7636       return CK_IntegralCast;
7637     }
7638     case Type::STK_Bool:
7639       return CK_IntegralComplexToBoolean;
7640     case Type::STK_Floating:
7641       Src = ImpCastExprToType(Src.get(),
7642                               SrcTy->castAs<ComplexType>()->getElementType(),
7643                               CK_IntegralComplexToReal);
7644       return CK_IntegralToFloating;
7645     case Type::STK_CPointer:
7646     case Type::STK_ObjCObjectPointer:
7647     case Type::STK_BlockPointer:
7648       llvm_unreachable("valid complex int->pointer cast?");
7649     case Type::STK_MemberPointer:
7650       llvm_unreachable("member pointer type in C");
7651     case Type::STK_FixedPoint:
7652       Diag(Src.get()->getExprLoc(),
7653            diag::err_unimplemented_conversion_with_fixed_point_type)
7654           << SrcTy;
7655       return CK_IntegralCast;
7656     }
7657     llvm_unreachable("Should have returned before this");
7658   }
7659 
7660   llvm_unreachable("Unhandled scalar cast");
7661 }
7662 
7663 static bool breakDownVectorType(QualType type, uint64_t &len,
7664                                 QualType &eltType) {
7665   // Vectors are simple.
7666   if (const VectorType *vecType = type->getAs<VectorType>()) {
7667     len = vecType->getNumElements();
7668     eltType = vecType->getElementType();
7669     assert(eltType->isScalarType());
7670     return true;
7671   }
7672 
7673   // We allow lax conversion to and from non-vector types, but only if
7674   // they're real types (i.e. non-complex, non-pointer scalar types).
7675   if (!type->isRealType()) return false;
7676 
7677   len = 1;
7678   eltType = type;
7679   return true;
7680 }
7681 
7682 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7683 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7684 /// allowed?
7685 ///
7686 /// This will also return false if the two given types do not make sense from
7687 /// the perspective of SVE bitcasts.
7688 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7689   assert(srcTy->isVectorType() || destTy->isVectorType());
7690 
7691   auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7692     if (!FirstType->isSizelessBuiltinType())
7693       return false;
7694 
7695     const auto *VecTy = SecondType->getAs<VectorType>();
7696     return VecTy &&
7697            VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7698   };
7699 
7700   return ValidScalableConversion(srcTy, destTy) ||
7701          ValidScalableConversion(destTy, srcTy);
7702 }
7703 
7704 /// Are the two types matrix types and do they have the same dimensions i.e.
7705 /// do they have the same number of rows and the same number of columns?
7706 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7707   if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7708     return false;
7709 
7710   const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7711   const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7712 
7713   return matSrcType->getNumRows() == matDestType->getNumRows() &&
7714          matSrcType->getNumColumns() == matDestType->getNumColumns();
7715 }
7716 
7717 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7718   assert(DestTy->isVectorType() || SrcTy->isVectorType());
7719 
7720   uint64_t SrcLen, DestLen;
7721   QualType SrcEltTy, DestEltTy;
7722   if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7723     return false;
7724   if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7725     return false;
7726 
7727   // ASTContext::getTypeSize will return the size rounded up to a
7728   // power of 2, so instead of using that, we need to use the raw
7729   // element size multiplied by the element count.
7730   uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7731   uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7732 
7733   return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7734 }
7735 
7736 /// Are the two types lax-compatible vector types?  That is, given
7737 /// that one of them is a vector, do they have equal storage sizes,
7738 /// where the storage size is the number of elements times the element
7739 /// size?
7740 ///
7741 /// This will also return false if either of the types is neither a
7742 /// vector nor a real type.
7743 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7744   assert(destTy->isVectorType() || srcTy->isVectorType());
7745 
7746   // Disallow lax conversions between scalars and ExtVectors (these
7747   // conversions are allowed for other vector types because common headers
7748   // depend on them).  Most scalar OP ExtVector cases are handled by the
7749   // splat path anyway, which does what we want (convert, not bitcast).
7750   // What this rules out for ExtVectors is crazy things like char4*float.
7751   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7752   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7753 
7754   return areVectorTypesSameSize(srcTy, destTy);
7755 }
7756 
7757 /// Is this a legal conversion between two types, one of which is
7758 /// known to be a vector type?
7759 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7760   assert(destTy->isVectorType() || srcTy->isVectorType());
7761 
7762   switch (Context.getLangOpts().getLaxVectorConversions()) {
7763   case LangOptions::LaxVectorConversionKind::None:
7764     return false;
7765 
7766   case LangOptions::LaxVectorConversionKind::Integer:
7767     if (!srcTy->isIntegralOrEnumerationType()) {
7768       auto *Vec = srcTy->getAs<VectorType>();
7769       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7770         return false;
7771     }
7772     if (!destTy->isIntegralOrEnumerationType()) {
7773       auto *Vec = destTy->getAs<VectorType>();
7774       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7775         return false;
7776     }
7777     // OK, integer (vector) -> integer (vector) bitcast.
7778     break;
7779 
7780     case LangOptions::LaxVectorConversionKind::All:
7781     break;
7782   }
7783 
7784   return areLaxCompatibleVectorTypes(srcTy, destTy);
7785 }
7786 
7787 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7788                            CastKind &Kind) {
7789   if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7790     if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7791       return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7792              << DestTy << SrcTy << R;
7793     }
7794   } else if (SrcTy->isMatrixType()) {
7795     return Diag(R.getBegin(),
7796                 diag::err_invalid_conversion_between_matrix_and_type)
7797            << SrcTy << DestTy << R;
7798   } else if (DestTy->isMatrixType()) {
7799     return Diag(R.getBegin(),
7800                 diag::err_invalid_conversion_between_matrix_and_type)
7801            << DestTy << SrcTy << R;
7802   }
7803 
7804   Kind = CK_MatrixCast;
7805   return false;
7806 }
7807 
7808 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7809                            CastKind &Kind) {
7810   assert(VectorTy->isVectorType() && "Not a vector type!");
7811 
7812   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7813     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7814       return Diag(R.getBegin(),
7815                   Ty->isVectorType() ?
7816                   diag::err_invalid_conversion_between_vectors :
7817                   diag::err_invalid_conversion_between_vector_and_integer)
7818         << VectorTy << Ty << R;
7819   } else
7820     return Diag(R.getBegin(),
7821                 diag::err_invalid_conversion_between_vector_and_scalar)
7822       << VectorTy << Ty << R;
7823 
7824   Kind = CK_BitCast;
7825   return false;
7826 }
7827 
7828 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7829   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7830 
7831   if (DestElemTy == SplattedExpr->getType())
7832     return SplattedExpr;
7833 
7834   assert(DestElemTy->isFloatingType() ||
7835          DestElemTy->isIntegralOrEnumerationType());
7836 
7837   CastKind CK;
7838   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7839     // OpenCL requires that we convert `true` boolean expressions to -1, but
7840     // only when splatting vectors.
7841     if (DestElemTy->isFloatingType()) {
7842       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7843       // in two steps: boolean to signed integral, then to floating.
7844       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7845                                                  CK_BooleanToSignedIntegral);
7846       SplattedExpr = CastExprRes.get();
7847       CK = CK_IntegralToFloating;
7848     } else {
7849       CK = CK_BooleanToSignedIntegral;
7850     }
7851   } else {
7852     ExprResult CastExprRes = SplattedExpr;
7853     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7854     if (CastExprRes.isInvalid())
7855       return ExprError();
7856     SplattedExpr = CastExprRes.get();
7857   }
7858   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7859 }
7860 
7861 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7862                                     Expr *CastExpr, CastKind &Kind) {
7863   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7864 
7865   QualType SrcTy = CastExpr->getType();
7866 
7867   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7868   // an ExtVectorType.
7869   // In OpenCL, casts between vectors of different types are not allowed.
7870   // (See OpenCL 6.2).
7871   if (SrcTy->isVectorType()) {
7872     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7873         (getLangOpts().OpenCL &&
7874          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7875       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7876         << DestTy << SrcTy << R;
7877       return ExprError();
7878     }
7879     Kind = CK_BitCast;
7880     return CastExpr;
7881   }
7882 
7883   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7884   // conversion will take place first from scalar to elt type, and then
7885   // splat from elt type to vector.
7886   if (SrcTy->isPointerType())
7887     return Diag(R.getBegin(),
7888                 diag::err_invalid_conversion_between_vector_and_scalar)
7889       << DestTy << SrcTy << R;
7890 
7891   Kind = CK_VectorSplat;
7892   return prepareVectorSplat(DestTy, CastExpr);
7893 }
7894 
7895 ExprResult
7896 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7897                     Declarator &D, ParsedType &Ty,
7898                     SourceLocation RParenLoc, Expr *CastExpr) {
7899   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7900          "ActOnCastExpr(): missing type or expr");
7901 
7902   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7903   if (D.isInvalidType())
7904     return ExprError();
7905 
7906   if (getLangOpts().CPlusPlus) {
7907     // Check that there are no default arguments (C++ only).
7908     CheckExtraCXXDefaultArguments(D);
7909   } else {
7910     // Make sure any TypoExprs have been dealt with.
7911     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7912     if (!Res.isUsable())
7913       return ExprError();
7914     CastExpr = Res.get();
7915   }
7916 
7917   checkUnusedDeclAttributes(D);
7918 
7919   QualType castType = castTInfo->getType();
7920   Ty = CreateParsedType(castType, castTInfo);
7921 
7922   bool isVectorLiteral = false;
7923 
7924   // Check for an altivec or OpenCL literal,
7925   // i.e. all the elements are integer constants.
7926   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7927   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7928   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7929        && castType->isVectorType() && (PE || PLE)) {
7930     if (PLE && PLE->getNumExprs() == 0) {
7931       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7932       return ExprError();
7933     }
7934     if (PE || PLE->getNumExprs() == 1) {
7935       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7936       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7937         isVectorLiteral = true;
7938     }
7939     else
7940       isVectorLiteral = true;
7941   }
7942 
7943   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7944   // then handle it as such.
7945   if (isVectorLiteral)
7946     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7947 
7948   // If the Expr being casted is a ParenListExpr, handle it specially.
7949   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7950   // sequence of BinOp comma operators.
7951   if (isa<ParenListExpr>(CastExpr)) {
7952     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7953     if (Result.isInvalid()) return ExprError();
7954     CastExpr = Result.get();
7955   }
7956 
7957   if (getLangOpts().CPlusPlus && !castType->isVoidType())
7958     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7959 
7960   CheckTollFreeBridgeCast(castType, CastExpr);
7961 
7962   CheckObjCBridgeRelatedCast(castType, CastExpr);
7963 
7964   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7965 
7966   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7967 }
7968 
7969 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7970                                     SourceLocation RParenLoc, Expr *E,
7971                                     TypeSourceInfo *TInfo) {
7972   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7973          "Expected paren or paren list expression");
7974 
7975   Expr **exprs;
7976   unsigned numExprs;
7977   Expr *subExpr;
7978   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7979   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7980     LiteralLParenLoc = PE->getLParenLoc();
7981     LiteralRParenLoc = PE->getRParenLoc();
7982     exprs = PE->getExprs();
7983     numExprs = PE->getNumExprs();
7984   } else { // isa<ParenExpr> by assertion at function entrance
7985     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7986     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7987     subExpr = cast<ParenExpr>(E)->getSubExpr();
7988     exprs = &subExpr;
7989     numExprs = 1;
7990   }
7991 
7992   QualType Ty = TInfo->getType();
7993   assert(Ty->isVectorType() && "Expected vector type");
7994 
7995   SmallVector<Expr *, 8> initExprs;
7996   const VectorType *VTy = Ty->castAs<VectorType>();
7997   unsigned numElems = VTy->getNumElements();
7998 
7999   // '(...)' form of vector initialization in AltiVec: the number of
8000   // initializers must be one or must match the size of the vector.
8001   // If a single value is specified in the initializer then it will be
8002   // replicated to all the components of the vector
8003   if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
8004                                  VTy->getElementType()))
8005     return ExprError();
8006   if (ShouldSplatAltivecScalarInCast(VTy)) {
8007     // The number of initializers must be one or must match the size of the
8008     // vector. If a single value is specified in the initializer then it will
8009     // be replicated to all the components of the vector
8010     if (numExprs == 1) {
8011       QualType ElemTy = VTy->getElementType();
8012       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8013       if (Literal.isInvalid())
8014         return ExprError();
8015       Literal = ImpCastExprToType(Literal.get(), ElemTy,
8016                                   PrepareScalarCast(Literal, ElemTy));
8017       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8018     }
8019     else if (numExprs < numElems) {
8020       Diag(E->getExprLoc(),
8021            diag::err_incorrect_number_of_vector_initializers);
8022       return ExprError();
8023     }
8024     else
8025       initExprs.append(exprs, exprs + numExprs);
8026   }
8027   else {
8028     // For OpenCL, when the number of initializers is a single value,
8029     // it will be replicated to all components of the vector.
8030     if (getLangOpts().OpenCL &&
8031         VTy->getVectorKind() == VectorType::GenericVector &&
8032         numExprs == 1) {
8033         QualType ElemTy = VTy->getElementType();
8034         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8035         if (Literal.isInvalid())
8036           return ExprError();
8037         Literal = ImpCastExprToType(Literal.get(), ElemTy,
8038                                     PrepareScalarCast(Literal, ElemTy));
8039         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8040     }
8041 
8042     initExprs.append(exprs, exprs + numExprs);
8043   }
8044   // FIXME: This means that pretty-printing the final AST will produce curly
8045   // braces instead of the original commas.
8046   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8047                                                    initExprs, LiteralRParenLoc);
8048   initE->setType(Ty);
8049   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8050 }
8051 
8052 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8053 /// the ParenListExpr into a sequence of comma binary operators.
8054 ExprResult
8055 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8056   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8057   if (!E)
8058     return OrigExpr;
8059 
8060   ExprResult Result(E->getExpr(0));
8061 
8062   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8063     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8064                         E->getExpr(i));
8065 
8066   if (Result.isInvalid()) return ExprError();
8067 
8068   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8069 }
8070 
8071 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8072                                     SourceLocation R,
8073                                     MultiExprArg Val) {
8074   return ParenListExpr::Create(Context, L, Val, R);
8075 }
8076 
8077 /// Emit a specialized diagnostic when one expression is a null pointer
8078 /// constant and the other is not a pointer.  Returns true if a diagnostic is
8079 /// emitted.
8080 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8081                                       SourceLocation QuestionLoc) {
8082   Expr *NullExpr = LHSExpr;
8083   Expr *NonPointerExpr = RHSExpr;
8084   Expr::NullPointerConstantKind NullKind =
8085       NullExpr->isNullPointerConstant(Context,
8086                                       Expr::NPC_ValueDependentIsNotNull);
8087 
8088   if (NullKind == Expr::NPCK_NotNull) {
8089     NullExpr = RHSExpr;
8090     NonPointerExpr = LHSExpr;
8091     NullKind =
8092         NullExpr->isNullPointerConstant(Context,
8093                                         Expr::NPC_ValueDependentIsNotNull);
8094   }
8095 
8096   if (NullKind == Expr::NPCK_NotNull)
8097     return false;
8098 
8099   if (NullKind == Expr::NPCK_ZeroExpression)
8100     return false;
8101 
8102   if (NullKind == Expr::NPCK_ZeroLiteral) {
8103     // In this case, check to make sure that we got here from a "NULL"
8104     // string in the source code.
8105     NullExpr = NullExpr->IgnoreParenImpCasts();
8106     SourceLocation loc = NullExpr->getExprLoc();
8107     if (!findMacroSpelling(loc, "NULL"))
8108       return false;
8109   }
8110 
8111   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8112   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8113       << NonPointerExpr->getType() << DiagType
8114       << NonPointerExpr->getSourceRange();
8115   return true;
8116 }
8117 
8118 /// Return false if the condition expression is valid, true otherwise.
8119 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
8120   QualType CondTy = Cond->getType();
8121 
8122   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8123   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8124     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8125       << CondTy << Cond->getSourceRange();
8126     return true;
8127   }
8128 
8129   // C99 6.5.15p2
8130   if (CondTy->isScalarType()) return false;
8131 
8132   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8133     << CondTy << Cond->getSourceRange();
8134   return true;
8135 }
8136 
8137 /// Handle when one or both operands are void type.
8138 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
8139                                          ExprResult &RHS) {
8140     Expr *LHSExpr = LHS.get();
8141     Expr *RHSExpr = RHS.get();
8142 
8143     if (!LHSExpr->getType()->isVoidType())
8144       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8145           << RHSExpr->getSourceRange();
8146     if (!RHSExpr->getType()->isVoidType())
8147       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8148           << LHSExpr->getSourceRange();
8149     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
8150     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
8151     return S.Context.VoidTy;
8152 }
8153 
8154 /// Return false if the NullExpr can be promoted to PointerTy,
8155 /// true otherwise.
8156 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8157                                         QualType PointerTy) {
8158   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8159       !NullExpr.get()->isNullPointerConstant(S.Context,
8160                                             Expr::NPC_ValueDependentIsNull))
8161     return true;
8162 
8163   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8164   return false;
8165 }
8166 
8167 /// Checks compatibility between two pointers and return the resulting
8168 /// type.
8169 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8170                                                      ExprResult &RHS,
8171                                                      SourceLocation Loc) {
8172   QualType LHSTy = LHS.get()->getType();
8173   QualType RHSTy = RHS.get()->getType();
8174 
8175   if (S.Context.hasSameType(LHSTy, RHSTy)) {
8176     // Two identical pointers types are always compatible.
8177     return LHSTy;
8178   }
8179 
8180   QualType lhptee, rhptee;
8181 
8182   // Get the pointee types.
8183   bool IsBlockPointer = false;
8184   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8185     lhptee = LHSBTy->getPointeeType();
8186     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8187     IsBlockPointer = true;
8188   } else {
8189     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8190     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8191   }
8192 
8193   // C99 6.5.15p6: If both operands are pointers to compatible types or to
8194   // differently qualified versions of compatible types, the result type is
8195   // a pointer to an appropriately qualified version of the composite
8196   // type.
8197 
8198   // Only CVR-qualifiers exist in the standard, and the differently-qualified
8199   // clause doesn't make sense for our extensions. E.g. address space 2 should
8200   // be incompatible with address space 3: they may live on different devices or
8201   // anything.
8202   Qualifiers lhQual = lhptee.getQualifiers();
8203   Qualifiers rhQual = rhptee.getQualifiers();
8204 
8205   LangAS ResultAddrSpace = LangAS::Default;
8206   LangAS LAddrSpace = lhQual.getAddressSpace();
8207   LangAS RAddrSpace = rhQual.getAddressSpace();
8208 
8209   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8210   // spaces is disallowed.
8211   if (lhQual.isAddressSpaceSupersetOf(rhQual))
8212     ResultAddrSpace = LAddrSpace;
8213   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8214     ResultAddrSpace = RAddrSpace;
8215   else {
8216     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8217         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8218         << RHS.get()->getSourceRange();
8219     return QualType();
8220   }
8221 
8222   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8223   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8224   lhQual.removeCVRQualifiers();
8225   rhQual.removeCVRQualifiers();
8226 
8227   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8228   // (C99 6.7.3) for address spaces. We assume that the check should behave in
8229   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8230   // qual types are compatible iff
8231   //  * corresponded types are compatible
8232   //  * CVR qualifiers are equal
8233   //  * address spaces are equal
8234   // Thus for conditional operator we merge CVR and address space unqualified
8235   // pointees and if there is a composite type we return a pointer to it with
8236   // merged qualifiers.
8237   LHSCastKind =
8238       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8239   RHSCastKind =
8240       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8241   lhQual.removeAddressSpace();
8242   rhQual.removeAddressSpace();
8243 
8244   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8245   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8246 
8247   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
8248 
8249   if (CompositeTy.isNull()) {
8250     // In this situation, we assume void* type. No especially good
8251     // reason, but this is what gcc does, and we do have to pick
8252     // to get a consistent AST.
8253     QualType incompatTy;
8254     incompatTy = S.Context.getPointerType(
8255         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8256     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8257     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8258 
8259     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8260     // for casts between types with incompatible address space qualifiers.
8261     // For the following code the compiler produces casts between global and
8262     // local address spaces of the corresponded innermost pointees:
8263     // local int *global *a;
8264     // global int *global *b;
8265     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8266     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8267         << LHSTy << RHSTy << LHS.get()->getSourceRange()
8268         << RHS.get()->getSourceRange();
8269 
8270     return incompatTy;
8271   }
8272 
8273   // The pointer types are compatible.
8274   // In case of OpenCL ResultTy should have the address space qualifier
8275   // which is a superset of address spaces of both the 2nd and the 3rd
8276   // operands of the conditional operator.
8277   QualType ResultTy = [&, ResultAddrSpace]() {
8278     if (S.getLangOpts().OpenCL) {
8279       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8280       CompositeQuals.setAddressSpace(ResultAddrSpace);
8281       return S.Context
8282           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8283           .withCVRQualifiers(MergedCVRQual);
8284     }
8285     return CompositeTy.withCVRQualifiers(MergedCVRQual);
8286   }();
8287   if (IsBlockPointer)
8288     ResultTy = S.Context.getBlockPointerType(ResultTy);
8289   else
8290     ResultTy = S.Context.getPointerType(ResultTy);
8291 
8292   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8293   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8294   return ResultTy;
8295 }
8296 
8297 /// Return the resulting type when the operands are both block pointers.
8298 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8299                                                           ExprResult &LHS,
8300                                                           ExprResult &RHS,
8301                                                           SourceLocation Loc) {
8302   QualType LHSTy = LHS.get()->getType();
8303   QualType RHSTy = RHS.get()->getType();
8304 
8305   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8306     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8307       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8308       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8309       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8310       return destType;
8311     }
8312     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8313       << LHSTy << RHSTy << LHS.get()->getSourceRange()
8314       << RHS.get()->getSourceRange();
8315     return QualType();
8316   }
8317 
8318   // We have 2 block pointer types.
8319   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8320 }
8321 
8322 /// Return the resulting type when the operands are both pointers.
8323 static QualType
8324 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8325                                             ExprResult &RHS,
8326                                             SourceLocation Loc) {
8327   // get the pointer types
8328   QualType LHSTy = LHS.get()->getType();
8329   QualType RHSTy = RHS.get()->getType();
8330 
8331   // get the "pointed to" types
8332   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8333   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8334 
8335   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8336   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8337     // Figure out necessary qualifiers (C99 6.5.15p6)
8338     QualType destPointee
8339       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8340     QualType destType = S.Context.getPointerType(destPointee);
8341     // Add qualifiers if necessary.
8342     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8343     // Promote to void*.
8344     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8345     return destType;
8346   }
8347   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8348     QualType destPointee
8349       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8350     QualType destType = S.Context.getPointerType(destPointee);
8351     // Add qualifiers if necessary.
8352     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8353     // Promote to void*.
8354     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8355     return destType;
8356   }
8357 
8358   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8359 }
8360 
8361 /// Return false if the first expression is not an integer and the second
8362 /// expression is not a pointer, true otherwise.
8363 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8364                                         Expr* PointerExpr, SourceLocation Loc,
8365                                         bool IsIntFirstExpr) {
8366   if (!PointerExpr->getType()->isPointerType() ||
8367       !Int.get()->getType()->isIntegerType())
8368     return false;
8369 
8370   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8371   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8372 
8373   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8374     << Expr1->getType() << Expr2->getType()
8375     << Expr1->getSourceRange() << Expr2->getSourceRange();
8376   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8377                             CK_IntegralToPointer);
8378   return true;
8379 }
8380 
8381 /// Simple conversion between integer and floating point types.
8382 ///
8383 /// Used when handling the OpenCL conditional operator where the
8384 /// condition is a vector while the other operands are scalar.
8385 ///
8386 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8387 /// types are either integer or floating type. Between the two
8388 /// operands, the type with the higher rank is defined as the "result
8389 /// type". The other operand needs to be promoted to the same type. No
8390 /// other type promotion is allowed. We cannot use
8391 /// UsualArithmeticConversions() for this purpose, since it always
8392 /// promotes promotable types.
8393 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8394                                             ExprResult &RHS,
8395                                             SourceLocation QuestionLoc) {
8396   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8397   if (LHS.isInvalid())
8398     return QualType();
8399   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8400   if (RHS.isInvalid())
8401     return QualType();
8402 
8403   // For conversion purposes, we ignore any qualifiers.
8404   // For example, "const float" and "float" are equivalent.
8405   QualType LHSType =
8406     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8407   QualType RHSType =
8408     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8409 
8410   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8411     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8412       << LHSType << LHS.get()->getSourceRange();
8413     return QualType();
8414   }
8415 
8416   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8417     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8418       << RHSType << RHS.get()->getSourceRange();
8419     return QualType();
8420   }
8421 
8422   // If both types are identical, no conversion is needed.
8423   if (LHSType == RHSType)
8424     return LHSType;
8425 
8426   // Now handle "real" floating types (i.e. float, double, long double).
8427   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8428     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8429                                  /*IsCompAssign = */ false);
8430 
8431   // Finally, we have two differing integer types.
8432   return handleIntegerConversion<doIntegralCast, doIntegralCast>
8433   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8434 }
8435 
8436 /// Convert scalar operands to a vector that matches the
8437 ///        condition in length.
8438 ///
8439 /// Used when handling the OpenCL conditional operator where the
8440 /// condition is a vector while the other operands are scalar.
8441 ///
8442 /// We first compute the "result type" for the scalar operands
8443 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8444 /// into a vector of that type where the length matches the condition
8445 /// vector type. s6.11.6 requires that the element types of the result
8446 /// and the condition must have the same number of bits.
8447 static QualType
8448 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8449                               QualType CondTy, SourceLocation QuestionLoc) {
8450   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8451   if (ResTy.isNull()) return QualType();
8452 
8453   const VectorType *CV = CondTy->getAs<VectorType>();
8454   assert(CV);
8455 
8456   // Determine the vector result type
8457   unsigned NumElements = CV->getNumElements();
8458   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8459 
8460   // Ensure that all types have the same number of bits
8461   if (S.Context.getTypeSize(CV->getElementType())
8462       != S.Context.getTypeSize(ResTy)) {
8463     // Since VectorTy is created internally, it does not pretty print
8464     // with an OpenCL name. Instead, we just print a description.
8465     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8466     SmallString<64> Str;
8467     llvm::raw_svector_ostream OS(Str);
8468     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8469     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8470       << CondTy << OS.str();
8471     return QualType();
8472   }
8473 
8474   // Convert operands to the vector result type
8475   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8476   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8477 
8478   return VectorTy;
8479 }
8480 
8481 /// Return false if this is a valid OpenCL condition vector
8482 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8483                                        SourceLocation QuestionLoc) {
8484   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8485   // integral type.
8486   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8487   assert(CondTy);
8488   QualType EleTy = CondTy->getElementType();
8489   if (EleTy->isIntegerType()) return false;
8490 
8491   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8492     << Cond->getType() << Cond->getSourceRange();
8493   return true;
8494 }
8495 
8496 /// Return false if the vector condition type and the vector
8497 ///        result type are compatible.
8498 ///
8499 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8500 /// number of elements, and their element types have the same number
8501 /// of bits.
8502 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8503                               SourceLocation QuestionLoc) {
8504   const VectorType *CV = CondTy->getAs<VectorType>();
8505   const VectorType *RV = VecResTy->getAs<VectorType>();
8506   assert(CV && RV);
8507 
8508   if (CV->getNumElements() != RV->getNumElements()) {
8509     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8510       << CondTy << VecResTy;
8511     return true;
8512   }
8513 
8514   QualType CVE = CV->getElementType();
8515   QualType RVE = RV->getElementType();
8516 
8517   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8518     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8519       << CondTy << VecResTy;
8520     return true;
8521   }
8522 
8523   return false;
8524 }
8525 
8526 /// Return the resulting type for the conditional operator in
8527 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8528 ///        s6.3.i) when the condition is a vector type.
8529 static QualType
8530 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8531                              ExprResult &LHS, ExprResult &RHS,
8532                              SourceLocation QuestionLoc) {
8533   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8534   if (Cond.isInvalid())
8535     return QualType();
8536   QualType CondTy = Cond.get()->getType();
8537 
8538   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8539     return QualType();
8540 
8541   // If either operand is a vector then find the vector type of the
8542   // result as specified in OpenCL v1.1 s6.3.i.
8543   if (LHS.get()->getType()->isVectorType() ||
8544       RHS.get()->getType()->isVectorType()) {
8545     bool IsBoolVecLang =
8546         !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8547     QualType VecResTy =
8548         S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8549                               /*isCompAssign*/ false,
8550                               /*AllowBothBool*/ true,
8551                               /*AllowBoolConversions*/ false,
8552                               /*AllowBooleanOperation*/ IsBoolVecLang,
8553                               /*ReportInvalid*/ true);
8554     if (VecResTy.isNull())
8555       return QualType();
8556     // The result type must match the condition type as specified in
8557     // OpenCL v1.1 s6.11.6.
8558     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8559       return QualType();
8560     return VecResTy;
8561   }
8562 
8563   // Both operands are scalar.
8564   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8565 }
8566 
8567 /// Return true if the Expr is block type
8568 static bool checkBlockType(Sema &S, const Expr *E) {
8569   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8570     QualType Ty = CE->getCallee()->getType();
8571     if (Ty->isBlockPointerType()) {
8572       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8573       return true;
8574     }
8575   }
8576   return false;
8577 }
8578 
8579 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8580 /// In that case, LHS = cond.
8581 /// C99 6.5.15
8582 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8583                                         ExprResult &RHS, ExprValueKind &VK,
8584                                         ExprObjectKind &OK,
8585                                         SourceLocation QuestionLoc) {
8586 
8587   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8588   if (!LHSResult.isUsable()) return QualType();
8589   LHS = LHSResult;
8590 
8591   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8592   if (!RHSResult.isUsable()) return QualType();
8593   RHS = RHSResult;
8594 
8595   // C++ is sufficiently different to merit its own checker.
8596   if (getLangOpts().CPlusPlus)
8597     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8598 
8599   VK = VK_PRValue;
8600   OK = OK_Ordinary;
8601 
8602   if (Context.isDependenceAllowed() &&
8603       (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8604        RHS.get()->isTypeDependent())) {
8605     assert(!getLangOpts().CPlusPlus);
8606     assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8607             RHS.get()->containsErrors()) &&
8608            "should only occur in error-recovery path.");
8609     return Context.DependentTy;
8610   }
8611 
8612   // The OpenCL operator with a vector condition is sufficiently
8613   // different to merit its own checker.
8614   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8615       Cond.get()->getType()->isExtVectorType())
8616     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8617 
8618   // First, check the condition.
8619   Cond = UsualUnaryConversions(Cond.get());
8620   if (Cond.isInvalid())
8621     return QualType();
8622   if (checkCondition(*this, Cond.get(), QuestionLoc))
8623     return QualType();
8624 
8625   // Now check the two expressions.
8626   if (LHS.get()->getType()->isVectorType() ||
8627       RHS.get()->getType()->isVectorType())
8628     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8629                                /*AllowBothBool*/ true,
8630                                /*AllowBoolConversions*/ false,
8631                                /*AllowBooleanOperation*/ false,
8632                                /*ReportInvalid*/ true);
8633 
8634   QualType ResTy =
8635       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8636   if (LHS.isInvalid() || RHS.isInvalid())
8637     return QualType();
8638 
8639   QualType LHSTy = LHS.get()->getType();
8640   QualType RHSTy = RHS.get()->getType();
8641 
8642   // Diagnose attempts to convert between __ibm128, __float128 and long double
8643   // where such conversions currently can't be handled.
8644   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8645     Diag(QuestionLoc,
8646          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8647       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8648     return QualType();
8649   }
8650 
8651   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8652   // selection operator (?:).
8653   if (getLangOpts().OpenCL &&
8654       ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8655     return QualType();
8656   }
8657 
8658   // If both operands have arithmetic type, do the usual arithmetic conversions
8659   // to find a common type: C99 6.5.15p3,5.
8660   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8661     // Disallow invalid arithmetic conversions, such as those between bit-
8662     // precise integers types of different sizes, or between a bit-precise
8663     // integer and another type.
8664     if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8665       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8666           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8667           << RHS.get()->getSourceRange();
8668       return QualType();
8669     }
8670 
8671     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8672     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8673 
8674     return ResTy;
8675   }
8676 
8677   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8678   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8679     return LHSTy;
8680   }
8681 
8682   // If both operands are the same structure or union type, the result is that
8683   // type.
8684   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8685     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8686       if (LHSRT->getDecl() == RHSRT->getDecl())
8687         // "If both the operands have structure or union type, the result has
8688         // that type."  This implies that CV qualifiers are dropped.
8689         return LHSTy.getUnqualifiedType();
8690     // FIXME: Type of conditional expression must be complete in C mode.
8691   }
8692 
8693   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8694   // The following || allows only one side to be void (a GCC-ism).
8695   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8696     return checkConditionalVoidType(*this, LHS, RHS);
8697   }
8698 
8699   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8700   // the type of the other operand."
8701   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8702   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8703 
8704   // All objective-c pointer type analysis is done here.
8705   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8706                                                         QuestionLoc);
8707   if (LHS.isInvalid() || RHS.isInvalid())
8708     return QualType();
8709   if (!compositeType.isNull())
8710     return compositeType;
8711 
8712 
8713   // Handle block pointer types.
8714   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8715     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8716                                                      QuestionLoc);
8717 
8718   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8719   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8720     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8721                                                        QuestionLoc);
8722 
8723   // GCC compatibility: soften pointer/integer mismatch.  Note that
8724   // null pointers have been filtered out by this point.
8725   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8726       /*IsIntFirstExpr=*/true))
8727     return RHSTy;
8728   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8729       /*IsIntFirstExpr=*/false))
8730     return LHSTy;
8731 
8732   // Allow ?: operations in which both operands have the same
8733   // built-in sizeless type.
8734   if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8735     return LHSTy;
8736 
8737   // Emit a better diagnostic if one of the expressions is a null pointer
8738   // constant and the other is not a pointer type. In this case, the user most
8739   // likely forgot to take the address of the other expression.
8740   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8741     return QualType();
8742 
8743   // Otherwise, the operands are not compatible.
8744   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8745     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8746     << RHS.get()->getSourceRange();
8747   return QualType();
8748 }
8749 
8750 /// FindCompositeObjCPointerType - Helper method to find composite type of
8751 /// two objective-c pointer types of the two input expressions.
8752 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8753                                             SourceLocation QuestionLoc) {
8754   QualType LHSTy = LHS.get()->getType();
8755   QualType RHSTy = RHS.get()->getType();
8756 
8757   // Handle things like Class and struct objc_class*.  Here we case the result
8758   // to the pseudo-builtin, because that will be implicitly cast back to the
8759   // redefinition type if an attempt is made to access its fields.
8760   if (LHSTy->isObjCClassType() &&
8761       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8762     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8763     return LHSTy;
8764   }
8765   if (RHSTy->isObjCClassType() &&
8766       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8767     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8768     return RHSTy;
8769   }
8770   // And the same for struct objc_object* / id
8771   if (LHSTy->isObjCIdType() &&
8772       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8773     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8774     return LHSTy;
8775   }
8776   if (RHSTy->isObjCIdType() &&
8777       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8778     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8779     return RHSTy;
8780   }
8781   // And the same for struct objc_selector* / SEL
8782   if (Context.isObjCSelType(LHSTy) &&
8783       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8784     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8785     return LHSTy;
8786   }
8787   if (Context.isObjCSelType(RHSTy) &&
8788       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8789     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8790     return RHSTy;
8791   }
8792   // Check constraints for Objective-C object pointers types.
8793   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8794 
8795     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8796       // Two identical object pointer types are always compatible.
8797       return LHSTy;
8798     }
8799     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8800     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8801     QualType compositeType = LHSTy;
8802 
8803     // If both operands are interfaces and either operand can be
8804     // assigned to the other, use that type as the composite
8805     // type. This allows
8806     //   xxx ? (A*) a : (B*) b
8807     // where B is a subclass of A.
8808     //
8809     // Additionally, as for assignment, if either type is 'id'
8810     // allow silent coercion. Finally, if the types are
8811     // incompatible then make sure to use 'id' as the composite
8812     // type so the result is acceptable for sending messages to.
8813 
8814     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8815     // It could return the composite type.
8816     if (!(compositeType =
8817           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8818       // Nothing more to do.
8819     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8820       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8821     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8822       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8823     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8824                 RHSOPT->isObjCQualifiedIdType()) &&
8825                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8826                                                          true)) {
8827       // Need to handle "id<xx>" explicitly.
8828       // GCC allows qualified id and any Objective-C type to devolve to
8829       // id. Currently localizing to here until clear this should be
8830       // part of ObjCQualifiedIdTypesAreCompatible.
8831       compositeType = Context.getObjCIdType();
8832     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8833       compositeType = Context.getObjCIdType();
8834     } else {
8835       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8836       << LHSTy << RHSTy
8837       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8838       QualType incompatTy = Context.getObjCIdType();
8839       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8840       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8841       return incompatTy;
8842     }
8843     // The object pointer types are compatible.
8844     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8845     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8846     return compositeType;
8847   }
8848   // Check Objective-C object pointer types and 'void *'
8849   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8850     if (getLangOpts().ObjCAutoRefCount) {
8851       // ARC forbids the implicit conversion of object pointers to 'void *',
8852       // so these types are not compatible.
8853       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8854           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8855       LHS = RHS = true;
8856       return QualType();
8857     }
8858     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8859     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8860     QualType destPointee
8861     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8862     QualType destType = Context.getPointerType(destPointee);
8863     // Add qualifiers if necessary.
8864     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8865     // Promote to void*.
8866     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8867     return destType;
8868   }
8869   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8870     if (getLangOpts().ObjCAutoRefCount) {
8871       // ARC forbids the implicit conversion of object pointers to 'void *',
8872       // so these types are not compatible.
8873       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8874           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8875       LHS = RHS = true;
8876       return QualType();
8877     }
8878     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8879     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8880     QualType destPointee
8881     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8882     QualType destType = Context.getPointerType(destPointee);
8883     // Add qualifiers if necessary.
8884     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8885     // Promote to void*.
8886     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8887     return destType;
8888   }
8889   return QualType();
8890 }
8891 
8892 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8893 /// ParenRange in parentheses.
8894 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8895                                const PartialDiagnostic &Note,
8896                                SourceRange ParenRange) {
8897   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8898   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8899       EndLoc.isValid()) {
8900     Self.Diag(Loc, Note)
8901       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8902       << FixItHint::CreateInsertion(EndLoc, ")");
8903   } else {
8904     // We can't display the parentheses, so just show the bare note.
8905     Self.Diag(Loc, Note) << ParenRange;
8906   }
8907 }
8908 
8909 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8910   return BinaryOperator::isAdditiveOp(Opc) ||
8911          BinaryOperator::isMultiplicativeOp(Opc) ||
8912          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8913   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8914   // not any of the logical operators.  Bitwise-xor is commonly used as a
8915   // logical-xor because there is no logical-xor operator.  The logical
8916   // operators, including uses of xor, have a high false positive rate for
8917   // precedence warnings.
8918 }
8919 
8920 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8921 /// expression, either using a built-in or overloaded operator,
8922 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8923 /// expression.
8924 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8925                                    Expr **RHSExprs) {
8926   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8927   E = E->IgnoreImpCasts();
8928   E = E->IgnoreConversionOperatorSingleStep();
8929   E = E->IgnoreImpCasts();
8930   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8931     E = MTE->getSubExpr();
8932     E = E->IgnoreImpCasts();
8933   }
8934 
8935   // Built-in binary operator.
8936   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8937     if (IsArithmeticOp(OP->getOpcode())) {
8938       *Opcode = OP->getOpcode();
8939       *RHSExprs = OP->getRHS();
8940       return true;
8941     }
8942   }
8943 
8944   // Overloaded operator.
8945   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8946     if (Call->getNumArgs() != 2)
8947       return false;
8948 
8949     // Make sure this is really a binary operator that is safe to pass into
8950     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8951     OverloadedOperatorKind OO = Call->getOperator();
8952     if (OO < OO_Plus || OO > OO_Arrow ||
8953         OO == OO_PlusPlus || OO == OO_MinusMinus)
8954       return false;
8955 
8956     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8957     if (IsArithmeticOp(OpKind)) {
8958       *Opcode = OpKind;
8959       *RHSExprs = Call->getArg(1);
8960       return true;
8961     }
8962   }
8963 
8964   return false;
8965 }
8966 
8967 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8968 /// or is a logical expression such as (x==y) which has int type, but is
8969 /// commonly interpreted as boolean.
8970 static bool ExprLooksBoolean(Expr *E) {
8971   E = E->IgnoreParenImpCasts();
8972 
8973   if (E->getType()->isBooleanType())
8974     return true;
8975   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8976     return OP->isComparisonOp() || OP->isLogicalOp();
8977   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8978     return OP->getOpcode() == UO_LNot;
8979   if (E->getType()->isPointerType())
8980     return true;
8981   // FIXME: What about overloaded operator calls returning "unspecified boolean
8982   // type"s (commonly pointer-to-members)?
8983 
8984   return false;
8985 }
8986 
8987 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8988 /// and binary operator are mixed in a way that suggests the programmer assumed
8989 /// the conditional operator has higher precedence, for example:
8990 /// "int x = a + someBinaryCondition ? 1 : 2".
8991 static void DiagnoseConditionalPrecedence(Sema &Self,
8992                                           SourceLocation OpLoc,
8993                                           Expr *Condition,
8994                                           Expr *LHSExpr,
8995                                           Expr *RHSExpr) {
8996   BinaryOperatorKind CondOpcode;
8997   Expr *CondRHS;
8998 
8999   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9000     return;
9001   if (!ExprLooksBoolean(CondRHS))
9002     return;
9003 
9004   // The condition is an arithmetic binary expression, with a right-
9005   // hand side that looks boolean, so warn.
9006 
9007   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9008                         ? diag::warn_precedence_bitwise_conditional
9009                         : diag::warn_precedence_conditional;
9010 
9011   Self.Diag(OpLoc, DiagID)
9012       << Condition->getSourceRange()
9013       << BinaryOperator::getOpcodeStr(CondOpcode);
9014 
9015   SuggestParentheses(
9016       Self, OpLoc,
9017       Self.PDiag(diag::note_precedence_silence)
9018           << BinaryOperator::getOpcodeStr(CondOpcode),
9019       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9020 
9021   SuggestParentheses(Self, OpLoc,
9022                      Self.PDiag(diag::note_precedence_conditional_first),
9023                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9024 }
9025 
9026 /// Compute the nullability of a conditional expression.
9027 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9028                                               QualType LHSTy, QualType RHSTy,
9029                                               ASTContext &Ctx) {
9030   if (!ResTy->isAnyPointerType())
9031     return ResTy;
9032 
9033   auto GetNullability = [&Ctx](QualType Ty) {
9034     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
9035     if (Kind) {
9036       // For our purposes, treat _Nullable_result as _Nullable.
9037       if (*Kind == NullabilityKind::NullableResult)
9038         return NullabilityKind::Nullable;
9039       return *Kind;
9040     }
9041     return NullabilityKind::Unspecified;
9042   };
9043 
9044   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9045   NullabilityKind MergedKind;
9046 
9047   // Compute nullability of a binary conditional expression.
9048   if (IsBin) {
9049     if (LHSKind == NullabilityKind::NonNull)
9050       MergedKind = NullabilityKind::NonNull;
9051     else
9052       MergedKind = RHSKind;
9053   // Compute nullability of a normal conditional expression.
9054   } else {
9055     if (LHSKind == NullabilityKind::Nullable ||
9056         RHSKind == NullabilityKind::Nullable)
9057       MergedKind = NullabilityKind::Nullable;
9058     else if (LHSKind == NullabilityKind::NonNull)
9059       MergedKind = RHSKind;
9060     else if (RHSKind == NullabilityKind::NonNull)
9061       MergedKind = LHSKind;
9062     else
9063       MergedKind = NullabilityKind::Unspecified;
9064   }
9065 
9066   // Return if ResTy already has the correct nullability.
9067   if (GetNullability(ResTy) == MergedKind)
9068     return ResTy;
9069 
9070   // Strip all nullability from ResTy.
9071   while (ResTy->getNullability(Ctx))
9072     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9073 
9074   // Create a new AttributedType with the new nullability kind.
9075   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
9076   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
9077 }
9078 
9079 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
9080 /// in the case of a the GNU conditional expr extension.
9081 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9082                                     SourceLocation ColonLoc,
9083                                     Expr *CondExpr, Expr *LHSExpr,
9084                                     Expr *RHSExpr) {
9085   if (!Context.isDependenceAllowed()) {
9086     // C cannot handle TypoExpr nodes in the condition because it
9087     // doesn't handle dependent types properly, so make sure any TypoExprs have
9088     // been dealt with before checking the operands.
9089     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9090     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9091     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9092 
9093     if (!CondResult.isUsable())
9094       return ExprError();
9095 
9096     if (LHSExpr) {
9097       if (!LHSResult.isUsable())
9098         return ExprError();
9099     }
9100 
9101     if (!RHSResult.isUsable())
9102       return ExprError();
9103 
9104     CondExpr = CondResult.get();
9105     LHSExpr = LHSResult.get();
9106     RHSExpr = RHSResult.get();
9107   }
9108 
9109   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9110   // was the condition.
9111   OpaqueValueExpr *opaqueValue = nullptr;
9112   Expr *commonExpr = nullptr;
9113   if (!LHSExpr) {
9114     commonExpr = CondExpr;
9115     // Lower out placeholder types first.  This is important so that we don't
9116     // try to capture a placeholder. This happens in few cases in C++; such
9117     // as Objective-C++'s dictionary subscripting syntax.
9118     if (commonExpr->hasPlaceholderType()) {
9119       ExprResult result = CheckPlaceholderExpr(commonExpr);
9120       if (!result.isUsable()) return ExprError();
9121       commonExpr = result.get();
9122     }
9123     // We usually want to apply unary conversions *before* saving, except
9124     // in the special case of a C++ l-value conditional.
9125     if (!(getLangOpts().CPlusPlus
9126           && !commonExpr->isTypeDependent()
9127           && commonExpr->getValueKind() == RHSExpr->getValueKind()
9128           && commonExpr->isGLValue()
9129           && commonExpr->isOrdinaryOrBitFieldObject()
9130           && RHSExpr->isOrdinaryOrBitFieldObject()
9131           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9132       ExprResult commonRes = UsualUnaryConversions(commonExpr);
9133       if (commonRes.isInvalid())
9134         return ExprError();
9135       commonExpr = commonRes.get();
9136     }
9137 
9138     // If the common expression is a class or array prvalue, materialize it
9139     // so that we can safely refer to it multiple times.
9140     if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9141                                     commonExpr->getType()->isArrayType())) {
9142       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9143       if (MatExpr.isInvalid())
9144         return ExprError();
9145       commonExpr = MatExpr.get();
9146     }
9147 
9148     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9149                                                 commonExpr->getType(),
9150                                                 commonExpr->getValueKind(),
9151                                                 commonExpr->getObjectKind(),
9152                                                 commonExpr);
9153     LHSExpr = CondExpr = opaqueValue;
9154   }
9155 
9156   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9157   ExprValueKind VK = VK_PRValue;
9158   ExprObjectKind OK = OK_Ordinary;
9159   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9160   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9161                                              VK, OK, QuestionLoc);
9162   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9163       RHS.isInvalid())
9164     return ExprError();
9165 
9166   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9167                                 RHS.get());
9168 
9169   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9170 
9171   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9172                                          Context);
9173 
9174   if (!commonExpr)
9175     return new (Context)
9176         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9177                             RHS.get(), result, VK, OK);
9178 
9179   return new (Context) BinaryConditionalOperator(
9180       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9181       ColonLoc, result, VK, OK);
9182 }
9183 
9184 // Check if we have a conversion between incompatible cmse function pointer
9185 // types, that is, a conversion between a function pointer with the
9186 // cmse_nonsecure_call attribute and one without.
9187 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9188                                           QualType ToType) {
9189   if (const auto *ToFn =
9190           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9191     if (const auto *FromFn =
9192             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9193       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9194       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9195 
9196       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9197     }
9198   }
9199   return false;
9200 }
9201 
9202 // checkPointerTypesForAssignment - This is a very tricky routine (despite
9203 // being closely modeled after the C99 spec:-). The odd characteristic of this
9204 // routine is it effectively iqnores the qualifiers on the top level pointee.
9205 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9206 // FIXME: add a couple examples in this comment.
9207 static Sema::AssignConvertType
9208 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
9209   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9210   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9211 
9212   // get the "pointed to" type (ignoring qualifiers at the top level)
9213   const Type *lhptee, *rhptee;
9214   Qualifiers lhq, rhq;
9215   std::tie(lhptee, lhq) =
9216       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9217   std::tie(rhptee, rhq) =
9218       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9219 
9220   Sema::AssignConvertType ConvTy = Sema::Compatible;
9221 
9222   // C99 6.5.16.1p1: This following citation is common to constraints
9223   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9224   // qualifiers of the type *pointed to* by the right;
9225 
9226   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9227   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9228       lhq.compatiblyIncludesObjCLifetime(rhq)) {
9229     // Ignore lifetime for further calculation.
9230     lhq.removeObjCLifetime();
9231     rhq.removeObjCLifetime();
9232   }
9233 
9234   if (!lhq.compatiblyIncludes(rhq)) {
9235     // Treat address-space mismatches as fatal.
9236     if (!lhq.isAddressSpaceSupersetOf(rhq))
9237       return Sema::IncompatiblePointerDiscardsQualifiers;
9238 
9239     // It's okay to add or remove GC or lifetime qualifiers when converting to
9240     // and from void*.
9241     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9242                         .compatiblyIncludes(
9243                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9244              && (lhptee->isVoidType() || rhptee->isVoidType()))
9245       ; // keep old
9246 
9247     // Treat lifetime mismatches as fatal.
9248     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9249       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9250 
9251     // For GCC/MS compatibility, other qualifier mismatches are treated
9252     // as still compatible in C.
9253     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9254   }
9255 
9256   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9257   // incomplete type and the other is a pointer to a qualified or unqualified
9258   // version of void...
9259   if (lhptee->isVoidType()) {
9260     if (rhptee->isIncompleteOrObjectType())
9261       return ConvTy;
9262 
9263     // As an extension, we allow cast to/from void* to function pointer.
9264     assert(rhptee->isFunctionType());
9265     return Sema::FunctionVoidPointer;
9266   }
9267 
9268   if (rhptee->isVoidType()) {
9269     if (lhptee->isIncompleteOrObjectType())
9270       return ConvTy;
9271 
9272     // As an extension, we allow cast to/from void* to function pointer.
9273     assert(lhptee->isFunctionType());
9274     return Sema::FunctionVoidPointer;
9275   }
9276 
9277   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9278   // unqualified versions of compatible types, ...
9279   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9280   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9281     // Check if the pointee types are compatible ignoring the sign.
9282     // We explicitly check for char so that we catch "char" vs
9283     // "unsigned char" on systems where "char" is unsigned.
9284     if (lhptee->isCharType())
9285       ltrans = S.Context.UnsignedCharTy;
9286     else if (lhptee->hasSignedIntegerRepresentation())
9287       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9288 
9289     if (rhptee->isCharType())
9290       rtrans = S.Context.UnsignedCharTy;
9291     else if (rhptee->hasSignedIntegerRepresentation())
9292       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9293 
9294     if (ltrans == rtrans) {
9295       // Types are compatible ignoring the sign. Qualifier incompatibility
9296       // takes priority over sign incompatibility because the sign
9297       // warning can be disabled.
9298       if (ConvTy != Sema::Compatible)
9299         return ConvTy;
9300 
9301       return Sema::IncompatiblePointerSign;
9302     }
9303 
9304     // If we are a multi-level pointer, it's possible that our issue is simply
9305     // one of qualification - e.g. char ** -> const char ** is not allowed. If
9306     // the eventual target type is the same and the pointers have the same
9307     // level of indirection, this must be the issue.
9308     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9309       do {
9310         std::tie(lhptee, lhq) =
9311           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9312         std::tie(rhptee, rhq) =
9313           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9314 
9315         // Inconsistent address spaces at this point is invalid, even if the
9316         // address spaces would be compatible.
9317         // FIXME: This doesn't catch address space mismatches for pointers of
9318         // different nesting levels, like:
9319         //   __local int *** a;
9320         //   int ** b = a;
9321         // It's not clear how to actually determine when such pointers are
9322         // invalidly incompatible.
9323         if (lhq.getAddressSpace() != rhq.getAddressSpace())
9324           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9325 
9326       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9327 
9328       if (lhptee == rhptee)
9329         return Sema::IncompatibleNestedPointerQualifiers;
9330     }
9331 
9332     // General pointer incompatibility takes priority over qualifiers.
9333     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9334       return Sema::IncompatibleFunctionPointer;
9335     return Sema::IncompatiblePointer;
9336   }
9337   if (!S.getLangOpts().CPlusPlus &&
9338       S.IsFunctionConversion(ltrans, rtrans, ltrans))
9339     return Sema::IncompatibleFunctionPointer;
9340   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9341     return Sema::IncompatibleFunctionPointer;
9342   return ConvTy;
9343 }
9344 
9345 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9346 /// block pointer types are compatible or whether a block and normal pointer
9347 /// are compatible. It is more restrict than comparing two function pointer
9348 // types.
9349 static Sema::AssignConvertType
9350 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9351                                     QualType RHSType) {
9352   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9353   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9354 
9355   QualType lhptee, rhptee;
9356 
9357   // get the "pointed to" type (ignoring qualifiers at the top level)
9358   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9359   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9360 
9361   // In C++, the types have to match exactly.
9362   if (S.getLangOpts().CPlusPlus)
9363     return Sema::IncompatibleBlockPointer;
9364 
9365   Sema::AssignConvertType ConvTy = Sema::Compatible;
9366 
9367   // For blocks we enforce that qualifiers are identical.
9368   Qualifiers LQuals = lhptee.getLocalQualifiers();
9369   Qualifiers RQuals = rhptee.getLocalQualifiers();
9370   if (S.getLangOpts().OpenCL) {
9371     LQuals.removeAddressSpace();
9372     RQuals.removeAddressSpace();
9373   }
9374   if (LQuals != RQuals)
9375     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9376 
9377   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9378   // assignment.
9379   // The current behavior is similar to C++ lambdas. A block might be
9380   // assigned to a variable iff its return type and parameters are compatible
9381   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9382   // an assignment. Presumably it should behave in way that a function pointer
9383   // assignment does in C, so for each parameter and return type:
9384   //  * CVR and address space of LHS should be a superset of CVR and address
9385   //  space of RHS.
9386   //  * unqualified types should be compatible.
9387   if (S.getLangOpts().OpenCL) {
9388     if (!S.Context.typesAreBlockPointerCompatible(
9389             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9390             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9391       return Sema::IncompatibleBlockPointer;
9392   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9393     return Sema::IncompatibleBlockPointer;
9394 
9395   return ConvTy;
9396 }
9397 
9398 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9399 /// for assignment compatibility.
9400 static Sema::AssignConvertType
9401 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9402                                    QualType RHSType) {
9403   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9404   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9405 
9406   if (LHSType->isObjCBuiltinType()) {
9407     // Class is not compatible with ObjC object pointers.
9408     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9409         !RHSType->isObjCQualifiedClassType())
9410       return Sema::IncompatiblePointer;
9411     return Sema::Compatible;
9412   }
9413   if (RHSType->isObjCBuiltinType()) {
9414     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9415         !LHSType->isObjCQualifiedClassType())
9416       return Sema::IncompatiblePointer;
9417     return Sema::Compatible;
9418   }
9419   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9420   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9421 
9422   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9423       // make an exception for id<P>
9424       !LHSType->isObjCQualifiedIdType())
9425     return Sema::CompatiblePointerDiscardsQualifiers;
9426 
9427   if (S.Context.typesAreCompatible(LHSType, RHSType))
9428     return Sema::Compatible;
9429   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9430     return Sema::IncompatibleObjCQualifiedId;
9431   return Sema::IncompatiblePointer;
9432 }
9433 
9434 Sema::AssignConvertType
9435 Sema::CheckAssignmentConstraints(SourceLocation Loc,
9436                                  QualType LHSType, QualType RHSType) {
9437   // Fake up an opaque expression.  We don't actually care about what
9438   // cast operations are required, so if CheckAssignmentConstraints
9439   // adds casts to this they'll be wasted, but fortunately that doesn't
9440   // usually happen on valid code.
9441   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9442   ExprResult RHSPtr = &RHSExpr;
9443   CastKind K;
9444 
9445   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9446 }
9447 
9448 /// This helper function returns true if QT is a vector type that has element
9449 /// type ElementType.
9450 static bool isVector(QualType QT, QualType ElementType) {
9451   if (const VectorType *VT = QT->getAs<VectorType>())
9452     return VT->getElementType().getCanonicalType() == ElementType;
9453   return false;
9454 }
9455 
9456 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9457 /// has code to accommodate several GCC extensions when type checking
9458 /// pointers. Here are some objectionable examples that GCC considers warnings:
9459 ///
9460 ///  int a, *pint;
9461 ///  short *pshort;
9462 ///  struct foo *pfoo;
9463 ///
9464 ///  pint = pshort; // warning: assignment from incompatible pointer type
9465 ///  a = pint; // warning: assignment makes integer from pointer without a cast
9466 ///  pint = a; // warning: assignment makes pointer from integer without a cast
9467 ///  pint = pfoo; // warning: assignment from incompatible pointer type
9468 ///
9469 /// As a result, the code for dealing with pointers is more complex than the
9470 /// C99 spec dictates.
9471 ///
9472 /// Sets 'Kind' for any result kind except Incompatible.
9473 Sema::AssignConvertType
9474 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9475                                  CastKind &Kind, bool ConvertRHS) {
9476   QualType RHSType = RHS.get()->getType();
9477   QualType OrigLHSType = LHSType;
9478 
9479   // Get canonical types.  We're not formatting these types, just comparing
9480   // them.
9481   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9482   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9483 
9484   // Common case: no conversion required.
9485   if (LHSType == RHSType) {
9486     Kind = CK_NoOp;
9487     return Compatible;
9488   }
9489 
9490   // If the LHS has an __auto_type, there are no additional type constraints
9491   // to be worried about.
9492   if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9493     if (AT->isGNUAutoType()) {
9494       Kind = CK_NoOp;
9495       return Compatible;
9496     }
9497   }
9498 
9499   // If we have an atomic type, try a non-atomic assignment, then just add an
9500   // atomic qualification step.
9501   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9502     Sema::AssignConvertType result =
9503       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9504     if (result != Compatible)
9505       return result;
9506     if (Kind != CK_NoOp && ConvertRHS)
9507       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9508     Kind = CK_NonAtomicToAtomic;
9509     return Compatible;
9510   }
9511 
9512   // If the left-hand side is a reference type, then we are in a
9513   // (rare!) case where we've allowed the use of references in C,
9514   // e.g., as a parameter type in a built-in function. In this case,
9515   // just make sure that the type referenced is compatible with the
9516   // right-hand side type. The caller is responsible for adjusting
9517   // LHSType so that the resulting expression does not have reference
9518   // type.
9519   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9520     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9521       Kind = CK_LValueBitCast;
9522       return Compatible;
9523     }
9524     return Incompatible;
9525   }
9526 
9527   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9528   // to the same ExtVector type.
9529   if (LHSType->isExtVectorType()) {
9530     if (RHSType->isExtVectorType())
9531       return Incompatible;
9532     if (RHSType->isArithmeticType()) {
9533       // CK_VectorSplat does T -> vector T, so first cast to the element type.
9534       if (ConvertRHS)
9535         RHS = prepareVectorSplat(LHSType, RHS.get());
9536       Kind = CK_VectorSplat;
9537       return Compatible;
9538     }
9539   }
9540 
9541   // Conversions to or from vector type.
9542   if (LHSType->isVectorType() || RHSType->isVectorType()) {
9543     if (LHSType->isVectorType() && RHSType->isVectorType()) {
9544       // Allow assignments of an AltiVec vector type to an equivalent GCC
9545       // vector type and vice versa
9546       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9547         Kind = CK_BitCast;
9548         return Compatible;
9549       }
9550 
9551       // If we are allowing lax vector conversions, and LHS and RHS are both
9552       // vectors, the total size only needs to be the same. This is a bitcast;
9553       // no bits are changed but the result type is different.
9554       if (isLaxVectorConversion(RHSType, LHSType)) {
9555         Kind = CK_BitCast;
9556         return IncompatibleVectors;
9557       }
9558     }
9559 
9560     // When the RHS comes from another lax conversion (e.g. binops between
9561     // scalars and vectors) the result is canonicalized as a vector. When the
9562     // LHS is also a vector, the lax is allowed by the condition above. Handle
9563     // the case where LHS is a scalar.
9564     if (LHSType->isScalarType()) {
9565       const VectorType *VecType = RHSType->getAs<VectorType>();
9566       if (VecType && VecType->getNumElements() == 1 &&
9567           isLaxVectorConversion(RHSType, LHSType)) {
9568         ExprResult *VecExpr = &RHS;
9569         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9570         Kind = CK_BitCast;
9571         return Compatible;
9572       }
9573     }
9574 
9575     // Allow assignments between fixed-length and sizeless SVE vectors.
9576     if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9577         (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9578       if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9579           Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9580         Kind = CK_BitCast;
9581         return Compatible;
9582       }
9583 
9584     return Incompatible;
9585   }
9586 
9587   // Diagnose attempts to convert between __ibm128, __float128 and long double
9588   // where such conversions currently can't be handled.
9589   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9590     return Incompatible;
9591 
9592   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9593   // discards the imaginary part.
9594   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9595       !LHSType->getAs<ComplexType>())
9596     return Incompatible;
9597 
9598   // Arithmetic conversions.
9599   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9600       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9601     if (ConvertRHS)
9602       Kind = PrepareScalarCast(RHS, LHSType);
9603     return Compatible;
9604   }
9605 
9606   // Conversions to normal pointers.
9607   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9608     // U* -> T*
9609     if (isa<PointerType>(RHSType)) {
9610       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9611       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9612       if (AddrSpaceL != AddrSpaceR)
9613         Kind = CK_AddressSpaceConversion;
9614       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9615         Kind = CK_NoOp;
9616       else
9617         Kind = CK_BitCast;
9618       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9619     }
9620 
9621     // int -> T*
9622     if (RHSType->isIntegerType()) {
9623       Kind = CK_IntegralToPointer; // FIXME: null?
9624       return IntToPointer;
9625     }
9626 
9627     // C pointers are not compatible with ObjC object pointers,
9628     // with two exceptions:
9629     if (isa<ObjCObjectPointerType>(RHSType)) {
9630       //  - conversions to void*
9631       if (LHSPointer->getPointeeType()->isVoidType()) {
9632         Kind = CK_BitCast;
9633         return Compatible;
9634       }
9635 
9636       //  - conversions from 'Class' to the redefinition type
9637       if (RHSType->isObjCClassType() &&
9638           Context.hasSameType(LHSType,
9639                               Context.getObjCClassRedefinitionType())) {
9640         Kind = CK_BitCast;
9641         return Compatible;
9642       }
9643 
9644       Kind = CK_BitCast;
9645       return IncompatiblePointer;
9646     }
9647 
9648     // U^ -> void*
9649     if (RHSType->getAs<BlockPointerType>()) {
9650       if (LHSPointer->getPointeeType()->isVoidType()) {
9651         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9652         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9653                                 ->getPointeeType()
9654                                 .getAddressSpace();
9655         Kind =
9656             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9657         return Compatible;
9658       }
9659     }
9660 
9661     return Incompatible;
9662   }
9663 
9664   // Conversions to block pointers.
9665   if (isa<BlockPointerType>(LHSType)) {
9666     // U^ -> T^
9667     if (RHSType->isBlockPointerType()) {
9668       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9669                               ->getPointeeType()
9670                               .getAddressSpace();
9671       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9672                               ->getPointeeType()
9673                               .getAddressSpace();
9674       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9675       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9676     }
9677 
9678     // int or null -> T^
9679     if (RHSType->isIntegerType()) {
9680       Kind = CK_IntegralToPointer; // FIXME: null
9681       return IntToBlockPointer;
9682     }
9683 
9684     // id -> T^
9685     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9686       Kind = CK_AnyPointerToBlockPointerCast;
9687       return Compatible;
9688     }
9689 
9690     // void* -> T^
9691     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9692       if (RHSPT->getPointeeType()->isVoidType()) {
9693         Kind = CK_AnyPointerToBlockPointerCast;
9694         return Compatible;
9695       }
9696 
9697     return Incompatible;
9698   }
9699 
9700   // Conversions to Objective-C pointers.
9701   if (isa<ObjCObjectPointerType>(LHSType)) {
9702     // A* -> B*
9703     if (RHSType->isObjCObjectPointerType()) {
9704       Kind = CK_BitCast;
9705       Sema::AssignConvertType result =
9706         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9707       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9708           result == Compatible &&
9709           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9710         result = IncompatibleObjCWeakRef;
9711       return result;
9712     }
9713 
9714     // int or null -> A*
9715     if (RHSType->isIntegerType()) {
9716       Kind = CK_IntegralToPointer; // FIXME: null
9717       return IntToPointer;
9718     }
9719 
9720     // In general, C pointers are not compatible with ObjC object pointers,
9721     // with two exceptions:
9722     if (isa<PointerType>(RHSType)) {
9723       Kind = CK_CPointerToObjCPointerCast;
9724 
9725       //  - conversions from 'void*'
9726       if (RHSType->isVoidPointerType()) {
9727         return Compatible;
9728       }
9729 
9730       //  - conversions to 'Class' from its redefinition type
9731       if (LHSType->isObjCClassType() &&
9732           Context.hasSameType(RHSType,
9733                               Context.getObjCClassRedefinitionType())) {
9734         return Compatible;
9735       }
9736 
9737       return IncompatiblePointer;
9738     }
9739 
9740     // Only under strict condition T^ is compatible with an Objective-C pointer.
9741     if (RHSType->isBlockPointerType() &&
9742         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9743       if (ConvertRHS)
9744         maybeExtendBlockObject(RHS);
9745       Kind = CK_BlockPointerToObjCPointerCast;
9746       return Compatible;
9747     }
9748 
9749     return Incompatible;
9750   }
9751 
9752   // Conversions from pointers that are not covered by the above.
9753   if (isa<PointerType>(RHSType)) {
9754     // T* -> _Bool
9755     if (LHSType == Context.BoolTy) {
9756       Kind = CK_PointerToBoolean;
9757       return Compatible;
9758     }
9759 
9760     // T* -> int
9761     if (LHSType->isIntegerType()) {
9762       Kind = CK_PointerToIntegral;
9763       return PointerToInt;
9764     }
9765 
9766     return Incompatible;
9767   }
9768 
9769   // Conversions from Objective-C pointers that are not covered by the above.
9770   if (isa<ObjCObjectPointerType>(RHSType)) {
9771     // T* -> _Bool
9772     if (LHSType == Context.BoolTy) {
9773       Kind = CK_PointerToBoolean;
9774       return Compatible;
9775     }
9776 
9777     // T* -> int
9778     if (LHSType->isIntegerType()) {
9779       Kind = CK_PointerToIntegral;
9780       return PointerToInt;
9781     }
9782 
9783     return Incompatible;
9784   }
9785 
9786   // struct A -> struct B
9787   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9788     if (Context.typesAreCompatible(LHSType, RHSType)) {
9789       Kind = CK_NoOp;
9790       return Compatible;
9791     }
9792   }
9793 
9794   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9795     Kind = CK_IntToOCLSampler;
9796     return Compatible;
9797   }
9798 
9799   return Incompatible;
9800 }
9801 
9802 /// Constructs a transparent union from an expression that is
9803 /// used to initialize the transparent union.
9804 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9805                                       ExprResult &EResult, QualType UnionType,
9806                                       FieldDecl *Field) {
9807   // Build an initializer list that designates the appropriate member
9808   // of the transparent union.
9809   Expr *E = EResult.get();
9810   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9811                                                    E, SourceLocation());
9812   Initializer->setType(UnionType);
9813   Initializer->setInitializedFieldInUnion(Field);
9814 
9815   // Build a compound literal constructing a value of the transparent
9816   // union type from this initializer list.
9817   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9818   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9819                                         VK_PRValue, Initializer, false);
9820 }
9821 
9822 Sema::AssignConvertType
9823 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9824                                                ExprResult &RHS) {
9825   QualType RHSType = RHS.get()->getType();
9826 
9827   // If the ArgType is a Union type, we want to handle a potential
9828   // transparent_union GCC extension.
9829   const RecordType *UT = ArgType->getAsUnionType();
9830   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9831     return Incompatible;
9832 
9833   // The field to initialize within the transparent union.
9834   RecordDecl *UD = UT->getDecl();
9835   FieldDecl *InitField = nullptr;
9836   // It's compatible if the expression matches any of the fields.
9837   for (auto *it : UD->fields()) {
9838     if (it->getType()->isPointerType()) {
9839       // If the transparent union contains a pointer type, we allow:
9840       // 1) void pointer
9841       // 2) null pointer constant
9842       if (RHSType->isPointerType())
9843         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9844           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9845           InitField = it;
9846           break;
9847         }
9848 
9849       if (RHS.get()->isNullPointerConstant(Context,
9850                                            Expr::NPC_ValueDependentIsNull)) {
9851         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9852                                 CK_NullToPointer);
9853         InitField = it;
9854         break;
9855       }
9856     }
9857 
9858     CastKind Kind;
9859     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9860           == Compatible) {
9861       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9862       InitField = it;
9863       break;
9864     }
9865   }
9866 
9867   if (!InitField)
9868     return Incompatible;
9869 
9870   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9871   return Compatible;
9872 }
9873 
9874 Sema::AssignConvertType
9875 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9876                                        bool Diagnose,
9877                                        bool DiagnoseCFAudited,
9878                                        bool ConvertRHS) {
9879   // We need to be able to tell the caller whether we diagnosed a problem, if
9880   // they ask us to issue diagnostics.
9881   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9882 
9883   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9884   // we can't avoid *all* modifications at the moment, so we need some somewhere
9885   // to put the updated value.
9886   ExprResult LocalRHS = CallerRHS;
9887   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9888 
9889   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9890     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9891       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9892           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9893         Diag(RHS.get()->getExprLoc(),
9894              diag::warn_noderef_to_dereferenceable_pointer)
9895             << RHS.get()->getSourceRange();
9896       }
9897     }
9898   }
9899 
9900   if (getLangOpts().CPlusPlus) {
9901     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9902       // C++ 5.17p3: If the left operand is not of class type, the
9903       // expression is implicitly converted (C++ 4) to the
9904       // cv-unqualified type of the left operand.
9905       QualType RHSType = RHS.get()->getType();
9906       if (Diagnose) {
9907         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9908                                         AA_Assigning);
9909       } else {
9910         ImplicitConversionSequence ICS =
9911             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9912                                   /*SuppressUserConversions=*/false,
9913                                   AllowedExplicit::None,
9914                                   /*InOverloadResolution=*/false,
9915                                   /*CStyle=*/false,
9916                                   /*AllowObjCWritebackConversion=*/false);
9917         if (ICS.isFailure())
9918           return Incompatible;
9919         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9920                                         ICS, AA_Assigning);
9921       }
9922       if (RHS.isInvalid())
9923         return Incompatible;
9924       Sema::AssignConvertType result = Compatible;
9925       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9926           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9927         result = IncompatibleObjCWeakRef;
9928       return result;
9929     }
9930 
9931     // FIXME: Currently, we fall through and treat C++ classes like C
9932     // structures.
9933     // FIXME: We also fall through for atomics; not sure what should
9934     // happen there, though.
9935   } else if (RHS.get()->getType() == Context.OverloadTy) {
9936     // As a set of extensions to C, we support overloading on functions. These
9937     // functions need to be resolved here.
9938     DeclAccessPair DAP;
9939     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9940             RHS.get(), LHSType, /*Complain=*/false, DAP))
9941       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9942     else
9943       return Incompatible;
9944   }
9945 
9946   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9947   // a null pointer constant.
9948   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9949        LHSType->isBlockPointerType()) &&
9950       RHS.get()->isNullPointerConstant(Context,
9951                                        Expr::NPC_ValueDependentIsNull)) {
9952     if (Diagnose || ConvertRHS) {
9953       CastKind Kind;
9954       CXXCastPath Path;
9955       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9956                              /*IgnoreBaseAccess=*/false, Diagnose);
9957       if (ConvertRHS)
9958         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9959     }
9960     return Compatible;
9961   }
9962 
9963   // OpenCL queue_t type assignment.
9964   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9965                                  Context, Expr::NPC_ValueDependentIsNull)) {
9966     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9967     return Compatible;
9968   }
9969 
9970   // This check seems unnatural, however it is necessary to ensure the proper
9971   // conversion of functions/arrays. If the conversion were done for all
9972   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9973   // expressions that suppress this implicit conversion (&, sizeof).
9974   //
9975   // Suppress this for references: C++ 8.5.3p5.
9976   if (!LHSType->isReferenceType()) {
9977     // FIXME: We potentially allocate here even if ConvertRHS is false.
9978     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9979     if (RHS.isInvalid())
9980       return Incompatible;
9981   }
9982   CastKind Kind;
9983   Sema::AssignConvertType result =
9984     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9985 
9986   // C99 6.5.16.1p2: The value of the right operand is converted to the
9987   // type of the assignment expression.
9988   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9989   // so that we can use references in built-in functions even in C.
9990   // The getNonReferenceType() call makes sure that the resulting expression
9991   // does not have reference type.
9992   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9993     QualType Ty = LHSType.getNonLValueExprType(Context);
9994     Expr *E = RHS.get();
9995 
9996     // Check for various Objective-C errors. If we are not reporting
9997     // diagnostics and just checking for errors, e.g., during overload
9998     // resolution, return Incompatible to indicate the failure.
9999     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10000         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
10001                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
10002       if (!Diagnose)
10003         return Incompatible;
10004     }
10005     if (getLangOpts().ObjC &&
10006         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10007                                            E->getType(), E, Diagnose) ||
10008          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10009       if (!Diagnose)
10010         return Incompatible;
10011       // Replace the expression with a corrected version and continue so we
10012       // can find further errors.
10013       RHS = E;
10014       return Compatible;
10015     }
10016 
10017     if (ConvertRHS)
10018       RHS = ImpCastExprToType(E, Ty, Kind);
10019   }
10020 
10021   return result;
10022 }
10023 
10024 namespace {
10025 /// The original operand to an operator, prior to the application of the usual
10026 /// arithmetic conversions and converting the arguments of a builtin operator
10027 /// candidate.
10028 struct OriginalOperand {
10029   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10030     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10031       Op = MTE->getSubExpr();
10032     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10033       Op = BTE->getSubExpr();
10034     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10035       Orig = ICE->getSubExprAsWritten();
10036       Conversion = ICE->getConversionFunction();
10037     }
10038   }
10039 
10040   QualType getType() const { return Orig->getType(); }
10041 
10042   Expr *Orig;
10043   NamedDecl *Conversion;
10044 };
10045 }
10046 
10047 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10048                                ExprResult &RHS) {
10049   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10050 
10051   Diag(Loc, diag::err_typecheck_invalid_operands)
10052     << OrigLHS.getType() << OrigRHS.getType()
10053     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10054 
10055   // If a user-defined conversion was applied to either of the operands prior
10056   // to applying the built-in operator rules, tell the user about it.
10057   if (OrigLHS.Conversion) {
10058     Diag(OrigLHS.Conversion->getLocation(),
10059          diag::note_typecheck_invalid_operands_converted)
10060       << 0 << LHS.get()->getType();
10061   }
10062   if (OrigRHS.Conversion) {
10063     Diag(OrigRHS.Conversion->getLocation(),
10064          diag::note_typecheck_invalid_operands_converted)
10065       << 1 << RHS.get()->getType();
10066   }
10067 
10068   return QualType();
10069 }
10070 
10071 // Diagnose cases where a scalar was implicitly converted to a vector and
10072 // diagnose the underlying types. Otherwise, diagnose the error
10073 // as invalid vector logical operands for non-C++ cases.
10074 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10075                                             ExprResult &RHS) {
10076   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10077   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10078 
10079   bool LHSNatVec = LHSType->isVectorType();
10080   bool RHSNatVec = RHSType->isVectorType();
10081 
10082   if (!(LHSNatVec && RHSNatVec)) {
10083     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10084     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10085     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10086         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10087         << Vector->getSourceRange();
10088     return QualType();
10089   }
10090 
10091   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10092       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10093       << RHS.get()->getSourceRange();
10094 
10095   return QualType();
10096 }
10097 
10098 /// Try to convert a value of non-vector type to a vector type by converting
10099 /// the type to the element type of the vector and then performing a splat.
10100 /// If the language is OpenCL, we only use conversions that promote scalar
10101 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10102 /// for float->int.
10103 ///
10104 /// OpenCL V2.0 6.2.6.p2:
10105 /// An error shall occur if any scalar operand type has greater rank
10106 /// than the type of the vector element.
10107 ///
10108 /// \param scalar - if non-null, actually perform the conversions
10109 /// \return true if the operation fails (but without diagnosing the failure)
10110 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10111                                      QualType scalarTy,
10112                                      QualType vectorEltTy,
10113                                      QualType vectorTy,
10114                                      unsigned &DiagID) {
10115   // The conversion to apply to the scalar before splatting it,
10116   // if necessary.
10117   CastKind scalarCast = CK_NoOp;
10118 
10119   if (vectorEltTy->isIntegralType(S.Context)) {
10120     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10121         (scalarTy->isIntegerType() &&
10122          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10123       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10124       return true;
10125     }
10126     if (!scalarTy->isIntegralType(S.Context))
10127       return true;
10128     scalarCast = CK_IntegralCast;
10129   } else if (vectorEltTy->isRealFloatingType()) {
10130     if (scalarTy->isRealFloatingType()) {
10131       if (S.getLangOpts().OpenCL &&
10132           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10133         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10134         return true;
10135       }
10136       scalarCast = CK_FloatingCast;
10137     }
10138     else if (scalarTy->isIntegralType(S.Context))
10139       scalarCast = CK_IntegralToFloating;
10140     else
10141       return true;
10142   } else {
10143     return true;
10144   }
10145 
10146   // Adjust scalar if desired.
10147   if (scalar) {
10148     if (scalarCast != CK_NoOp)
10149       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10150     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10151   }
10152   return false;
10153 }
10154 
10155 /// Convert vector E to a vector with the same number of elements but different
10156 /// element type.
10157 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10158   const auto *VecTy = E->getType()->getAs<VectorType>();
10159   assert(VecTy && "Expression E must be a vector");
10160   QualType NewVecTy =
10161       VecTy->isExtVectorType()
10162           ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10163           : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10164                                     VecTy->getVectorKind());
10165 
10166   // Look through the implicit cast. Return the subexpression if its type is
10167   // NewVecTy.
10168   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10169     if (ICE->getSubExpr()->getType() == NewVecTy)
10170       return ICE->getSubExpr();
10171 
10172   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10173   return S.ImpCastExprToType(E, NewVecTy, Cast);
10174 }
10175 
10176 /// Test if a (constant) integer Int can be casted to another integer type
10177 /// IntTy without losing precision.
10178 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10179                                       QualType OtherIntTy) {
10180   QualType IntTy = Int->get()->getType().getUnqualifiedType();
10181 
10182   // Reject cases where the value of the Int is unknown as that would
10183   // possibly cause truncation, but accept cases where the scalar can be
10184   // demoted without loss of precision.
10185   Expr::EvalResult EVResult;
10186   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10187   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10188   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10189   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10190 
10191   if (CstInt) {
10192     // If the scalar is constant and is of a higher order and has more active
10193     // bits that the vector element type, reject it.
10194     llvm::APSInt Result = EVResult.Val.getInt();
10195     unsigned NumBits = IntSigned
10196                            ? (Result.isNegative() ? Result.getMinSignedBits()
10197                                                   : Result.getActiveBits())
10198                            : Result.getActiveBits();
10199     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10200       return true;
10201 
10202     // If the signedness of the scalar type and the vector element type
10203     // differs and the number of bits is greater than that of the vector
10204     // element reject it.
10205     return (IntSigned != OtherIntSigned &&
10206             NumBits > S.Context.getIntWidth(OtherIntTy));
10207   }
10208 
10209   // Reject cases where the value of the scalar is not constant and it's
10210   // order is greater than that of the vector element type.
10211   return (Order < 0);
10212 }
10213 
10214 /// Test if a (constant) integer Int can be casted to floating point type
10215 /// FloatTy without losing precision.
10216 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10217                                      QualType FloatTy) {
10218   QualType IntTy = Int->get()->getType().getUnqualifiedType();
10219 
10220   // Determine if the integer constant can be expressed as a floating point
10221   // number of the appropriate type.
10222   Expr::EvalResult EVResult;
10223   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10224 
10225   uint64_t Bits = 0;
10226   if (CstInt) {
10227     // Reject constants that would be truncated if they were converted to
10228     // the floating point type. Test by simple to/from conversion.
10229     // FIXME: Ideally the conversion to an APFloat and from an APFloat
10230     //        could be avoided if there was a convertFromAPInt method
10231     //        which could signal back if implicit truncation occurred.
10232     llvm::APSInt Result = EVResult.Val.getInt();
10233     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10234     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10235                            llvm::APFloat::rmTowardZero);
10236     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10237                              !IntTy->hasSignedIntegerRepresentation());
10238     bool Ignored = false;
10239     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10240                            &Ignored);
10241     if (Result != ConvertBack)
10242       return true;
10243   } else {
10244     // Reject types that cannot be fully encoded into the mantissa of
10245     // the float.
10246     Bits = S.Context.getTypeSize(IntTy);
10247     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10248         S.Context.getFloatTypeSemantics(FloatTy));
10249     if (Bits > FloatPrec)
10250       return true;
10251   }
10252 
10253   return false;
10254 }
10255 
10256 /// Attempt to convert and splat Scalar into a vector whose types matches
10257 /// Vector following GCC conversion rules. The rule is that implicit
10258 /// conversion can occur when Scalar can be casted to match Vector's element
10259 /// type without causing truncation of Scalar.
10260 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10261                                         ExprResult *Vector) {
10262   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10263   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10264   QualType VectorEltTy;
10265 
10266   if (const auto *VT = VectorTy->getAs<VectorType>()) {
10267     assert(!isa<ExtVectorType>(VT) &&
10268            "ExtVectorTypes should not be handled here!");
10269     VectorEltTy = VT->getElementType();
10270   } else if (VectorTy->isVLSTBuiltinType()) {
10271     VectorEltTy =
10272         VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10273   } else {
10274     llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10275   }
10276 
10277   // Reject cases where the vector element type or the scalar element type are
10278   // not integral or floating point types.
10279   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10280     return true;
10281 
10282   // The conversion to apply to the scalar before splatting it,
10283   // if necessary.
10284   CastKind ScalarCast = CK_NoOp;
10285 
10286   // Accept cases where the vector elements are integers and the scalar is
10287   // an integer.
10288   // FIXME: Notionally if the scalar was a floating point value with a precise
10289   //        integral representation, we could cast it to an appropriate integer
10290   //        type and then perform the rest of the checks here. GCC will perform
10291   //        this conversion in some cases as determined by the input language.
10292   //        We should accept it on a language independent basis.
10293   if (VectorEltTy->isIntegralType(S.Context) &&
10294       ScalarTy->isIntegralType(S.Context) &&
10295       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10296 
10297     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10298       return true;
10299 
10300     ScalarCast = CK_IntegralCast;
10301   } else if (VectorEltTy->isIntegralType(S.Context) &&
10302              ScalarTy->isRealFloatingType()) {
10303     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10304       ScalarCast = CK_FloatingToIntegral;
10305     else
10306       return true;
10307   } else if (VectorEltTy->isRealFloatingType()) {
10308     if (ScalarTy->isRealFloatingType()) {
10309 
10310       // Reject cases where the scalar type is not a constant and has a higher
10311       // Order than the vector element type.
10312       llvm::APFloat Result(0.0);
10313 
10314       // Determine whether this is a constant scalar. In the event that the
10315       // value is dependent (and thus cannot be evaluated by the constant
10316       // evaluator), skip the evaluation. This will then diagnose once the
10317       // expression is instantiated.
10318       bool CstScalar = Scalar->get()->isValueDependent() ||
10319                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
10320       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10321       if (!CstScalar && Order < 0)
10322         return true;
10323 
10324       // If the scalar cannot be safely casted to the vector element type,
10325       // reject it.
10326       if (CstScalar) {
10327         bool Truncated = false;
10328         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10329                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
10330         if (Truncated)
10331           return true;
10332       }
10333 
10334       ScalarCast = CK_FloatingCast;
10335     } else if (ScalarTy->isIntegralType(S.Context)) {
10336       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10337         return true;
10338 
10339       ScalarCast = CK_IntegralToFloating;
10340     } else
10341       return true;
10342   } else if (ScalarTy->isEnumeralType())
10343     return true;
10344 
10345   // Adjust scalar if desired.
10346   if (Scalar) {
10347     if (ScalarCast != CK_NoOp)
10348       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10349     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10350   }
10351   return false;
10352 }
10353 
10354 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10355                                    SourceLocation Loc, bool IsCompAssign,
10356                                    bool AllowBothBool,
10357                                    bool AllowBoolConversions,
10358                                    bool AllowBoolOperation,
10359                                    bool ReportInvalid) {
10360   if (!IsCompAssign) {
10361     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10362     if (LHS.isInvalid())
10363       return QualType();
10364   }
10365   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10366   if (RHS.isInvalid())
10367     return QualType();
10368 
10369   // For conversion purposes, we ignore any qualifiers.
10370   // For example, "const float" and "float" are equivalent.
10371   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10372   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10373 
10374   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10375   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10376   assert(LHSVecType || RHSVecType);
10377 
10378   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10379       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10380     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10381 
10382   // AltiVec-style "vector bool op vector bool" combinations are allowed
10383   // for some operators but not others.
10384   if (!AllowBothBool &&
10385       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10386       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10387     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10388 
10389   // This operation may not be performed on boolean vectors.
10390   if (!AllowBoolOperation &&
10391       (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10392     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10393 
10394   // If the vector types are identical, return.
10395   if (Context.hasSameType(LHSType, RHSType))
10396     return LHSType;
10397 
10398   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10399   if (LHSVecType && RHSVecType &&
10400       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10401     if (isa<ExtVectorType>(LHSVecType)) {
10402       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10403       return LHSType;
10404     }
10405 
10406     if (!IsCompAssign)
10407       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10408     return RHSType;
10409   }
10410 
10411   // AllowBoolConversions says that bool and non-bool AltiVec vectors
10412   // can be mixed, with the result being the non-bool type.  The non-bool
10413   // operand must have integer element type.
10414   if (AllowBoolConversions && LHSVecType && RHSVecType &&
10415       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10416       (Context.getTypeSize(LHSVecType->getElementType()) ==
10417        Context.getTypeSize(RHSVecType->getElementType()))) {
10418     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10419         LHSVecType->getElementType()->isIntegerType() &&
10420         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10421       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10422       return LHSType;
10423     }
10424     if (!IsCompAssign &&
10425         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10426         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10427         RHSVecType->getElementType()->isIntegerType()) {
10428       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10429       return RHSType;
10430     }
10431   }
10432 
10433   // Expressions containing fixed-length and sizeless SVE vectors are invalid
10434   // since the ambiguity can affect the ABI.
10435   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10436     const VectorType *VecType = SecondType->getAs<VectorType>();
10437     return FirstType->isSizelessBuiltinType() && VecType &&
10438            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10439             VecType->getVectorKind() ==
10440                 VectorType::SveFixedLengthPredicateVector);
10441   };
10442 
10443   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10444     Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10445     return QualType();
10446   }
10447 
10448   // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10449   // since the ambiguity can affect the ABI.
10450   auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10451     const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10452     const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10453 
10454     if (FirstVecType && SecondVecType)
10455       return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10456              (SecondVecType->getVectorKind() ==
10457                   VectorType::SveFixedLengthDataVector ||
10458               SecondVecType->getVectorKind() ==
10459                   VectorType::SveFixedLengthPredicateVector);
10460 
10461     return FirstType->isSizelessBuiltinType() && SecondVecType &&
10462            SecondVecType->getVectorKind() == VectorType::GenericVector;
10463   };
10464 
10465   if (IsSveGnuConversion(LHSType, RHSType) ||
10466       IsSveGnuConversion(RHSType, LHSType)) {
10467     Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10468     return QualType();
10469   }
10470 
10471   // If there's a vector type and a scalar, try to convert the scalar to
10472   // the vector element type and splat.
10473   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10474   if (!RHSVecType) {
10475     if (isa<ExtVectorType>(LHSVecType)) {
10476       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10477                                     LHSVecType->getElementType(), LHSType,
10478                                     DiagID))
10479         return LHSType;
10480     } else {
10481       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10482         return LHSType;
10483     }
10484   }
10485   if (!LHSVecType) {
10486     if (isa<ExtVectorType>(RHSVecType)) {
10487       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10488                                     LHSType, RHSVecType->getElementType(),
10489                                     RHSType, DiagID))
10490         return RHSType;
10491     } else {
10492       if (LHS.get()->isLValue() ||
10493           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10494         return RHSType;
10495     }
10496   }
10497 
10498   // FIXME: The code below also handles conversion between vectors and
10499   // non-scalars, we should break this down into fine grained specific checks
10500   // and emit proper diagnostics.
10501   QualType VecType = LHSVecType ? LHSType : RHSType;
10502   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10503   QualType OtherType = LHSVecType ? RHSType : LHSType;
10504   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10505   if (isLaxVectorConversion(OtherType, VecType)) {
10506     // If we're allowing lax vector conversions, only the total (data) size
10507     // needs to be the same. For non compound assignment, if one of the types is
10508     // scalar, the result is always the vector type.
10509     if (!IsCompAssign) {
10510       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10511       return VecType;
10512     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10513     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10514     // type. Note that this is already done by non-compound assignments in
10515     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10516     // <1 x T> -> T. The result is also a vector type.
10517     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10518                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10519       ExprResult *RHSExpr = &RHS;
10520       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10521       return VecType;
10522     }
10523   }
10524 
10525   // Okay, the expression is invalid.
10526 
10527   // If there's a non-vector, non-real operand, diagnose that.
10528   if ((!RHSVecType && !RHSType->isRealType()) ||
10529       (!LHSVecType && !LHSType->isRealType())) {
10530     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10531       << LHSType << RHSType
10532       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10533     return QualType();
10534   }
10535 
10536   // OpenCL V1.1 6.2.6.p1:
10537   // If the operands are of more than one vector type, then an error shall
10538   // occur. Implicit conversions between vector types are not permitted, per
10539   // section 6.2.1.
10540   if (getLangOpts().OpenCL &&
10541       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10542       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10543     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10544                                                            << RHSType;
10545     return QualType();
10546   }
10547 
10548 
10549   // If there is a vector type that is not a ExtVector and a scalar, we reach
10550   // this point if scalar could not be converted to the vector's element type
10551   // without truncation.
10552   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10553       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10554     QualType Scalar = LHSVecType ? RHSType : LHSType;
10555     QualType Vector = LHSVecType ? LHSType : RHSType;
10556     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10557     Diag(Loc,
10558          diag::err_typecheck_vector_not_convertable_implict_truncation)
10559         << ScalarOrVector << Scalar << Vector;
10560 
10561     return QualType();
10562   }
10563 
10564   // Otherwise, use the generic diagnostic.
10565   Diag(Loc, DiagID)
10566     << LHSType << RHSType
10567     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10568   return QualType();
10569 }
10570 
10571 QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10572                                            SourceLocation Loc,
10573                                            bool IsCompAssign,
10574                                            ArithConvKind OperationKind) {
10575   if (!IsCompAssign) {
10576     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10577     if (LHS.isInvalid())
10578       return QualType();
10579   }
10580   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10581   if (RHS.isInvalid())
10582     return QualType();
10583 
10584   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10585   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10586 
10587   const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10588   const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10589 
10590   unsigned DiagID = diag::err_typecheck_invalid_operands;
10591   if ((OperationKind == ACK_Arithmetic) &&
10592       ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10593        (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10594     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10595                       << RHS.get()->getSourceRange();
10596     return QualType();
10597   }
10598 
10599   if (Context.hasSameType(LHSType, RHSType))
10600     return LHSType;
10601 
10602   if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) {
10603     if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10604       return LHSType;
10605   }
10606   if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) {
10607     if (LHS.get()->isLValue() ||
10608         !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10609       return RHSType;
10610   }
10611 
10612   if ((!LHSType->isVLSTBuiltinType() && !LHSType->isRealType()) ||
10613       (!RHSType->isVLSTBuiltinType() && !RHSType->isRealType())) {
10614     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10615         << LHSType << RHSType << LHS.get()->getSourceRange()
10616         << RHS.get()->getSourceRange();
10617     return QualType();
10618   }
10619 
10620   if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
10621       Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10622           Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10623     Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10624         << LHSType << RHSType << LHS.get()->getSourceRange()
10625         << RHS.get()->getSourceRange();
10626     return QualType();
10627   }
10628 
10629   if (LHSType->isVLSTBuiltinType() || RHSType->isVLSTBuiltinType()) {
10630     QualType Scalar = LHSType->isVLSTBuiltinType() ? RHSType : LHSType;
10631     QualType Vector = LHSType->isVLSTBuiltinType() ? LHSType : RHSType;
10632     bool ScalarOrVector =
10633         LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType();
10634 
10635     Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10636         << ScalarOrVector << Scalar << Vector;
10637 
10638     return QualType();
10639   }
10640 
10641   Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10642                     << RHS.get()->getSourceRange();
10643   return QualType();
10644 }
10645 
10646 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10647 // expression.  These are mainly cases where the null pointer is used as an
10648 // integer instead of a pointer.
10649 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10650                                 SourceLocation Loc, bool IsCompare) {
10651   // The canonical way to check for a GNU null is with isNullPointerConstant,
10652   // but we use a bit of a hack here for speed; this is a relatively
10653   // hot path, and isNullPointerConstant is slow.
10654   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10655   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10656 
10657   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10658 
10659   // Avoid analyzing cases where the result will either be invalid (and
10660   // diagnosed as such) or entirely valid and not something to warn about.
10661   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10662       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10663     return;
10664 
10665   // Comparison operations would not make sense with a null pointer no matter
10666   // what the other expression is.
10667   if (!IsCompare) {
10668     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10669         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10670         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10671     return;
10672   }
10673 
10674   // The rest of the operations only make sense with a null pointer
10675   // if the other expression is a pointer.
10676   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10677       NonNullType->canDecayToPointerType())
10678     return;
10679 
10680   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10681       << LHSNull /* LHS is NULL */ << NonNullType
10682       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10683 }
10684 
10685 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10686                                           SourceLocation Loc) {
10687   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10688   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10689   if (!LUE || !RUE)
10690     return;
10691   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10692       RUE->getKind() != UETT_SizeOf)
10693     return;
10694 
10695   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10696   QualType LHSTy = LHSArg->getType();
10697   QualType RHSTy;
10698 
10699   if (RUE->isArgumentType())
10700     RHSTy = RUE->getArgumentType().getNonReferenceType();
10701   else
10702     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10703 
10704   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10705     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10706       return;
10707 
10708     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10709     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10710       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10711         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10712             << LHSArgDecl;
10713     }
10714   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10715     QualType ArrayElemTy = ArrayTy->getElementType();
10716     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10717         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10718         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10719         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10720       return;
10721     S.Diag(Loc, diag::warn_division_sizeof_array)
10722         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10723     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10724       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10725         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10726             << LHSArgDecl;
10727     }
10728 
10729     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10730   }
10731 }
10732 
10733 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10734                                                ExprResult &RHS,
10735                                                SourceLocation Loc, bool IsDiv) {
10736   // Check for division/remainder by zero.
10737   Expr::EvalResult RHSValue;
10738   if (!RHS.get()->isValueDependent() &&
10739       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10740       RHSValue.Val.getInt() == 0)
10741     S.DiagRuntimeBehavior(Loc, RHS.get(),
10742                           S.PDiag(diag::warn_remainder_division_by_zero)
10743                             << IsDiv << RHS.get()->getSourceRange());
10744 }
10745 
10746 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10747                                            SourceLocation Loc,
10748                                            bool IsCompAssign, bool IsDiv) {
10749   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10750 
10751   QualType LHSTy = LHS.get()->getType();
10752   QualType RHSTy = RHS.get()->getType();
10753   if (LHSTy->isVectorType() || RHSTy->isVectorType())
10754     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10755                                /*AllowBothBool*/ getLangOpts().AltiVec,
10756                                /*AllowBoolConversions*/ false,
10757                                /*AllowBooleanOperation*/ false,
10758                                /*ReportInvalid*/ true);
10759   if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType())
10760     return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10761                                        ACK_Arithmetic);
10762   if (!IsDiv &&
10763       (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10764     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10765   // For division, only matrix-by-scalar is supported. Other combinations with
10766   // matrix types are invalid.
10767   if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10768     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10769 
10770   QualType compType = UsualArithmeticConversions(
10771       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10772   if (LHS.isInvalid() || RHS.isInvalid())
10773     return QualType();
10774 
10775 
10776   if (compType.isNull() || !compType->isArithmeticType())
10777     return InvalidOperands(Loc, LHS, RHS);
10778   if (IsDiv) {
10779     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10780     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10781   }
10782   return compType;
10783 }
10784 
10785 QualType Sema::CheckRemainderOperands(
10786   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10787   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10788 
10789   if (LHS.get()->getType()->isVectorType() ||
10790       RHS.get()->getType()->isVectorType()) {
10791     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10792         RHS.get()->getType()->hasIntegerRepresentation())
10793       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10794                                  /*AllowBothBool*/ getLangOpts().AltiVec,
10795                                  /*AllowBoolConversions*/ false,
10796                                  /*AllowBooleanOperation*/ false,
10797                                  /*ReportInvalid*/ true);
10798     return InvalidOperands(Loc, LHS, RHS);
10799   }
10800 
10801   if (LHS.get()->getType()->isVLSTBuiltinType() ||
10802       RHS.get()->getType()->isVLSTBuiltinType()) {
10803     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10804         RHS.get()->getType()->hasIntegerRepresentation())
10805       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10806                                          ACK_Arithmetic);
10807 
10808     return InvalidOperands(Loc, LHS, RHS);
10809   }
10810 
10811   QualType compType = UsualArithmeticConversions(
10812       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10813   if (LHS.isInvalid() || RHS.isInvalid())
10814     return QualType();
10815 
10816   if (compType.isNull() || !compType->isIntegerType())
10817     return InvalidOperands(Loc, LHS, RHS);
10818   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10819   return compType;
10820 }
10821 
10822 /// Diagnose invalid arithmetic on two void pointers.
10823 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10824                                                 Expr *LHSExpr, Expr *RHSExpr) {
10825   S.Diag(Loc, S.getLangOpts().CPlusPlus
10826                 ? diag::err_typecheck_pointer_arith_void_type
10827                 : diag::ext_gnu_void_ptr)
10828     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10829                             << RHSExpr->getSourceRange();
10830 }
10831 
10832 /// Diagnose invalid arithmetic on a void pointer.
10833 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10834                                             Expr *Pointer) {
10835   S.Diag(Loc, S.getLangOpts().CPlusPlus
10836                 ? diag::err_typecheck_pointer_arith_void_type
10837                 : diag::ext_gnu_void_ptr)
10838     << 0 /* one pointer */ << Pointer->getSourceRange();
10839 }
10840 
10841 /// Diagnose invalid arithmetic on a null pointer.
10842 ///
10843 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10844 /// idiom, which we recognize as a GNU extension.
10845 ///
10846 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10847                                             Expr *Pointer, bool IsGNUIdiom) {
10848   if (IsGNUIdiom)
10849     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10850       << Pointer->getSourceRange();
10851   else
10852     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10853       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10854 }
10855 
10856 /// Diagnose invalid subraction on a null pointer.
10857 ///
10858 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10859                                              Expr *Pointer, bool BothNull) {
10860   // Null - null is valid in C++ [expr.add]p7
10861   if (BothNull && S.getLangOpts().CPlusPlus)
10862     return;
10863 
10864   // Is this s a macro from a system header?
10865   if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10866     return;
10867 
10868   S.DiagRuntimeBehavior(Loc, Pointer,
10869                         S.PDiag(diag::warn_pointer_sub_null_ptr)
10870                             << S.getLangOpts().CPlusPlus
10871                             << Pointer->getSourceRange());
10872 }
10873 
10874 /// Diagnose invalid arithmetic on two function pointers.
10875 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10876                                                     Expr *LHS, Expr *RHS) {
10877   assert(LHS->getType()->isAnyPointerType());
10878   assert(RHS->getType()->isAnyPointerType());
10879   S.Diag(Loc, S.getLangOpts().CPlusPlus
10880                 ? diag::err_typecheck_pointer_arith_function_type
10881                 : diag::ext_gnu_ptr_func_arith)
10882     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10883     // We only show the second type if it differs from the first.
10884     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10885                                                    RHS->getType())
10886     << RHS->getType()->getPointeeType()
10887     << LHS->getSourceRange() << RHS->getSourceRange();
10888 }
10889 
10890 /// Diagnose invalid arithmetic on a function pointer.
10891 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10892                                                 Expr *Pointer) {
10893   assert(Pointer->getType()->isAnyPointerType());
10894   S.Diag(Loc, S.getLangOpts().CPlusPlus
10895                 ? diag::err_typecheck_pointer_arith_function_type
10896                 : diag::ext_gnu_ptr_func_arith)
10897     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10898     << 0 /* one pointer, so only one type */
10899     << Pointer->getSourceRange();
10900 }
10901 
10902 /// Emit error if Operand is incomplete pointer type
10903 ///
10904 /// \returns True if pointer has incomplete type
10905 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10906                                                  Expr *Operand) {
10907   QualType ResType = Operand->getType();
10908   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10909     ResType = ResAtomicType->getValueType();
10910 
10911   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10912   QualType PointeeTy = ResType->getPointeeType();
10913   return S.RequireCompleteSizedType(
10914       Loc, PointeeTy,
10915       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10916       Operand->getSourceRange());
10917 }
10918 
10919 /// Check the validity of an arithmetic pointer operand.
10920 ///
10921 /// If the operand has pointer type, this code will check for pointer types
10922 /// which are invalid in arithmetic operations. These will be diagnosed
10923 /// appropriately, including whether or not the use is supported as an
10924 /// extension.
10925 ///
10926 /// \returns True when the operand is valid to use (even if as an extension).
10927 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10928                                             Expr *Operand) {
10929   QualType ResType = Operand->getType();
10930   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10931     ResType = ResAtomicType->getValueType();
10932 
10933   if (!ResType->isAnyPointerType()) return true;
10934 
10935   QualType PointeeTy = ResType->getPointeeType();
10936   if (PointeeTy->isVoidType()) {
10937     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10938     return !S.getLangOpts().CPlusPlus;
10939   }
10940   if (PointeeTy->isFunctionType()) {
10941     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10942     return !S.getLangOpts().CPlusPlus;
10943   }
10944 
10945   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10946 
10947   return true;
10948 }
10949 
10950 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10951 /// operands.
10952 ///
10953 /// This routine will diagnose any invalid arithmetic on pointer operands much
10954 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10955 /// for emitting a single diagnostic even for operations where both LHS and RHS
10956 /// are (potentially problematic) pointers.
10957 ///
10958 /// \returns True when the operand is valid to use (even if as an extension).
10959 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10960                                                 Expr *LHSExpr, Expr *RHSExpr) {
10961   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10962   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10963   if (!isLHSPointer && !isRHSPointer) return true;
10964 
10965   QualType LHSPointeeTy, RHSPointeeTy;
10966   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10967   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10968 
10969   // if both are pointers check if operation is valid wrt address spaces
10970   if (isLHSPointer && isRHSPointer) {
10971     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10972       S.Diag(Loc,
10973              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10974           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10975           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10976       return false;
10977     }
10978   }
10979 
10980   // Check for arithmetic on pointers to incomplete types.
10981   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10982   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10983   if (isLHSVoidPtr || isRHSVoidPtr) {
10984     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10985     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10986     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10987 
10988     return !S.getLangOpts().CPlusPlus;
10989   }
10990 
10991   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10992   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10993   if (isLHSFuncPtr || isRHSFuncPtr) {
10994     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10995     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10996                                                                 RHSExpr);
10997     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10998 
10999     return !S.getLangOpts().CPlusPlus;
11000   }
11001 
11002   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11003     return false;
11004   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11005     return false;
11006 
11007   return true;
11008 }
11009 
11010 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11011 /// literal.
11012 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11013                                   Expr *LHSExpr, Expr *RHSExpr) {
11014   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11015   Expr* IndexExpr = RHSExpr;
11016   if (!StrExpr) {
11017     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11018     IndexExpr = LHSExpr;
11019   }
11020 
11021   bool IsStringPlusInt = StrExpr &&
11022       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11023   if (!IsStringPlusInt || IndexExpr->isValueDependent())
11024     return;
11025 
11026   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11027   Self.Diag(OpLoc, diag::warn_string_plus_int)
11028       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11029 
11030   // Only print a fixit for "str" + int, not for int + "str".
11031   if (IndexExpr == RHSExpr) {
11032     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11033     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11034         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11035         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11036         << FixItHint::CreateInsertion(EndLoc, "]");
11037   } else
11038     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11039 }
11040 
11041 /// Emit a warning when adding a char literal to a string.
11042 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11043                                    Expr *LHSExpr, Expr *RHSExpr) {
11044   const Expr *StringRefExpr = LHSExpr;
11045   const CharacterLiteral *CharExpr =
11046       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11047 
11048   if (!CharExpr) {
11049     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11050     StringRefExpr = RHSExpr;
11051   }
11052 
11053   if (!CharExpr || !StringRefExpr)
11054     return;
11055 
11056   const QualType StringType = StringRefExpr->getType();
11057 
11058   // Return if not a PointerType.
11059   if (!StringType->isAnyPointerType())
11060     return;
11061 
11062   // Return if not a CharacterType.
11063   if (!StringType->getPointeeType()->isAnyCharacterType())
11064     return;
11065 
11066   ASTContext &Ctx = Self.getASTContext();
11067   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11068 
11069   const QualType CharType = CharExpr->getType();
11070   if (!CharType->isAnyCharacterType() &&
11071       CharType->isIntegerType() &&
11072       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11073     Self.Diag(OpLoc, diag::warn_string_plus_char)
11074         << DiagRange << Ctx.CharTy;
11075   } else {
11076     Self.Diag(OpLoc, diag::warn_string_plus_char)
11077         << DiagRange << CharExpr->getType();
11078   }
11079 
11080   // Only print a fixit for str + char, not for char + str.
11081   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11082     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11083     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11084         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11085         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11086         << FixItHint::CreateInsertion(EndLoc, "]");
11087   } else {
11088     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11089   }
11090 }
11091 
11092 /// Emit error when two pointers are incompatible.
11093 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11094                                            Expr *LHSExpr, Expr *RHSExpr) {
11095   assert(LHSExpr->getType()->isAnyPointerType());
11096   assert(RHSExpr->getType()->isAnyPointerType());
11097   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11098     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11099     << RHSExpr->getSourceRange();
11100 }
11101 
11102 // C99 6.5.6
11103 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11104                                      SourceLocation Loc, BinaryOperatorKind Opc,
11105                                      QualType* CompLHSTy) {
11106   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11107 
11108   if (LHS.get()->getType()->isVectorType() ||
11109       RHS.get()->getType()->isVectorType()) {
11110     QualType compType =
11111         CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11112                             /*AllowBothBool*/ getLangOpts().AltiVec,
11113                             /*AllowBoolConversions*/ getLangOpts().ZVector,
11114                             /*AllowBooleanOperation*/ false,
11115                             /*ReportInvalid*/ true);
11116     if (CompLHSTy) *CompLHSTy = compType;
11117     return compType;
11118   }
11119 
11120   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11121       RHS.get()->getType()->isVLSTBuiltinType()) {
11122     QualType compType =
11123         CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11124     if (CompLHSTy)
11125       *CompLHSTy = compType;
11126     return compType;
11127   }
11128 
11129   if (LHS.get()->getType()->isConstantMatrixType() ||
11130       RHS.get()->getType()->isConstantMatrixType()) {
11131     QualType compType =
11132         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11133     if (CompLHSTy)
11134       *CompLHSTy = compType;
11135     return compType;
11136   }
11137 
11138   QualType compType = UsualArithmeticConversions(
11139       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11140   if (LHS.isInvalid() || RHS.isInvalid())
11141     return QualType();
11142 
11143   // Diagnose "string literal" '+' int and string '+' "char literal".
11144   if (Opc == BO_Add) {
11145     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11146     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11147   }
11148 
11149   // handle the common case first (both operands are arithmetic).
11150   if (!compType.isNull() && compType->isArithmeticType()) {
11151     if (CompLHSTy) *CompLHSTy = compType;
11152     return compType;
11153   }
11154 
11155   // Type-checking.  Ultimately the pointer's going to be in PExp;
11156   // note that we bias towards the LHS being the pointer.
11157   Expr *PExp = LHS.get(), *IExp = RHS.get();
11158 
11159   bool isObjCPointer;
11160   if (PExp->getType()->isPointerType()) {
11161     isObjCPointer = false;
11162   } else if (PExp->getType()->isObjCObjectPointerType()) {
11163     isObjCPointer = true;
11164   } else {
11165     std::swap(PExp, IExp);
11166     if (PExp->getType()->isPointerType()) {
11167       isObjCPointer = false;
11168     } else if (PExp->getType()->isObjCObjectPointerType()) {
11169       isObjCPointer = true;
11170     } else {
11171       return InvalidOperands(Loc, LHS, RHS);
11172     }
11173   }
11174   assert(PExp->getType()->isAnyPointerType());
11175 
11176   if (!IExp->getType()->isIntegerType())
11177     return InvalidOperands(Loc, LHS, RHS);
11178 
11179   // Adding to a null pointer results in undefined behavior.
11180   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11181           Context, Expr::NPC_ValueDependentIsNotNull)) {
11182     // In C++ adding zero to a null pointer is defined.
11183     Expr::EvalResult KnownVal;
11184     if (!getLangOpts().CPlusPlus ||
11185         (!IExp->isValueDependent() &&
11186          (!IExp->EvaluateAsInt(KnownVal, Context) ||
11187           KnownVal.Val.getInt() != 0))) {
11188       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11189       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11190           Context, BO_Add, PExp, IExp);
11191       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11192     }
11193   }
11194 
11195   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11196     return QualType();
11197 
11198   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11199     return QualType();
11200 
11201   // Check array bounds for pointer arithemtic
11202   CheckArrayAccess(PExp, IExp);
11203 
11204   if (CompLHSTy) {
11205     QualType LHSTy = Context.isPromotableBitField(LHS.get());
11206     if (LHSTy.isNull()) {
11207       LHSTy = LHS.get()->getType();
11208       if (LHSTy->isPromotableIntegerType())
11209         LHSTy = Context.getPromotedIntegerType(LHSTy);
11210     }
11211     *CompLHSTy = LHSTy;
11212   }
11213 
11214   return PExp->getType();
11215 }
11216 
11217 // C99 6.5.6
11218 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11219                                         SourceLocation Loc,
11220                                         QualType* CompLHSTy) {
11221   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11222 
11223   if (LHS.get()->getType()->isVectorType() ||
11224       RHS.get()->getType()->isVectorType()) {
11225     QualType compType =
11226         CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11227                             /*AllowBothBool*/ getLangOpts().AltiVec,
11228                             /*AllowBoolConversions*/ getLangOpts().ZVector,
11229                             /*AllowBooleanOperation*/ false,
11230                             /*ReportInvalid*/ true);
11231     if (CompLHSTy) *CompLHSTy = compType;
11232     return compType;
11233   }
11234 
11235   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11236       RHS.get()->getType()->isVLSTBuiltinType()) {
11237     QualType compType =
11238         CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11239     if (CompLHSTy)
11240       *CompLHSTy = compType;
11241     return compType;
11242   }
11243 
11244   if (LHS.get()->getType()->isConstantMatrixType() ||
11245       RHS.get()->getType()->isConstantMatrixType()) {
11246     QualType compType =
11247         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11248     if (CompLHSTy)
11249       *CompLHSTy = compType;
11250     return compType;
11251   }
11252 
11253   QualType compType = UsualArithmeticConversions(
11254       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11255   if (LHS.isInvalid() || RHS.isInvalid())
11256     return QualType();
11257 
11258   // Enforce type constraints: C99 6.5.6p3.
11259 
11260   // Handle the common case first (both operands are arithmetic).
11261   if (!compType.isNull() && compType->isArithmeticType()) {
11262     if (CompLHSTy) *CompLHSTy = compType;
11263     return compType;
11264   }
11265 
11266   // Either ptr - int   or   ptr - ptr.
11267   if (LHS.get()->getType()->isAnyPointerType()) {
11268     QualType lpointee = LHS.get()->getType()->getPointeeType();
11269 
11270     // Diagnose bad cases where we step over interface counts.
11271     if (LHS.get()->getType()->isObjCObjectPointerType() &&
11272         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11273       return QualType();
11274 
11275     // The result type of a pointer-int computation is the pointer type.
11276     if (RHS.get()->getType()->isIntegerType()) {
11277       // Subtracting from a null pointer should produce a warning.
11278       // The last argument to the diagnose call says this doesn't match the
11279       // GNU int-to-pointer idiom.
11280       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11281                                            Expr::NPC_ValueDependentIsNotNull)) {
11282         // In C++ adding zero to a null pointer is defined.
11283         Expr::EvalResult KnownVal;
11284         if (!getLangOpts().CPlusPlus ||
11285             (!RHS.get()->isValueDependent() &&
11286              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11287               KnownVal.Val.getInt() != 0))) {
11288           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11289         }
11290       }
11291 
11292       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11293         return QualType();
11294 
11295       // Check array bounds for pointer arithemtic
11296       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11297                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11298 
11299       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11300       return LHS.get()->getType();
11301     }
11302 
11303     // Handle pointer-pointer subtractions.
11304     if (const PointerType *RHSPTy
11305           = RHS.get()->getType()->getAs<PointerType>()) {
11306       QualType rpointee = RHSPTy->getPointeeType();
11307 
11308       if (getLangOpts().CPlusPlus) {
11309         // Pointee types must be the same: C++ [expr.add]
11310         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11311           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11312         }
11313       } else {
11314         // Pointee types must be compatible C99 6.5.6p3
11315         if (!Context.typesAreCompatible(
11316                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11317                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11318           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11319           return QualType();
11320         }
11321       }
11322 
11323       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11324                                                LHS.get(), RHS.get()))
11325         return QualType();
11326 
11327       bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11328           Context, Expr::NPC_ValueDependentIsNotNull);
11329       bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11330           Context, Expr::NPC_ValueDependentIsNotNull);
11331 
11332       // Subtracting nullptr or from nullptr is suspect
11333       if (LHSIsNullPtr)
11334         diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11335       if (RHSIsNullPtr)
11336         diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11337 
11338       // The pointee type may have zero size.  As an extension, a structure or
11339       // union may have zero size or an array may have zero length.  In this
11340       // case subtraction does not make sense.
11341       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11342         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11343         if (ElementSize.isZero()) {
11344           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11345             << rpointee.getUnqualifiedType()
11346             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11347         }
11348       }
11349 
11350       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11351       return Context.getPointerDiffType();
11352     }
11353   }
11354 
11355   return InvalidOperands(Loc, LHS, RHS);
11356 }
11357 
11358 static bool isScopedEnumerationType(QualType T) {
11359   if (const EnumType *ET = T->getAs<EnumType>())
11360     return ET->getDecl()->isScoped();
11361   return false;
11362 }
11363 
11364 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11365                                    SourceLocation Loc, BinaryOperatorKind Opc,
11366                                    QualType LHSType) {
11367   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11368   // so skip remaining warnings as we don't want to modify values within Sema.
11369   if (S.getLangOpts().OpenCL)
11370     return;
11371 
11372   // Check right/shifter operand
11373   Expr::EvalResult RHSResult;
11374   if (RHS.get()->isValueDependent() ||
11375       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11376     return;
11377   llvm::APSInt Right = RHSResult.Val.getInt();
11378 
11379   if (Right.isNegative()) {
11380     S.DiagRuntimeBehavior(Loc, RHS.get(),
11381                           S.PDiag(diag::warn_shift_negative)
11382                             << RHS.get()->getSourceRange());
11383     return;
11384   }
11385 
11386   QualType LHSExprType = LHS.get()->getType();
11387   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11388   if (LHSExprType->isBitIntType())
11389     LeftSize = S.Context.getIntWidth(LHSExprType);
11390   else if (LHSExprType->isFixedPointType()) {
11391     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11392     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11393   }
11394   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11395   if (Right.uge(LeftBits)) {
11396     S.DiagRuntimeBehavior(Loc, RHS.get(),
11397                           S.PDiag(diag::warn_shift_gt_typewidth)
11398                             << RHS.get()->getSourceRange());
11399     return;
11400   }
11401 
11402   // FIXME: We probably need to handle fixed point types specially here.
11403   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11404     return;
11405 
11406   // When left shifting an ICE which is signed, we can check for overflow which
11407   // according to C++ standards prior to C++2a has undefined behavior
11408   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11409   // more than the maximum value representable in the result type, so never
11410   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11411   // expression is still probably a bug.)
11412   Expr::EvalResult LHSResult;
11413   if (LHS.get()->isValueDependent() ||
11414       LHSType->hasUnsignedIntegerRepresentation() ||
11415       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11416     return;
11417   llvm::APSInt Left = LHSResult.Val.getInt();
11418 
11419   // If LHS does not have a signed type and non-negative value
11420   // then, the behavior is undefined before C++2a. Warn about it.
11421   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
11422       !S.getLangOpts().CPlusPlus20) {
11423     S.DiagRuntimeBehavior(Loc, LHS.get(),
11424                           S.PDiag(diag::warn_shift_lhs_negative)
11425                             << LHS.get()->getSourceRange());
11426     return;
11427   }
11428 
11429   llvm::APInt ResultBits =
11430       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
11431   if (LeftBits.uge(ResultBits))
11432     return;
11433   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11434   Result = Result.shl(Right);
11435 
11436   // Print the bit representation of the signed integer as an unsigned
11437   // hexadecimal number.
11438   SmallString<40> HexResult;
11439   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11440 
11441   // If we are only missing a sign bit, this is less likely to result in actual
11442   // bugs -- if the result is cast back to an unsigned type, it will have the
11443   // expected value. Thus we place this behind a different warning that can be
11444   // turned off separately if needed.
11445   if (LeftBits == ResultBits - 1) {
11446     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11447         << HexResult << LHSType
11448         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11449     return;
11450   }
11451 
11452   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11453     << HexResult.str() << Result.getMinSignedBits() << LHSType
11454     << Left.getBitWidth() << LHS.get()->getSourceRange()
11455     << RHS.get()->getSourceRange();
11456 }
11457 
11458 /// Return the resulting type when a vector is shifted
11459 ///        by a scalar or vector shift amount.
11460 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11461                                  SourceLocation Loc, bool IsCompAssign) {
11462   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11463   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11464       !LHS.get()->getType()->isVectorType()) {
11465     S.Diag(Loc, diag::err_shift_rhs_only_vector)
11466       << RHS.get()->getType() << LHS.get()->getType()
11467       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11468     return QualType();
11469   }
11470 
11471   if (!IsCompAssign) {
11472     LHS = S.UsualUnaryConversions(LHS.get());
11473     if (LHS.isInvalid()) return QualType();
11474   }
11475 
11476   RHS = S.UsualUnaryConversions(RHS.get());
11477   if (RHS.isInvalid()) return QualType();
11478 
11479   QualType LHSType = LHS.get()->getType();
11480   // Note that LHS might be a scalar because the routine calls not only in
11481   // OpenCL case.
11482   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11483   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11484 
11485   // Note that RHS might not be a vector.
11486   QualType RHSType = RHS.get()->getType();
11487   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11488   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11489 
11490   // Do not allow shifts for boolean vectors.
11491   if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11492       (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11493     S.Diag(Loc, diag::err_typecheck_invalid_operands)
11494         << LHS.get()->getType() << RHS.get()->getType()
11495         << LHS.get()->getSourceRange();
11496     return QualType();
11497   }
11498 
11499   // The operands need to be integers.
11500   if (!LHSEleType->isIntegerType()) {
11501     S.Diag(Loc, diag::err_typecheck_expect_int)
11502       << LHS.get()->getType() << LHS.get()->getSourceRange();
11503     return QualType();
11504   }
11505 
11506   if (!RHSEleType->isIntegerType()) {
11507     S.Diag(Loc, diag::err_typecheck_expect_int)
11508       << RHS.get()->getType() << RHS.get()->getSourceRange();
11509     return QualType();
11510   }
11511 
11512   if (!LHSVecTy) {
11513     assert(RHSVecTy);
11514     if (IsCompAssign)
11515       return RHSType;
11516     if (LHSEleType != RHSEleType) {
11517       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11518       LHSEleType = RHSEleType;
11519     }
11520     QualType VecTy =
11521         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11522     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11523     LHSType = VecTy;
11524   } else if (RHSVecTy) {
11525     // OpenCL v1.1 s6.3.j says that for vector types, the operators
11526     // are applied component-wise. So if RHS is a vector, then ensure
11527     // that the number of elements is the same as LHS...
11528     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11529       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11530         << LHS.get()->getType() << RHS.get()->getType()
11531         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11532       return QualType();
11533     }
11534     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11535       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11536       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11537       if (LHSBT != RHSBT &&
11538           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11539         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11540             << LHS.get()->getType() << RHS.get()->getType()
11541             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11542       }
11543     }
11544   } else {
11545     // ...else expand RHS to match the number of elements in LHS.
11546     QualType VecTy =
11547       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11548     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11549   }
11550 
11551   return LHSType;
11552 }
11553 
11554 static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
11555                                          ExprResult &RHS, SourceLocation Loc,
11556                                          bool IsCompAssign) {
11557   if (!IsCompAssign) {
11558     LHS = S.UsualUnaryConversions(LHS.get());
11559     if (LHS.isInvalid())
11560       return QualType();
11561   }
11562 
11563   RHS = S.UsualUnaryConversions(RHS.get());
11564   if (RHS.isInvalid())
11565     return QualType();
11566 
11567   QualType LHSType = LHS.get()->getType();
11568   const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11569   QualType LHSEleType = LHSType->isVLSTBuiltinType()
11570                             ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11571                             : LHSType;
11572 
11573   // Note that RHS might not be a vector
11574   QualType RHSType = RHS.get()->getType();
11575   const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11576   QualType RHSEleType = RHSType->isVLSTBuiltinType()
11577                             ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11578                             : RHSType;
11579 
11580   if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11581       (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11582     S.Diag(Loc, diag::err_typecheck_invalid_operands)
11583         << LHSType << RHSType << LHS.get()->getSourceRange();
11584     return QualType();
11585   }
11586 
11587   if (!LHSEleType->isIntegerType()) {
11588     S.Diag(Loc, diag::err_typecheck_expect_int)
11589         << LHS.get()->getType() << LHS.get()->getSourceRange();
11590     return QualType();
11591   }
11592 
11593   if (!RHSEleType->isIntegerType()) {
11594     S.Diag(Loc, diag::err_typecheck_expect_int)
11595         << RHS.get()->getType() << RHS.get()->getSourceRange();
11596     return QualType();
11597   }
11598 
11599   if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
11600       (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11601        S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11602     S.Diag(Loc, diag::err_typecheck_invalid_operands)
11603         << LHSType << RHSType << LHS.get()->getSourceRange()
11604         << RHS.get()->getSourceRange();
11605     return QualType();
11606   }
11607 
11608   if (!LHSType->isVLSTBuiltinType()) {
11609     assert(RHSType->isVLSTBuiltinType());
11610     if (IsCompAssign)
11611       return RHSType;
11612     if (LHSEleType != RHSEleType) {
11613       LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11614       LHSEleType = RHSEleType;
11615     }
11616     const llvm::ElementCount VecSize =
11617         S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11618     QualType VecTy =
11619         S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11620     LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11621     LHSType = VecTy;
11622   } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) {
11623     if (S.Context.getTypeSize(RHSBuiltinTy) !=
11624         S.Context.getTypeSize(LHSBuiltinTy)) {
11625       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11626           << LHSType << RHSType << LHS.get()->getSourceRange()
11627           << RHS.get()->getSourceRange();
11628       return QualType();
11629     }
11630   } else {
11631     const llvm::ElementCount VecSize =
11632         S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11633     if (LHSEleType != RHSEleType) {
11634       RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11635       RHSEleType = LHSEleType;
11636     }
11637     QualType VecTy =
11638         S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11639     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11640   }
11641 
11642   return LHSType;
11643 }
11644 
11645 // C99 6.5.7
11646 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11647                                   SourceLocation Loc, BinaryOperatorKind Opc,
11648                                   bool IsCompAssign) {
11649   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11650 
11651   // Vector shifts promote their scalar inputs to vector type.
11652   if (LHS.get()->getType()->isVectorType() ||
11653       RHS.get()->getType()->isVectorType()) {
11654     if (LangOpts.ZVector) {
11655       // The shift operators for the z vector extensions work basically
11656       // like general shifts, except that neither the LHS nor the RHS is
11657       // allowed to be a "vector bool".
11658       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11659         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11660           return InvalidOperands(Loc, LHS, RHS);
11661       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11662         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11663           return InvalidOperands(Loc, LHS, RHS);
11664     }
11665     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11666   }
11667 
11668   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11669       RHS.get()->getType()->isVLSTBuiltinType())
11670     return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11671 
11672   // Shifts don't perform usual arithmetic conversions, they just do integer
11673   // promotions on each operand. C99 6.5.7p3
11674 
11675   // For the LHS, do usual unary conversions, but then reset them away
11676   // if this is a compound assignment.
11677   ExprResult OldLHS = LHS;
11678   LHS = UsualUnaryConversions(LHS.get());
11679   if (LHS.isInvalid())
11680     return QualType();
11681   QualType LHSType = LHS.get()->getType();
11682   if (IsCompAssign) LHS = OldLHS;
11683 
11684   // The RHS is simpler.
11685   RHS = UsualUnaryConversions(RHS.get());
11686   if (RHS.isInvalid())
11687     return QualType();
11688   QualType RHSType = RHS.get()->getType();
11689 
11690   // C99 6.5.7p2: Each of the operands shall have integer type.
11691   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11692   if ((!LHSType->isFixedPointOrIntegerType() &&
11693        !LHSType->hasIntegerRepresentation()) ||
11694       !RHSType->hasIntegerRepresentation())
11695     return InvalidOperands(Loc, LHS, RHS);
11696 
11697   // C++0x: Don't allow scoped enums. FIXME: Use something better than
11698   // hasIntegerRepresentation() above instead of this.
11699   if (isScopedEnumerationType(LHSType) ||
11700       isScopedEnumerationType(RHSType)) {
11701     return InvalidOperands(Loc, LHS, RHS);
11702   }
11703   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11704 
11705   // "The type of the result is that of the promoted left operand."
11706   return LHSType;
11707 }
11708 
11709 /// Diagnose bad pointer comparisons.
11710 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11711                                               ExprResult &LHS, ExprResult &RHS,
11712                                               bool IsError) {
11713   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11714                       : diag::ext_typecheck_comparison_of_distinct_pointers)
11715     << LHS.get()->getType() << RHS.get()->getType()
11716     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11717 }
11718 
11719 /// Returns false if the pointers are converted to a composite type,
11720 /// true otherwise.
11721 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11722                                            ExprResult &LHS, ExprResult &RHS) {
11723   // C++ [expr.rel]p2:
11724   //   [...] Pointer conversions (4.10) and qualification
11725   //   conversions (4.4) are performed on pointer operands (or on
11726   //   a pointer operand and a null pointer constant) to bring
11727   //   them to their composite pointer type. [...]
11728   //
11729   // C++ [expr.eq]p1 uses the same notion for (in)equality
11730   // comparisons of pointers.
11731 
11732   QualType LHSType = LHS.get()->getType();
11733   QualType RHSType = RHS.get()->getType();
11734   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11735          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11736 
11737   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11738   if (T.isNull()) {
11739     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11740         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11741       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11742     else
11743       S.InvalidOperands(Loc, LHS, RHS);
11744     return true;
11745   }
11746 
11747   return false;
11748 }
11749 
11750 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11751                                                     ExprResult &LHS,
11752                                                     ExprResult &RHS,
11753                                                     bool IsError) {
11754   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11755                       : diag::ext_typecheck_comparison_of_fptr_to_void)
11756     << LHS.get()->getType() << RHS.get()->getType()
11757     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11758 }
11759 
11760 static bool isObjCObjectLiteral(ExprResult &E) {
11761   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11762   case Stmt::ObjCArrayLiteralClass:
11763   case Stmt::ObjCDictionaryLiteralClass:
11764   case Stmt::ObjCStringLiteralClass:
11765   case Stmt::ObjCBoxedExprClass:
11766     return true;
11767   default:
11768     // Note that ObjCBoolLiteral is NOT an object literal!
11769     return false;
11770   }
11771 }
11772 
11773 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11774   const ObjCObjectPointerType *Type =
11775     LHS->getType()->getAs<ObjCObjectPointerType>();
11776 
11777   // If this is not actually an Objective-C object, bail out.
11778   if (!Type)
11779     return false;
11780 
11781   // Get the LHS object's interface type.
11782   QualType InterfaceType = Type->getPointeeType();
11783 
11784   // If the RHS isn't an Objective-C object, bail out.
11785   if (!RHS->getType()->isObjCObjectPointerType())
11786     return false;
11787 
11788   // Try to find the -isEqual: method.
11789   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11790   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11791                                                       InterfaceType,
11792                                                       /*IsInstance=*/true);
11793   if (!Method) {
11794     if (Type->isObjCIdType()) {
11795       // For 'id', just check the global pool.
11796       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11797                                                   /*receiverId=*/true);
11798     } else {
11799       // Check protocols.
11800       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11801                                              /*IsInstance=*/true);
11802     }
11803   }
11804 
11805   if (!Method)
11806     return false;
11807 
11808   QualType T = Method->parameters()[0]->getType();
11809   if (!T->isObjCObjectPointerType())
11810     return false;
11811 
11812   QualType R = Method->getReturnType();
11813   if (!R->isScalarType())
11814     return false;
11815 
11816   return true;
11817 }
11818 
11819 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11820   FromE = FromE->IgnoreParenImpCasts();
11821   switch (FromE->getStmtClass()) {
11822     default:
11823       break;
11824     case Stmt::ObjCStringLiteralClass:
11825       // "string literal"
11826       return LK_String;
11827     case Stmt::ObjCArrayLiteralClass:
11828       // "array literal"
11829       return LK_Array;
11830     case Stmt::ObjCDictionaryLiteralClass:
11831       // "dictionary literal"
11832       return LK_Dictionary;
11833     case Stmt::BlockExprClass:
11834       return LK_Block;
11835     case Stmt::ObjCBoxedExprClass: {
11836       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11837       switch (Inner->getStmtClass()) {
11838         case Stmt::IntegerLiteralClass:
11839         case Stmt::FloatingLiteralClass:
11840         case Stmt::CharacterLiteralClass:
11841         case Stmt::ObjCBoolLiteralExprClass:
11842         case Stmt::CXXBoolLiteralExprClass:
11843           // "numeric literal"
11844           return LK_Numeric;
11845         case Stmt::ImplicitCastExprClass: {
11846           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11847           // Boolean literals can be represented by implicit casts.
11848           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11849             return LK_Numeric;
11850           break;
11851         }
11852         default:
11853           break;
11854       }
11855       return LK_Boxed;
11856     }
11857   }
11858   return LK_None;
11859 }
11860 
11861 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11862                                           ExprResult &LHS, ExprResult &RHS,
11863                                           BinaryOperator::Opcode Opc){
11864   Expr *Literal;
11865   Expr *Other;
11866   if (isObjCObjectLiteral(LHS)) {
11867     Literal = LHS.get();
11868     Other = RHS.get();
11869   } else {
11870     Literal = RHS.get();
11871     Other = LHS.get();
11872   }
11873 
11874   // Don't warn on comparisons against nil.
11875   Other = Other->IgnoreParenCasts();
11876   if (Other->isNullPointerConstant(S.getASTContext(),
11877                                    Expr::NPC_ValueDependentIsNotNull))
11878     return;
11879 
11880   // This should be kept in sync with warn_objc_literal_comparison.
11881   // LK_String should always be after the other literals, since it has its own
11882   // warning flag.
11883   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11884   assert(LiteralKind != Sema::LK_Block);
11885   if (LiteralKind == Sema::LK_None) {
11886     llvm_unreachable("Unknown Objective-C object literal kind");
11887   }
11888 
11889   if (LiteralKind == Sema::LK_String)
11890     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11891       << Literal->getSourceRange();
11892   else
11893     S.Diag(Loc, diag::warn_objc_literal_comparison)
11894       << LiteralKind << Literal->getSourceRange();
11895 
11896   if (BinaryOperator::isEqualityOp(Opc) &&
11897       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11898     SourceLocation Start = LHS.get()->getBeginLoc();
11899     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11900     CharSourceRange OpRange =
11901       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11902 
11903     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11904       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11905       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11906       << FixItHint::CreateInsertion(End, "]");
11907   }
11908 }
11909 
11910 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11911 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11912                                            ExprResult &RHS, SourceLocation Loc,
11913                                            BinaryOperatorKind Opc) {
11914   // Check that left hand side is !something.
11915   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11916   if (!UO || UO->getOpcode() != UO_LNot) return;
11917 
11918   // Only check if the right hand side is non-bool arithmetic type.
11919   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11920 
11921   // Make sure that the something in !something is not bool.
11922   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11923   if (SubExpr->isKnownToHaveBooleanValue()) return;
11924 
11925   // Emit warning.
11926   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11927   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11928       << Loc << IsBitwiseOp;
11929 
11930   // First note suggest !(x < y)
11931   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11932   SourceLocation FirstClose = RHS.get()->getEndLoc();
11933   FirstClose = S.getLocForEndOfToken(FirstClose);
11934   if (FirstClose.isInvalid())
11935     FirstOpen = SourceLocation();
11936   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11937       << IsBitwiseOp
11938       << FixItHint::CreateInsertion(FirstOpen, "(")
11939       << FixItHint::CreateInsertion(FirstClose, ")");
11940 
11941   // Second note suggests (!x) < y
11942   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11943   SourceLocation SecondClose = LHS.get()->getEndLoc();
11944   SecondClose = S.getLocForEndOfToken(SecondClose);
11945   if (SecondClose.isInvalid())
11946     SecondOpen = SourceLocation();
11947   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11948       << FixItHint::CreateInsertion(SecondOpen, "(")
11949       << FixItHint::CreateInsertion(SecondClose, ")");
11950 }
11951 
11952 // Returns true if E refers to a non-weak array.
11953 static bool checkForArray(const Expr *E) {
11954   const ValueDecl *D = nullptr;
11955   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11956     D = DR->getDecl();
11957   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11958     if (Mem->isImplicitAccess())
11959       D = Mem->getMemberDecl();
11960   }
11961   if (!D)
11962     return false;
11963   return D->getType()->isArrayType() && !D->isWeak();
11964 }
11965 
11966 /// Diagnose some forms of syntactically-obvious tautological comparison.
11967 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11968                                            Expr *LHS, Expr *RHS,
11969                                            BinaryOperatorKind Opc) {
11970   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11971   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11972 
11973   QualType LHSType = LHS->getType();
11974   QualType RHSType = RHS->getType();
11975   if (LHSType->hasFloatingRepresentation() ||
11976       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11977       S.inTemplateInstantiation())
11978     return;
11979 
11980   // Comparisons between two array types are ill-formed for operator<=>, so
11981   // we shouldn't emit any additional warnings about it.
11982   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11983     return;
11984 
11985   // For non-floating point types, check for self-comparisons of the form
11986   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11987   // often indicate logic errors in the program.
11988   //
11989   // NOTE: Don't warn about comparison expressions resulting from macro
11990   // expansion. Also don't warn about comparisons which are only self
11991   // comparisons within a template instantiation. The warnings should catch
11992   // obvious cases in the definition of the template anyways. The idea is to
11993   // warn when the typed comparison operator will always evaluate to the same
11994   // result.
11995 
11996   // Used for indexing into %select in warn_comparison_always
11997   enum {
11998     AlwaysConstant,
11999     AlwaysTrue,
12000     AlwaysFalse,
12001     AlwaysEqual, // std::strong_ordering::equal from operator<=>
12002   };
12003 
12004   // C++2a [depr.array.comp]:
12005   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12006   //   operands of array type are deprecated.
12007   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
12008       RHSStripped->getType()->isArrayType()) {
12009     S.Diag(Loc, diag::warn_depr_array_comparison)
12010         << LHS->getSourceRange() << RHS->getSourceRange()
12011         << LHSStripped->getType() << RHSStripped->getType();
12012     // Carry on to produce the tautological comparison warning, if this
12013     // expression is potentially-evaluated, we can resolve the array to a
12014     // non-weak declaration, and so on.
12015   }
12016 
12017   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12018     if (Expr::isSameComparisonOperand(LHS, RHS)) {
12019       unsigned Result;
12020       switch (Opc) {
12021       case BO_EQ:
12022       case BO_LE:
12023       case BO_GE:
12024         Result = AlwaysTrue;
12025         break;
12026       case BO_NE:
12027       case BO_LT:
12028       case BO_GT:
12029         Result = AlwaysFalse;
12030         break;
12031       case BO_Cmp:
12032         Result = AlwaysEqual;
12033         break;
12034       default:
12035         Result = AlwaysConstant;
12036         break;
12037       }
12038       S.DiagRuntimeBehavior(Loc, nullptr,
12039                             S.PDiag(diag::warn_comparison_always)
12040                                 << 0 /*self-comparison*/
12041                                 << Result);
12042     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12043       // What is it always going to evaluate to?
12044       unsigned Result;
12045       switch (Opc) {
12046       case BO_EQ: // e.g. array1 == array2
12047         Result = AlwaysFalse;
12048         break;
12049       case BO_NE: // e.g. array1 != array2
12050         Result = AlwaysTrue;
12051         break;
12052       default: // e.g. array1 <= array2
12053         // The best we can say is 'a constant'
12054         Result = AlwaysConstant;
12055         break;
12056       }
12057       S.DiagRuntimeBehavior(Loc, nullptr,
12058                             S.PDiag(diag::warn_comparison_always)
12059                                 << 1 /*array comparison*/
12060                                 << Result);
12061     }
12062   }
12063 
12064   if (isa<CastExpr>(LHSStripped))
12065     LHSStripped = LHSStripped->IgnoreParenCasts();
12066   if (isa<CastExpr>(RHSStripped))
12067     RHSStripped = RHSStripped->IgnoreParenCasts();
12068 
12069   // Warn about comparisons against a string constant (unless the other
12070   // operand is null); the user probably wants string comparison function.
12071   Expr *LiteralString = nullptr;
12072   Expr *LiteralStringStripped = nullptr;
12073   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12074       !RHSStripped->isNullPointerConstant(S.Context,
12075                                           Expr::NPC_ValueDependentIsNull)) {
12076     LiteralString = LHS;
12077     LiteralStringStripped = LHSStripped;
12078   } else if ((isa<StringLiteral>(RHSStripped) ||
12079               isa<ObjCEncodeExpr>(RHSStripped)) &&
12080              !LHSStripped->isNullPointerConstant(S.Context,
12081                                           Expr::NPC_ValueDependentIsNull)) {
12082     LiteralString = RHS;
12083     LiteralStringStripped = RHSStripped;
12084   }
12085 
12086   if (LiteralString) {
12087     S.DiagRuntimeBehavior(Loc, nullptr,
12088                           S.PDiag(diag::warn_stringcompare)
12089                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
12090                               << LiteralString->getSourceRange());
12091   }
12092 }
12093 
12094 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12095   switch (CK) {
12096   default: {
12097 #ifndef NDEBUG
12098     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12099                  << "\n";
12100 #endif
12101     llvm_unreachable("unhandled cast kind");
12102   }
12103   case CK_UserDefinedConversion:
12104     return ICK_Identity;
12105   case CK_LValueToRValue:
12106     return ICK_Lvalue_To_Rvalue;
12107   case CK_ArrayToPointerDecay:
12108     return ICK_Array_To_Pointer;
12109   case CK_FunctionToPointerDecay:
12110     return ICK_Function_To_Pointer;
12111   case CK_IntegralCast:
12112     return ICK_Integral_Conversion;
12113   case CK_FloatingCast:
12114     return ICK_Floating_Conversion;
12115   case CK_IntegralToFloating:
12116   case CK_FloatingToIntegral:
12117     return ICK_Floating_Integral;
12118   case CK_IntegralComplexCast:
12119   case CK_FloatingComplexCast:
12120   case CK_FloatingComplexToIntegralComplex:
12121   case CK_IntegralComplexToFloatingComplex:
12122     return ICK_Complex_Conversion;
12123   case CK_FloatingComplexToReal:
12124   case CK_FloatingRealToComplex:
12125   case CK_IntegralComplexToReal:
12126   case CK_IntegralRealToComplex:
12127     return ICK_Complex_Real;
12128   }
12129 }
12130 
12131 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12132                                              QualType FromType,
12133                                              SourceLocation Loc) {
12134   // Check for a narrowing implicit conversion.
12135   StandardConversionSequence SCS;
12136   SCS.setAsIdentityConversion();
12137   SCS.setToType(0, FromType);
12138   SCS.setToType(1, ToType);
12139   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12140     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12141 
12142   APValue PreNarrowingValue;
12143   QualType PreNarrowingType;
12144   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12145                                PreNarrowingType,
12146                                /*IgnoreFloatToIntegralConversion*/ true)) {
12147   case NK_Dependent_Narrowing:
12148     // Implicit conversion to a narrower type, but the expression is
12149     // value-dependent so we can't tell whether it's actually narrowing.
12150   case NK_Not_Narrowing:
12151     return false;
12152 
12153   case NK_Constant_Narrowing:
12154     // Implicit conversion to a narrower type, and the value is not a constant
12155     // expression.
12156     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12157         << /*Constant*/ 1
12158         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12159     return true;
12160 
12161   case NK_Variable_Narrowing:
12162     // Implicit conversion to a narrower type, and the value is not a constant
12163     // expression.
12164   case NK_Type_Narrowing:
12165     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12166         << /*Constant*/ 0 << FromType << ToType;
12167     // TODO: It's not a constant expression, but what if the user intended it
12168     // to be? Can we produce notes to help them figure out why it isn't?
12169     return true;
12170   }
12171   llvm_unreachable("unhandled case in switch");
12172 }
12173 
12174 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12175                                                          ExprResult &LHS,
12176                                                          ExprResult &RHS,
12177                                                          SourceLocation Loc) {
12178   QualType LHSType = LHS.get()->getType();
12179   QualType RHSType = RHS.get()->getType();
12180   // Dig out the original argument type and expression before implicit casts
12181   // were applied. These are the types/expressions we need to check the
12182   // [expr.spaceship] requirements against.
12183   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12184   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12185   QualType LHSStrippedType = LHSStripped.get()->getType();
12186   QualType RHSStrippedType = RHSStripped.get()->getType();
12187 
12188   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12189   // other is not, the program is ill-formed.
12190   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12191     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12192     return QualType();
12193   }
12194 
12195   // FIXME: Consider combining this with checkEnumArithmeticConversions.
12196   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12197                     RHSStrippedType->isEnumeralType();
12198   if (NumEnumArgs == 1) {
12199     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12200     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12201     if (OtherTy->hasFloatingRepresentation()) {
12202       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12203       return QualType();
12204     }
12205   }
12206   if (NumEnumArgs == 2) {
12207     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12208     // type E, the operator yields the result of converting the operands
12209     // to the underlying type of E and applying <=> to the converted operands.
12210     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12211       S.InvalidOperands(Loc, LHS, RHS);
12212       return QualType();
12213     }
12214     QualType IntType =
12215         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12216     assert(IntType->isArithmeticType());
12217 
12218     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12219     // promote the boolean type, and all other promotable integer types, to
12220     // avoid this.
12221     if (IntType->isPromotableIntegerType())
12222       IntType = S.Context.getPromotedIntegerType(IntType);
12223 
12224     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12225     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12226     LHSType = RHSType = IntType;
12227   }
12228 
12229   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12230   // usual arithmetic conversions are applied to the operands.
12231   QualType Type =
12232       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12233   if (LHS.isInvalid() || RHS.isInvalid())
12234     return QualType();
12235   if (Type.isNull())
12236     return S.InvalidOperands(Loc, LHS, RHS);
12237 
12238   Optional<ComparisonCategoryType> CCT =
12239       getComparisonCategoryForBuiltinCmp(Type);
12240   if (!CCT)
12241     return S.InvalidOperands(Loc, LHS, RHS);
12242 
12243   bool HasNarrowing = checkThreeWayNarrowingConversion(
12244       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12245   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12246                                                    RHS.get()->getBeginLoc());
12247   if (HasNarrowing)
12248     return QualType();
12249 
12250   assert(!Type.isNull() && "composite type for <=> has not been set");
12251 
12252   return S.CheckComparisonCategoryType(
12253       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
12254 }
12255 
12256 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12257                                                  ExprResult &RHS,
12258                                                  SourceLocation Loc,
12259                                                  BinaryOperatorKind Opc) {
12260   if (Opc == BO_Cmp)
12261     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12262 
12263   // C99 6.5.8p3 / C99 6.5.9p4
12264   QualType Type =
12265       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12266   if (LHS.isInvalid() || RHS.isInvalid())
12267     return QualType();
12268   if (Type.isNull())
12269     return S.InvalidOperands(Loc, LHS, RHS);
12270   assert(Type->isArithmeticType() || Type->isEnumeralType());
12271 
12272   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12273     return S.InvalidOperands(Loc, LHS, RHS);
12274 
12275   // Check for comparisons of floating point operands using != and ==.
12276   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
12277     S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12278 
12279   // The result of comparisons is 'bool' in C++, 'int' in C.
12280   return S.Context.getLogicalOperationType();
12281 }
12282 
12283 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12284   if (!NullE.get()->getType()->isAnyPointerType())
12285     return;
12286   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12287   if (!E.get()->getType()->isAnyPointerType() &&
12288       E.get()->isNullPointerConstant(Context,
12289                                      Expr::NPC_ValueDependentIsNotNull) ==
12290         Expr::NPCK_ZeroExpression) {
12291     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12292       if (CL->getValue() == 0)
12293         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12294             << NullValue
12295             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12296                                             NullValue ? "NULL" : "(void *)0");
12297     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12298         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12299         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12300         if (T == Context.CharTy)
12301           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12302               << NullValue
12303               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12304                                               NullValue ? "NULL" : "(void *)0");
12305       }
12306   }
12307 }
12308 
12309 // C99 6.5.8, C++ [expr.rel]
12310 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12311                                     SourceLocation Loc,
12312                                     BinaryOperatorKind Opc) {
12313   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12314   bool IsThreeWay = Opc == BO_Cmp;
12315   bool IsOrdered = IsRelational || IsThreeWay;
12316   auto IsAnyPointerType = [](ExprResult E) {
12317     QualType Ty = E.get()->getType();
12318     return Ty->isPointerType() || Ty->isMemberPointerType();
12319   };
12320 
12321   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12322   // type, array-to-pointer, ..., conversions are performed on both operands to
12323   // bring them to their composite type.
12324   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12325   // any type-related checks.
12326   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12327     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12328     if (LHS.isInvalid())
12329       return QualType();
12330     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12331     if (RHS.isInvalid())
12332       return QualType();
12333   } else {
12334     LHS = DefaultLvalueConversion(LHS.get());
12335     if (LHS.isInvalid())
12336       return QualType();
12337     RHS = DefaultLvalueConversion(RHS.get());
12338     if (RHS.isInvalid())
12339       return QualType();
12340   }
12341 
12342   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12343   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12344     CheckPtrComparisonWithNullChar(LHS, RHS);
12345     CheckPtrComparisonWithNullChar(RHS, LHS);
12346   }
12347 
12348   // Handle vector comparisons separately.
12349   if (LHS.get()->getType()->isVectorType() ||
12350       RHS.get()->getType()->isVectorType())
12351     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12352 
12353   if (LHS.get()->getType()->isVLSTBuiltinType() ||
12354       RHS.get()->getType()->isVLSTBuiltinType())
12355     return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12356 
12357   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12358   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12359 
12360   QualType LHSType = LHS.get()->getType();
12361   QualType RHSType = RHS.get()->getType();
12362   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12363       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12364     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12365 
12366   const Expr::NullPointerConstantKind LHSNullKind =
12367       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12368   const Expr::NullPointerConstantKind RHSNullKind =
12369       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12370   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12371   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12372 
12373   auto computeResultTy = [&]() {
12374     if (Opc != BO_Cmp)
12375       return Context.getLogicalOperationType();
12376     assert(getLangOpts().CPlusPlus);
12377     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12378 
12379     QualType CompositeTy = LHS.get()->getType();
12380     assert(!CompositeTy->isReferenceType());
12381 
12382     Optional<ComparisonCategoryType> CCT =
12383         getComparisonCategoryForBuiltinCmp(CompositeTy);
12384     if (!CCT)
12385       return InvalidOperands(Loc, LHS, RHS);
12386 
12387     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12388       // P0946R0: Comparisons between a null pointer constant and an object
12389       // pointer result in std::strong_equality, which is ill-formed under
12390       // P1959R0.
12391       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12392           << (LHSIsNull ? LHS.get()->getSourceRange()
12393                         : RHS.get()->getSourceRange());
12394       return QualType();
12395     }
12396 
12397     return CheckComparisonCategoryType(
12398         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12399   };
12400 
12401   if (!IsOrdered && LHSIsNull != RHSIsNull) {
12402     bool IsEquality = Opc == BO_EQ;
12403     if (RHSIsNull)
12404       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12405                                    RHS.get()->getSourceRange());
12406     else
12407       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12408                                    LHS.get()->getSourceRange());
12409   }
12410 
12411   if (IsOrdered && LHSType->isFunctionPointerType() &&
12412       RHSType->isFunctionPointerType()) {
12413     // Valid unless a relational comparison of function pointers
12414     bool IsError = Opc == BO_Cmp;
12415     auto DiagID =
12416         IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12417         : getLangOpts().CPlusPlus
12418             ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12419             : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12420     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12421                       << RHS.get()->getSourceRange();
12422     if (IsError)
12423       return QualType();
12424   }
12425 
12426   if ((LHSType->isIntegerType() && !LHSIsNull) ||
12427       (RHSType->isIntegerType() && !RHSIsNull)) {
12428     // Skip normal pointer conversion checks in this case; we have better
12429     // diagnostics for this below.
12430   } else if (getLangOpts().CPlusPlus) {
12431     // Equality comparison of a function pointer to a void pointer is invalid,
12432     // but we allow it as an extension.
12433     // FIXME: If we really want to allow this, should it be part of composite
12434     // pointer type computation so it works in conditionals too?
12435     if (!IsOrdered &&
12436         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12437          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12438       // This is a gcc extension compatibility comparison.
12439       // In a SFINAE context, we treat this as a hard error to maintain
12440       // conformance with the C++ standard.
12441       diagnoseFunctionPointerToVoidComparison(
12442           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12443 
12444       if (isSFINAEContext())
12445         return QualType();
12446 
12447       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12448       return computeResultTy();
12449     }
12450 
12451     // C++ [expr.eq]p2:
12452     //   If at least one operand is a pointer [...] bring them to their
12453     //   composite pointer type.
12454     // C++ [expr.spaceship]p6
12455     //  If at least one of the operands is of pointer type, [...] bring them
12456     //  to their composite pointer type.
12457     // C++ [expr.rel]p2:
12458     //   If both operands are pointers, [...] bring them to their composite
12459     //   pointer type.
12460     // For <=>, the only valid non-pointer types are arrays and functions, and
12461     // we already decayed those, so this is really the same as the relational
12462     // comparison rule.
12463     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12464             (IsOrdered ? 2 : 1) &&
12465         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12466                                          RHSType->isObjCObjectPointerType()))) {
12467       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12468         return QualType();
12469       return computeResultTy();
12470     }
12471   } else if (LHSType->isPointerType() &&
12472              RHSType->isPointerType()) { // C99 6.5.8p2
12473     // All of the following pointer-related warnings are GCC extensions, except
12474     // when handling null pointer constants.
12475     QualType LCanPointeeTy =
12476       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12477     QualType RCanPointeeTy =
12478       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12479 
12480     // C99 6.5.9p2 and C99 6.5.8p2
12481     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12482                                    RCanPointeeTy.getUnqualifiedType())) {
12483       if (IsRelational) {
12484         // Pointers both need to point to complete or incomplete types
12485         if ((LCanPointeeTy->isIncompleteType() !=
12486              RCanPointeeTy->isIncompleteType()) &&
12487             !getLangOpts().C11) {
12488           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12489               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12490               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12491               << RCanPointeeTy->isIncompleteType();
12492         }
12493       }
12494     } else if (!IsRelational &&
12495                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12496       // Valid unless comparison between non-null pointer and function pointer
12497       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12498           && !LHSIsNull && !RHSIsNull)
12499         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12500                                                 /*isError*/false);
12501     } else {
12502       // Invalid
12503       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12504     }
12505     if (LCanPointeeTy != RCanPointeeTy) {
12506       // Treat NULL constant as a special case in OpenCL.
12507       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12508         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12509           Diag(Loc,
12510                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12511               << LHSType << RHSType << 0 /* comparison */
12512               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12513         }
12514       }
12515       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12516       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12517       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12518                                                : CK_BitCast;
12519       if (LHSIsNull && !RHSIsNull)
12520         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12521       else
12522         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12523     }
12524     return computeResultTy();
12525   }
12526 
12527   if (getLangOpts().CPlusPlus) {
12528     // C++ [expr.eq]p4:
12529     //   Two operands of type std::nullptr_t or one operand of type
12530     //   std::nullptr_t and the other a null pointer constant compare equal.
12531     if (!IsOrdered && LHSIsNull && RHSIsNull) {
12532       if (LHSType->isNullPtrType()) {
12533         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12534         return computeResultTy();
12535       }
12536       if (RHSType->isNullPtrType()) {
12537         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12538         return computeResultTy();
12539       }
12540     }
12541 
12542     // Comparison of Objective-C pointers and block pointers against nullptr_t.
12543     // These aren't covered by the composite pointer type rules.
12544     if (!IsOrdered && RHSType->isNullPtrType() &&
12545         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12546       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12547       return computeResultTy();
12548     }
12549     if (!IsOrdered && LHSType->isNullPtrType() &&
12550         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12551       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12552       return computeResultTy();
12553     }
12554 
12555     if (IsRelational &&
12556         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12557          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12558       // HACK: Relational comparison of nullptr_t against a pointer type is
12559       // invalid per DR583, but we allow it within std::less<> and friends,
12560       // since otherwise common uses of it break.
12561       // FIXME: Consider removing this hack once LWG fixes std::less<> and
12562       // friends to have std::nullptr_t overload candidates.
12563       DeclContext *DC = CurContext;
12564       if (isa<FunctionDecl>(DC))
12565         DC = DC->getParent();
12566       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12567         if (CTSD->isInStdNamespace() &&
12568             llvm::StringSwitch<bool>(CTSD->getName())
12569                 .Cases("less", "less_equal", "greater", "greater_equal", true)
12570                 .Default(false)) {
12571           if (RHSType->isNullPtrType())
12572             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12573           else
12574             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12575           return computeResultTy();
12576         }
12577       }
12578     }
12579 
12580     // C++ [expr.eq]p2:
12581     //   If at least one operand is a pointer to member, [...] bring them to
12582     //   their composite pointer type.
12583     if (!IsOrdered &&
12584         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12585       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12586         return QualType();
12587       else
12588         return computeResultTy();
12589     }
12590   }
12591 
12592   // Handle block pointer types.
12593   if (!IsOrdered && LHSType->isBlockPointerType() &&
12594       RHSType->isBlockPointerType()) {
12595     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12596     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12597 
12598     if (!LHSIsNull && !RHSIsNull &&
12599         !Context.typesAreCompatible(lpointee, rpointee)) {
12600       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12601         << LHSType << RHSType << LHS.get()->getSourceRange()
12602         << RHS.get()->getSourceRange();
12603     }
12604     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12605     return computeResultTy();
12606   }
12607 
12608   // Allow block pointers to be compared with null pointer constants.
12609   if (!IsOrdered
12610       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12611           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12612     if (!LHSIsNull && !RHSIsNull) {
12613       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12614              ->getPointeeType()->isVoidType())
12615             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12616                 ->getPointeeType()->isVoidType())))
12617         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12618           << LHSType << RHSType << LHS.get()->getSourceRange()
12619           << RHS.get()->getSourceRange();
12620     }
12621     if (LHSIsNull && !RHSIsNull)
12622       LHS = ImpCastExprToType(LHS.get(), RHSType,
12623                               RHSType->isPointerType() ? CK_BitCast
12624                                 : CK_AnyPointerToBlockPointerCast);
12625     else
12626       RHS = ImpCastExprToType(RHS.get(), LHSType,
12627                               LHSType->isPointerType() ? CK_BitCast
12628                                 : CK_AnyPointerToBlockPointerCast);
12629     return computeResultTy();
12630   }
12631 
12632   if (LHSType->isObjCObjectPointerType() ||
12633       RHSType->isObjCObjectPointerType()) {
12634     const PointerType *LPT = LHSType->getAs<PointerType>();
12635     const PointerType *RPT = RHSType->getAs<PointerType>();
12636     if (LPT || RPT) {
12637       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12638       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12639 
12640       if (!LPtrToVoid && !RPtrToVoid &&
12641           !Context.typesAreCompatible(LHSType, RHSType)) {
12642         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12643                                           /*isError*/false);
12644       }
12645       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12646       // the RHS, but we have test coverage for this behavior.
12647       // FIXME: Consider using convertPointersToCompositeType in C++.
12648       if (LHSIsNull && !RHSIsNull) {
12649         Expr *E = LHS.get();
12650         if (getLangOpts().ObjCAutoRefCount)
12651           CheckObjCConversion(SourceRange(), RHSType, E,
12652                               CCK_ImplicitConversion);
12653         LHS = ImpCastExprToType(E, RHSType,
12654                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12655       }
12656       else {
12657         Expr *E = RHS.get();
12658         if (getLangOpts().ObjCAutoRefCount)
12659           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12660                               /*Diagnose=*/true,
12661                               /*DiagnoseCFAudited=*/false, Opc);
12662         RHS = ImpCastExprToType(E, LHSType,
12663                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12664       }
12665       return computeResultTy();
12666     }
12667     if (LHSType->isObjCObjectPointerType() &&
12668         RHSType->isObjCObjectPointerType()) {
12669       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12670         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12671                                           /*isError*/false);
12672       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12673         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12674 
12675       if (LHSIsNull && !RHSIsNull)
12676         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12677       else
12678         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12679       return computeResultTy();
12680     }
12681 
12682     if (!IsOrdered && LHSType->isBlockPointerType() &&
12683         RHSType->isBlockCompatibleObjCPointerType(Context)) {
12684       LHS = ImpCastExprToType(LHS.get(), RHSType,
12685                               CK_BlockPointerToObjCPointerCast);
12686       return computeResultTy();
12687     } else if (!IsOrdered &&
12688                LHSType->isBlockCompatibleObjCPointerType(Context) &&
12689                RHSType->isBlockPointerType()) {
12690       RHS = ImpCastExprToType(RHS.get(), LHSType,
12691                               CK_BlockPointerToObjCPointerCast);
12692       return computeResultTy();
12693     }
12694   }
12695   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12696       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12697     unsigned DiagID = 0;
12698     bool isError = false;
12699     if (LangOpts.DebuggerSupport) {
12700       // Under a debugger, allow the comparison of pointers to integers,
12701       // since users tend to want to compare addresses.
12702     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12703                (RHSIsNull && RHSType->isIntegerType())) {
12704       if (IsOrdered) {
12705         isError = getLangOpts().CPlusPlus;
12706         DiagID =
12707           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12708                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12709       }
12710     } else if (getLangOpts().CPlusPlus) {
12711       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12712       isError = true;
12713     } else if (IsOrdered)
12714       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12715     else
12716       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12717 
12718     if (DiagID) {
12719       Diag(Loc, DiagID)
12720         << LHSType << RHSType << LHS.get()->getSourceRange()
12721         << RHS.get()->getSourceRange();
12722       if (isError)
12723         return QualType();
12724     }
12725 
12726     if (LHSType->isIntegerType())
12727       LHS = ImpCastExprToType(LHS.get(), RHSType,
12728                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12729     else
12730       RHS = ImpCastExprToType(RHS.get(), LHSType,
12731                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12732     return computeResultTy();
12733   }
12734 
12735   // Handle block pointers.
12736   if (!IsOrdered && RHSIsNull
12737       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12738     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12739     return computeResultTy();
12740   }
12741   if (!IsOrdered && LHSIsNull
12742       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12743     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12744     return computeResultTy();
12745   }
12746 
12747   if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12748     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12749       return computeResultTy();
12750     }
12751 
12752     if (LHSType->isQueueT() && RHSType->isQueueT()) {
12753       return computeResultTy();
12754     }
12755 
12756     if (LHSIsNull && RHSType->isQueueT()) {
12757       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12758       return computeResultTy();
12759     }
12760 
12761     if (LHSType->isQueueT() && RHSIsNull) {
12762       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12763       return computeResultTy();
12764     }
12765   }
12766 
12767   return InvalidOperands(Loc, LHS, RHS);
12768 }
12769 
12770 // Return a signed ext_vector_type that is of identical size and number of
12771 // elements. For floating point vectors, return an integer type of identical
12772 // size and number of elements. In the non ext_vector_type case, search from
12773 // the largest type to the smallest type to avoid cases where long long == long,
12774 // where long gets picked over long long.
12775 QualType Sema::GetSignedVectorType(QualType V) {
12776   const VectorType *VTy = V->castAs<VectorType>();
12777   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12778 
12779   if (isa<ExtVectorType>(VTy)) {
12780     if (VTy->isExtVectorBoolType())
12781       return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
12782     if (TypeSize == Context.getTypeSize(Context.CharTy))
12783       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12784     if (TypeSize == Context.getTypeSize(Context.ShortTy))
12785       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12786     if (TypeSize == Context.getTypeSize(Context.IntTy))
12787       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12788     if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12789       return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
12790     if (TypeSize == Context.getTypeSize(Context.LongTy))
12791       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12792     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12793            "Unhandled vector element size in vector compare");
12794     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12795   }
12796 
12797   if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12798     return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
12799                                  VectorType::GenericVector);
12800   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12801     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12802                                  VectorType::GenericVector);
12803   if (TypeSize == Context.getTypeSize(Context.LongTy))
12804     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12805                                  VectorType::GenericVector);
12806   if (TypeSize == Context.getTypeSize(Context.IntTy))
12807     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12808                                  VectorType::GenericVector);
12809   if (TypeSize == Context.getTypeSize(Context.ShortTy))
12810     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12811                                  VectorType::GenericVector);
12812   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12813          "Unhandled vector element size in vector compare");
12814   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12815                                VectorType::GenericVector);
12816 }
12817 
12818 QualType Sema::GetSignedSizelessVectorType(QualType V) {
12819   const BuiltinType *VTy = V->castAs<BuiltinType>();
12820   assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
12821 
12822   const QualType ETy = V->getSveEltType(Context);
12823   const auto TypeSize = Context.getTypeSize(ETy);
12824 
12825   const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12826   const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12827   return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12828 }
12829 
12830 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12831 /// operates on extended vector types.  Instead of producing an IntTy result,
12832 /// like a scalar comparison, a vector comparison produces a vector of integer
12833 /// types.
12834 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12835                                           SourceLocation Loc,
12836                                           BinaryOperatorKind Opc) {
12837   if (Opc == BO_Cmp) {
12838     Diag(Loc, diag::err_three_way_vector_comparison);
12839     return QualType();
12840   }
12841 
12842   // Check to make sure we're operating on vectors of the same type and width,
12843   // Allowing one side to be a scalar of element type.
12844   QualType vType =
12845       CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12846                           /*AllowBothBool*/ true,
12847                           /*AllowBoolConversions*/ getLangOpts().ZVector,
12848                           /*AllowBooleanOperation*/ true,
12849                           /*ReportInvalid*/ true);
12850   if (vType.isNull())
12851     return vType;
12852 
12853   QualType LHSType = LHS.get()->getType();
12854 
12855   // Determine the return type of a vector compare. By default clang will return
12856   // a scalar for all vector compares except vector bool and vector pixel.
12857   // With the gcc compiler we will always return a vector type and with the xl
12858   // compiler we will always return a scalar type. This switch allows choosing
12859   // which behavior is prefered.
12860   if (getLangOpts().AltiVec) {
12861     switch (getLangOpts().getAltivecSrcCompat()) {
12862     case LangOptions::AltivecSrcCompatKind::Mixed:
12863       // If AltiVec, the comparison results in a numeric type, i.e.
12864       // bool for C++, int for C
12865       if (vType->castAs<VectorType>()->getVectorKind() ==
12866           VectorType::AltiVecVector)
12867         return Context.getLogicalOperationType();
12868       else
12869         Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12870       break;
12871     case LangOptions::AltivecSrcCompatKind::GCC:
12872       // For GCC we always return the vector type.
12873       break;
12874     case LangOptions::AltivecSrcCompatKind::XL:
12875       return Context.getLogicalOperationType();
12876       break;
12877     }
12878   }
12879 
12880   // For non-floating point types, check for self-comparisons of the form
12881   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12882   // often indicate logic errors in the program.
12883   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12884 
12885   // Check for comparisons of floating point operands using != and ==.
12886   if (BinaryOperator::isEqualityOp(Opc) &&
12887       LHSType->hasFloatingRepresentation()) {
12888     assert(RHS.get()->getType()->hasFloatingRepresentation());
12889     CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12890   }
12891 
12892   // Return a signed type for the vector.
12893   return GetSignedVectorType(vType);
12894 }
12895 
12896 QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
12897                                                   ExprResult &RHS,
12898                                                   SourceLocation Loc,
12899                                                   BinaryOperatorKind Opc) {
12900   if (Opc == BO_Cmp) {
12901     Diag(Loc, diag::err_three_way_vector_comparison);
12902     return QualType();
12903   }
12904 
12905   // Check to make sure we're operating on vectors of the same type and width,
12906   // Allowing one side to be a scalar of element type.
12907   QualType vType = CheckSizelessVectorOperands(
12908       LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12909 
12910   if (vType.isNull())
12911     return vType;
12912 
12913   QualType LHSType = LHS.get()->getType();
12914 
12915   // For non-floating point types, check for self-comparisons of the form
12916   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12917   // often indicate logic errors in the program.
12918   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12919 
12920   // Check for comparisons of floating point operands using != and ==.
12921   if (BinaryOperator::isEqualityOp(Opc) &&
12922       LHSType->hasFloatingRepresentation()) {
12923     assert(RHS.get()->getType()->hasFloatingRepresentation());
12924     CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12925   }
12926 
12927   const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12928   const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12929 
12930   if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12931       RHSBuiltinTy->isSVEBool())
12932     return LHSType;
12933 
12934   // Return a signed type for the vector.
12935   return GetSignedSizelessVectorType(vType);
12936 }
12937 
12938 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12939                                     const ExprResult &XorRHS,
12940                                     const SourceLocation Loc) {
12941   // Do not diagnose macros.
12942   if (Loc.isMacroID())
12943     return;
12944 
12945   // Do not diagnose if both LHS and RHS are macros.
12946   if (XorLHS.get()->getExprLoc().isMacroID() &&
12947       XorRHS.get()->getExprLoc().isMacroID())
12948     return;
12949 
12950   bool Negative = false;
12951   bool ExplicitPlus = false;
12952   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12953   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12954 
12955   if (!LHSInt)
12956     return;
12957   if (!RHSInt) {
12958     // Check negative literals.
12959     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12960       UnaryOperatorKind Opc = UO->getOpcode();
12961       if (Opc != UO_Minus && Opc != UO_Plus)
12962         return;
12963       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12964       if (!RHSInt)
12965         return;
12966       Negative = (Opc == UO_Minus);
12967       ExplicitPlus = !Negative;
12968     } else {
12969       return;
12970     }
12971   }
12972 
12973   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12974   llvm::APInt RightSideValue = RHSInt->getValue();
12975   if (LeftSideValue != 2 && LeftSideValue != 10)
12976     return;
12977 
12978   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12979     return;
12980 
12981   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12982       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12983   llvm::StringRef ExprStr =
12984       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12985 
12986   CharSourceRange XorRange =
12987       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12988   llvm::StringRef XorStr =
12989       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12990   // Do not diagnose if xor keyword/macro is used.
12991   if (XorStr == "xor")
12992     return;
12993 
12994   std::string LHSStr = std::string(Lexer::getSourceText(
12995       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12996       S.getSourceManager(), S.getLangOpts()));
12997   std::string RHSStr = std::string(Lexer::getSourceText(
12998       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12999       S.getSourceManager(), S.getLangOpts()));
13000 
13001   if (Negative) {
13002     RightSideValue = -RightSideValue;
13003     RHSStr = "-" + RHSStr;
13004   } else if (ExplicitPlus) {
13005     RHSStr = "+" + RHSStr;
13006   }
13007 
13008   StringRef LHSStrRef = LHSStr;
13009   StringRef RHSStrRef = RHSStr;
13010   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13011   // literals.
13012   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
13013       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
13014       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
13015       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
13016       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
13017       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
13018       LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13019     return;
13020 
13021   bool SuggestXor =
13022       S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13023   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13024   int64_t RightSideIntValue = RightSideValue.getSExtValue();
13025   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13026     std::string SuggestedExpr = "1 << " + RHSStr;
13027     bool Overflow = false;
13028     llvm::APInt One = (LeftSideValue - 1);
13029     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13030     if (Overflow) {
13031       if (RightSideIntValue < 64)
13032         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13033             << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13034             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13035       else if (RightSideIntValue == 64)
13036         S.Diag(Loc, diag::warn_xor_used_as_pow)
13037             << ExprStr << toString(XorValue, 10, true);
13038       else
13039         return;
13040     } else {
13041       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13042           << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13043           << toString(PowValue, 10, true)
13044           << FixItHint::CreateReplacement(
13045                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13046     }
13047 
13048     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13049         << ("0x2 ^ " + RHSStr) << SuggestXor;
13050   } else if (LeftSideValue == 10) {
13051     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13052     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13053         << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13054         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13055     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13056         << ("0xA ^ " + RHSStr) << SuggestXor;
13057   }
13058 }
13059 
13060 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13061                                           SourceLocation Loc) {
13062   // Ensure that either both operands are of the same vector type, or
13063   // one operand is of a vector type and the other is of its element type.
13064   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13065                                        /*AllowBothBool*/ true,
13066                                        /*AllowBoolConversions*/ false,
13067                                        /*AllowBooleanOperation*/ false,
13068                                        /*ReportInvalid*/ false);
13069   if (vType.isNull())
13070     return InvalidOperands(Loc, LHS, RHS);
13071   if (getLangOpts().OpenCL &&
13072       getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13073       vType->hasFloatingRepresentation())
13074     return InvalidOperands(Loc, LHS, RHS);
13075   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13076   //        usage of the logical operators && and || with vectors in C. This
13077   //        check could be notionally dropped.
13078   if (!getLangOpts().CPlusPlus &&
13079       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13080     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13081 
13082   return GetSignedVectorType(LHS.get()->getType());
13083 }
13084 
13085 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13086                                               SourceLocation Loc,
13087                                               bool IsCompAssign) {
13088   if (!IsCompAssign) {
13089     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13090     if (LHS.isInvalid())
13091       return QualType();
13092   }
13093   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13094   if (RHS.isInvalid())
13095     return QualType();
13096 
13097   // For conversion purposes, we ignore any qualifiers.
13098   // For example, "const float" and "float" are equivalent.
13099   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13100   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13101 
13102   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13103   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13104   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13105 
13106   if (Context.hasSameType(LHSType, RHSType))
13107     return LHSType;
13108 
13109   // Type conversion may change LHS/RHS. Keep copies to the original results, in
13110   // case we have to return InvalidOperands.
13111   ExprResult OriginalLHS = LHS;
13112   ExprResult OriginalRHS = RHS;
13113   if (LHSMatType && !RHSMatType) {
13114     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13115     if (!RHS.isInvalid())
13116       return LHSType;
13117 
13118     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13119   }
13120 
13121   if (!LHSMatType && RHSMatType) {
13122     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13123     if (!LHS.isInvalid())
13124       return RHSType;
13125     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13126   }
13127 
13128   return InvalidOperands(Loc, LHS, RHS);
13129 }
13130 
13131 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13132                                            SourceLocation Loc,
13133                                            bool IsCompAssign) {
13134   if (!IsCompAssign) {
13135     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13136     if (LHS.isInvalid())
13137       return QualType();
13138   }
13139   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13140   if (RHS.isInvalid())
13141     return QualType();
13142 
13143   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13144   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13145   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13146 
13147   if (LHSMatType && RHSMatType) {
13148     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13149       return InvalidOperands(Loc, LHS, RHS);
13150 
13151     if (!Context.hasSameType(LHSMatType->getElementType(),
13152                              RHSMatType->getElementType()))
13153       return InvalidOperands(Loc, LHS, RHS);
13154 
13155     return Context.getConstantMatrixType(LHSMatType->getElementType(),
13156                                          LHSMatType->getNumRows(),
13157                                          RHSMatType->getNumColumns());
13158   }
13159   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13160 }
13161 
13162 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13163   switch (Opc) {
13164   default:
13165     return false;
13166   case BO_And:
13167   case BO_AndAssign:
13168   case BO_Or:
13169   case BO_OrAssign:
13170   case BO_Xor:
13171   case BO_XorAssign:
13172     return true;
13173   }
13174 }
13175 
13176 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13177                                            SourceLocation Loc,
13178                                            BinaryOperatorKind Opc) {
13179   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13180 
13181   bool IsCompAssign =
13182       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13183 
13184   bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13185 
13186   if (LHS.get()->getType()->isVectorType() ||
13187       RHS.get()->getType()->isVectorType()) {
13188     if (LHS.get()->getType()->hasIntegerRepresentation() &&
13189         RHS.get()->getType()->hasIntegerRepresentation())
13190       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13191                                  /*AllowBothBool*/ true,
13192                                  /*AllowBoolConversions*/ getLangOpts().ZVector,
13193                                  /*AllowBooleanOperation*/ LegalBoolVecOperator,
13194                                  /*ReportInvalid*/ true);
13195     return InvalidOperands(Loc, LHS, RHS);
13196   }
13197 
13198   if (LHS.get()->getType()->isVLSTBuiltinType() ||
13199       RHS.get()->getType()->isVLSTBuiltinType()) {
13200     if (LHS.get()->getType()->hasIntegerRepresentation() &&
13201         RHS.get()->getType()->hasIntegerRepresentation())
13202       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13203                                          ACK_BitwiseOp);
13204     return InvalidOperands(Loc, LHS, RHS);
13205   }
13206 
13207   if (LHS.get()->getType()->isVLSTBuiltinType() ||
13208       RHS.get()->getType()->isVLSTBuiltinType()) {
13209     if (LHS.get()->getType()->hasIntegerRepresentation() &&
13210         RHS.get()->getType()->hasIntegerRepresentation())
13211       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13212                                          ACK_BitwiseOp);
13213     return InvalidOperands(Loc, LHS, RHS);
13214   }
13215 
13216   if (Opc == BO_And)
13217     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13218 
13219   if (LHS.get()->getType()->hasFloatingRepresentation() ||
13220       RHS.get()->getType()->hasFloatingRepresentation())
13221     return InvalidOperands(Loc, LHS, RHS);
13222 
13223   ExprResult LHSResult = LHS, RHSResult = RHS;
13224   QualType compType = UsualArithmeticConversions(
13225       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13226   if (LHSResult.isInvalid() || RHSResult.isInvalid())
13227     return QualType();
13228   LHS = LHSResult.get();
13229   RHS = RHSResult.get();
13230 
13231   if (Opc == BO_Xor)
13232     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13233 
13234   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13235     return compType;
13236   return InvalidOperands(Loc, LHS, RHS);
13237 }
13238 
13239 // C99 6.5.[13,14]
13240 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13241                                            SourceLocation Loc,
13242                                            BinaryOperatorKind Opc) {
13243   // Check vector operands differently.
13244   if (LHS.get()->getType()->isVectorType() ||
13245       RHS.get()->getType()->isVectorType())
13246     return CheckVectorLogicalOperands(LHS, RHS, Loc);
13247 
13248   bool EnumConstantInBoolContext = false;
13249   for (const ExprResult &HS : {LHS, RHS}) {
13250     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13251       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13252       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13253         EnumConstantInBoolContext = true;
13254     }
13255   }
13256 
13257   if (EnumConstantInBoolContext)
13258     Diag(Loc, diag::warn_enum_constant_in_bool_context);
13259 
13260   // Diagnose cases where the user write a logical and/or but probably meant a
13261   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
13262   // is a constant.
13263   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13264       !LHS.get()->getType()->isBooleanType() &&
13265       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13266       // Don't warn in macros or template instantiations.
13267       !Loc.isMacroID() && !inTemplateInstantiation()) {
13268     // If the RHS can be constant folded, and if it constant folds to something
13269     // that isn't 0 or 1 (which indicate a potential logical operation that
13270     // happened to fold to true/false) then warn.
13271     // Parens on the RHS are ignored.
13272     Expr::EvalResult EVResult;
13273     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13274       llvm::APSInt Result = EVResult.Val.getInt();
13275       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
13276            !RHS.get()->getExprLoc().isMacroID()) ||
13277           (Result != 0 && Result != 1)) {
13278         Diag(Loc, diag::warn_logical_instead_of_bitwise)
13279             << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13280         // Suggest replacing the logical operator with the bitwise version
13281         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13282             << (Opc == BO_LAnd ? "&" : "|")
13283             << FixItHint::CreateReplacement(
13284                    SourceRange(Loc, getLocForEndOfToken(Loc)),
13285                    Opc == BO_LAnd ? "&" : "|");
13286         if (Opc == BO_LAnd)
13287           // Suggest replacing "Foo() && kNonZero" with "Foo()"
13288           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13289               << FixItHint::CreateRemoval(
13290                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
13291                                  RHS.get()->getEndLoc()));
13292       }
13293     }
13294   }
13295 
13296   if (!Context.getLangOpts().CPlusPlus) {
13297     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13298     // not operate on the built-in scalar and vector float types.
13299     if (Context.getLangOpts().OpenCL &&
13300         Context.getLangOpts().OpenCLVersion < 120) {
13301       if (LHS.get()->getType()->isFloatingType() ||
13302           RHS.get()->getType()->isFloatingType())
13303         return InvalidOperands(Loc, LHS, RHS);
13304     }
13305 
13306     LHS = UsualUnaryConversions(LHS.get());
13307     if (LHS.isInvalid())
13308       return QualType();
13309 
13310     RHS = UsualUnaryConversions(RHS.get());
13311     if (RHS.isInvalid())
13312       return QualType();
13313 
13314     if (!LHS.get()->getType()->isScalarType() ||
13315         !RHS.get()->getType()->isScalarType())
13316       return InvalidOperands(Loc, LHS, RHS);
13317 
13318     return Context.IntTy;
13319   }
13320 
13321   // The following is safe because we only use this method for
13322   // non-overloadable operands.
13323 
13324   // C++ [expr.log.and]p1
13325   // C++ [expr.log.or]p1
13326   // The operands are both contextually converted to type bool.
13327   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
13328   if (LHSRes.isInvalid())
13329     return InvalidOperands(Loc, LHS, RHS);
13330   LHS = LHSRes;
13331 
13332   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
13333   if (RHSRes.isInvalid())
13334     return InvalidOperands(Loc, LHS, RHS);
13335   RHS = RHSRes;
13336 
13337   // C++ [expr.log.and]p2
13338   // C++ [expr.log.or]p2
13339   // The result is a bool.
13340   return Context.BoolTy;
13341 }
13342 
13343 static bool IsReadonlyMessage(Expr *E, Sema &S) {
13344   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13345   if (!ME) return false;
13346   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13347   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13348       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13349   if (!Base) return false;
13350   return Base->getMethodDecl() != nullptr;
13351 }
13352 
13353 /// Is the given expression (which must be 'const') a reference to a
13354 /// variable which was originally non-const, but which has become
13355 /// 'const' due to being captured within a block?
13356 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13357 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13358   assert(E->isLValue() && E->getType().isConstQualified());
13359   E = E->IgnoreParens();
13360 
13361   // Must be a reference to a declaration from an enclosing scope.
13362   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13363   if (!DRE) return NCCK_None;
13364   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13365 
13366   // The declaration must be a variable which is not declared 'const'.
13367   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13368   if (!var) return NCCK_None;
13369   if (var->getType().isConstQualified()) return NCCK_None;
13370   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
13371 
13372   // Decide whether the first capture was for a block or a lambda.
13373   DeclContext *DC = S.CurContext, *Prev = nullptr;
13374   // Decide whether the first capture was for a block or a lambda.
13375   while (DC) {
13376     // For init-capture, it is possible that the variable belongs to the
13377     // template pattern of the current context.
13378     if (auto *FD = dyn_cast<FunctionDecl>(DC))
13379       if (var->isInitCapture() &&
13380           FD->getTemplateInstantiationPattern() == var->getDeclContext())
13381         break;
13382     if (DC == var->getDeclContext())
13383       break;
13384     Prev = DC;
13385     DC = DC->getParent();
13386   }
13387   // Unless we have an init-capture, we've gone one step too far.
13388   if (!var->isInitCapture())
13389     DC = Prev;
13390   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13391 }
13392 
13393 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13394   Ty = Ty.getNonReferenceType();
13395   if (IsDereference && Ty->isPointerType())
13396     Ty = Ty->getPointeeType();
13397   return !Ty.isConstQualified();
13398 }
13399 
13400 // Update err_typecheck_assign_const and note_typecheck_assign_const
13401 // when this enum is changed.
13402 enum {
13403   ConstFunction,
13404   ConstVariable,
13405   ConstMember,
13406   ConstMethod,
13407   NestedConstMember,
13408   ConstUnknown,  // Keep as last element
13409 };
13410 
13411 /// Emit the "read-only variable not assignable" error and print notes to give
13412 /// more information about why the variable is not assignable, such as pointing
13413 /// to the declaration of a const variable, showing that a method is const, or
13414 /// that the function is returning a const reference.
13415 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13416                                     SourceLocation Loc) {
13417   SourceRange ExprRange = E->getSourceRange();
13418 
13419   // Only emit one error on the first const found.  All other consts will emit
13420   // a note to the error.
13421   bool DiagnosticEmitted = false;
13422 
13423   // Track if the current expression is the result of a dereference, and if the
13424   // next checked expression is the result of a dereference.
13425   bool IsDereference = false;
13426   bool NextIsDereference = false;
13427 
13428   // Loop to process MemberExpr chains.
13429   while (true) {
13430     IsDereference = NextIsDereference;
13431 
13432     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13433     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13434       NextIsDereference = ME->isArrow();
13435       const ValueDecl *VD = ME->getMemberDecl();
13436       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13437         // Mutable fields can be modified even if the class is const.
13438         if (Field->isMutable()) {
13439           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13440           break;
13441         }
13442 
13443         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13444           if (!DiagnosticEmitted) {
13445             S.Diag(Loc, diag::err_typecheck_assign_const)
13446                 << ExprRange << ConstMember << false /*static*/ << Field
13447                 << Field->getType();
13448             DiagnosticEmitted = true;
13449           }
13450           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13451               << ConstMember << false /*static*/ << Field << Field->getType()
13452               << Field->getSourceRange();
13453         }
13454         E = ME->getBase();
13455         continue;
13456       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13457         if (VDecl->getType().isConstQualified()) {
13458           if (!DiagnosticEmitted) {
13459             S.Diag(Loc, diag::err_typecheck_assign_const)
13460                 << ExprRange << ConstMember << true /*static*/ << VDecl
13461                 << VDecl->getType();
13462             DiagnosticEmitted = true;
13463           }
13464           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13465               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13466               << VDecl->getSourceRange();
13467         }
13468         // Static fields do not inherit constness from parents.
13469         break;
13470       }
13471       break; // End MemberExpr
13472     } else if (const ArraySubscriptExpr *ASE =
13473                    dyn_cast<ArraySubscriptExpr>(E)) {
13474       E = ASE->getBase()->IgnoreParenImpCasts();
13475       continue;
13476     } else if (const ExtVectorElementExpr *EVE =
13477                    dyn_cast<ExtVectorElementExpr>(E)) {
13478       E = EVE->getBase()->IgnoreParenImpCasts();
13479       continue;
13480     }
13481     break;
13482   }
13483 
13484   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13485     // Function calls
13486     const FunctionDecl *FD = CE->getDirectCallee();
13487     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13488       if (!DiagnosticEmitted) {
13489         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13490                                                       << ConstFunction << FD;
13491         DiagnosticEmitted = true;
13492       }
13493       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13494              diag::note_typecheck_assign_const)
13495           << ConstFunction << FD << FD->getReturnType()
13496           << FD->getReturnTypeSourceRange();
13497     }
13498   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13499     // Point to variable declaration.
13500     if (const ValueDecl *VD = DRE->getDecl()) {
13501       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13502         if (!DiagnosticEmitted) {
13503           S.Diag(Loc, diag::err_typecheck_assign_const)
13504               << ExprRange << ConstVariable << VD << VD->getType();
13505           DiagnosticEmitted = true;
13506         }
13507         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13508             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13509       }
13510     }
13511   } else if (isa<CXXThisExpr>(E)) {
13512     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13513       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13514         if (MD->isConst()) {
13515           if (!DiagnosticEmitted) {
13516             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13517                                                           << ConstMethod << MD;
13518             DiagnosticEmitted = true;
13519           }
13520           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13521               << ConstMethod << MD << MD->getSourceRange();
13522         }
13523       }
13524     }
13525   }
13526 
13527   if (DiagnosticEmitted)
13528     return;
13529 
13530   // Can't determine a more specific message, so display the generic error.
13531   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13532 }
13533 
13534 enum OriginalExprKind {
13535   OEK_Variable,
13536   OEK_Member,
13537   OEK_LValue
13538 };
13539 
13540 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13541                                          const RecordType *Ty,
13542                                          SourceLocation Loc, SourceRange Range,
13543                                          OriginalExprKind OEK,
13544                                          bool &DiagnosticEmitted) {
13545   std::vector<const RecordType *> RecordTypeList;
13546   RecordTypeList.push_back(Ty);
13547   unsigned NextToCheckIndex = 0;
13548   // We walk the record hierarchy breadth-first to ensure that we print
13549   // diagnostics in field nesting order.
13550   while (RecordTypeList.size() > NextToCheckIndex) {
13551     bool IsNested = NextToCheckIndex > 0;
13552     for (const FieldDecl *Field :
13553          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13554       // First, check every field for constness.
13555       QualType FieldTy = Field->getType();
13556       if (FieldTy.isConstQualified()) {
13557         if (!DiagnosticEmitted) {
13558           S.Diag(Loc, diag::err_typecheck_assign_const)
13559               << Range << NestedConstMember << OEK << VD
13560               << IsNested << Field;
13561           DiagnosticEmitted = true;
13562         }
13563         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13564             << NestedConstMember << IsNested << Field
13565             << FieldTy << Field->getSourceRange();
13566       }
13567 
13568       // Then we append it to the list to check next in order.
13569       FieldTy = FieldTy.getCanonicalType();
13570       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13571         if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13572           RecordTypeList.push_back(FieldRecTy);
13573       }
13574     }
13575     ++NextToCheckIndex;
13576   }
13577 }
13578 
13579 /// Emit an error for the case where a record we are trying to assign to has a
13580 /// const-qualified field somewhere in its hierarchy.
13581 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13582                                          SourceLocation Loc) {
13583   QualType Ty = E->getType();
13584   assert(Ty->isRecordType() && "lvalue was not record?");
13585   SourceRange Range = E->getSourceRange();
13586   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13587   bool DiagEmitted = false;
13588 
13589   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13590     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13591             Range, OEK_Member, DiagEmitted);
13592   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13593     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13594             Range, OEK_Variable, DiagEmitted);
13595   else
13596     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13597             Range, OEK_LValue, DiagEmitted);
13598   if (!DiagEmitted)
13599     DiagnoseConstAssignment(S, E, Loc);
13600 }
13601 
13602 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
13603 /// emit an error and return true.  If so, return false.
13604 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
13605   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13606 
13607   S.CheckShadowingDeclModification(E, Loc);
13608 
13609   SourceLocation OrigLoc = Loc;
13610   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
13611                                                               &Loc);
13612   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13613     IsLV = Expr::MLV_InvalidMessageExpression;
13614   if (IsLV == Expr::MLV_Valid)
13615     return false;
13616 
13617   unsigned DiagID = 0;
13618   bool NeedType = false;
13619   switch (IsLV) { // C99 6.5.16p2
13620   case Expr::MLV_ConstQualified:
13621     // Use a specialized diagnostic when we're assigning to an object
13622     // from an enclosing function or block.
13623     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
13624       if (NCCK == NCCK_Block)
13625         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13626       else
13627         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13628       break;
13629     }
13630 
13631     // In ARC, use some specialized diagnostics for occasions where we
13632     // infer 'const'.  These are always pseudo-strong variables.
13633     if (S.getLangOpts().ObjCAutoRefCount) {
13634       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13635       if (declRef && isa<VarDecl>(declRef->getDecl())) {
13636         VarDecl *var = cast<VarDecl>(declRef->getDecl());
13637 
13638         // Use the normal diagnostic if it's pseudo-__strong but the
13639         // user actually wrote 'const'.
13640         if (var->isARCPseudoStrong() &&
13641             (!var->getTypeSourceInfo() ||
13642              !var->getTypeSourceInfo()->getType().isConstQualified())) {
13643           // There are three pseudo-strong cases:
13644           //  - self
13645           ObjCMethodDecl *method = S.getCurMethodDecl();
13646           if (method && var == method->getSelfDecl()) {
13647             DiagID = method->isClassMethod()
13648               ? diag::err_typecheck_arc_assign_self_class_method
13649               : diag::err_typecheck_arc_assign_self;
13650 
13651           //  - Objective-C externally_retained attribute.
13652           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13653                      isa<ParmVarDecl>(var)) {
13654             DiagID = diag::err_typecheck_arc_assign_externally_retained;
13655 
13656           //  - fast enumeration variables
13657           } else {
13658             DiagID = diag::err_typecheck_arr_assign_enumeration;
13659           }
13660 
13661           SourceRange Assign;
13662           if (Loc != OrigLoc)
13663             Assign = SourceRange(OrigLoc, OrigLoc);
13664           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13665           // We need to preserve the AST regardless, so migration tool
13666           // can do its job.
13667           return false;
13668         }
13669       }
13670     }
13671 
13672     // If none of the special cases above are triggered, then this is a
13673     // simple const assignment.
13674     if (DiagID == 0) {
13675       DiagnoseConstAssignment(S, E, Loc);
13676       return true;
13677     }
13678 
13679     break;
13680   case Expr::MLV_ConstAddrSpace:
13681     DiagnoseConstAssignment(S, E, Loc);
13682     return true;
13683   case Expr::MLV_ConstQualifiedField:
13684     DiagnoseRecursiveConstFields(S, E, Loc);
13685     return true;
13686   case Expr::MLV_ArrayType:
13687   case Expr::MLV_ArrayTemporary:
13688     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13689     NeedType = true;
13690     break;
13691   case Expr::MLV_NotObjectType:
13692     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13693     NeedType = true;
13694     break;
13695   case Expr::MLV_LValueCast:
13696     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13697     break;
13698   case Expr::MLV_Valid:
13699     llvm_unreachable("did not take early return for MLV_Valid");
13700   case Expr::MLV_InvalidExpression:
13701   case Expr::MLV_MemberFunction:
13702   case Expr::MLV_ClassTemporary:
13703     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13704     break;
13705   case Expr::MLV_IncompleteType:
13706   case Expr::MLV_IncompleteVoidType:
13707     return S.RequireCompleteType(Loc, E->getType(),
13708              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13709   case Expr::MLV_DuplicateVectorComponents:
13710     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13711     break;
13712   case Expr::MLV_NoSetterProperty:
13713     llvm_unreachable("readonly properties should be processed differently");
13714   case Expr::MLV_InvalidMessageExpression:
13715     DiagID = diag::err_readonly_message_assignment;
13716     break;
13717   case Expr::MLV_SubObjCPropertySetting:
13718     DiagID = diag::err_no_subobject_property_setting;
13719     break;
13720   }
13721 
13722   SourceRange Assign;
13723   if (Loc != OrigLoc)
13724     Assign = SourceRange(OrigLoc, OrigLoc);
13725   if (NeedType)
13726     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13727   else
13728     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13729   return true;
13730 }
13731 
13732 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13733                                          SourceLocation Loc,
13734                                          Sema &Sema) {
13735   if (Sema.inTemplateInstantiation())
13736     return;
13737   if (Sema.isUnevaluatedContext())
13738     return;
13739   if (Loc.isInvalid() || Loc.isMacroID())
13740     return;
13741   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13742     return;
13743 
13744   // C / C++ fields
13745   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13746   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13747   if (ML && MR) {
13748     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13749       return;
13750     const ValueDecl *LHSDecl =
13751         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13752     const ValueDecl *RHSDecl =
13753         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13754     if (LHSDecl != RHSDecl)
13755       return;
13756     if (LHSDecl->getType().isVolatileQualified())
13757       return;
13758     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13759       if (RefTy->getPointeeType().isVolatileQualified())
13760         return;
13761 
13762     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13763   }
13764 
13765   // Objective-C instance variables
13766   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13767   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13768   if (OL && OR && OL->getDecl() == OR->getDecl()) {
13769     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13770     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13771     if (RL && RR && RL->getDecl() == RR->getDecl())
13772       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13773   }
13774 }
13775 
13776 // C99 6.5.16.1
13777 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13778                                        SourceLocation Loc,
13779                                        QualType CompoundType) {
13780   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13781 
13782   // Verify that LHS is a modifiable lvalue, and emit error if not.
13783   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13784     return QualType();
13785 
13786   QualType LHSType = LHSExpr->getType();
13787   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13788                                              CompoundType;
13789   // OpenCL v1.2 s6.1.1.1 p2:
13790   // The half data type can only be used to declare a pointer to a buffer that
13791   // contains half values
13792   if (getLangOpts().OpenCL &&
13793       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13794       LHSType->isHalfType()) {
13795     Diag(Loc, diag::err_opencl_half_load_store) << 1
13796         << LHSType.getUnqualifiedType();
13797     return QualType();
13798   }
13799 
13800   AssignConvertType ConvTy;
13801   if (CompoundType.isNull()) {
13802     Expr *RHSCheck = RHS.get();
13803 
13804     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13805 
13806     QualType LHSTy(LHSType);
13807     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13808     if (RHS.isInvalid())
13809       return QualType();
13810     // Special case of NSObject attributes on c-style pointer types.
13811     if (ConvTy == IncompatiblePointer &&
13812         ((Context.isObjCNSObjectType(LHSType) &&
13813           RHSType->isObjCObjectPointerType()) ||
13814          (Context.isObjCNSObjectType(RHSType) &&
13815           LHSType->isObjCObjectPointerType())))
13816       ConvTy = Compatible;
13817 
13818     if (ConvTy == Compatible &&
13819         LHSType->isObjCObjectType())
13820         Diag(Loc, diag::err_objc_object_assignment)
13821           << LHSType;
13822 
13823     // If the RHS is a unary plus or minus, check to see if they = and + are
13824     // right next to each other.  If so, the user may have typo'd "x =+ 4"
13825     // instead of "x += 4".
13826     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13827       RHSCheck = ICE->getSubExpr();
13828     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13829       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13830           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13831           // Only if the two operators are exactly adjacent.
13832           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13833           // And there is a space or other character before the subexpr of the
13834           // unary +/-.  We don't want to warn on "x=-1".
13835           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13836           UO->getSubExpr()->getBeginLoc().isFileID()) {
13837         Diag(Loc, diag::warn_not_compound_assign)
13838           << (UO->getOpcode() == UO_Plus ? "+" : "-")
13839           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13840       }
13841     }
13842 
13843     if (ConvTy == Compatible) {
13844       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13845         // Warn about retain cycles where a block captures the LHS, but
13846         // not if the LHS is a simple variable into which the block is
13847         // being stored...unless that variable can be captured by reference!
13848         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13849         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13850         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13851           checkRetainCycles(LHSExpr, RHS.get());
13852       }
13853 
13854       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13855           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13856         // It is safe to assign a weak reference into a strong variable.
13857         // Although this code can still have problems:
13858         //   id x = self.weakProp;
13859         //   id y = self.weakProp;
13860         // we do not warn to warn spuriously when 'x' and 'y' are on separate
13861         // paths through the function. This should be revisited if
13862         // -Wrepeated-use-of-weak is made flow-sensitive.
13863         // For ObjCWeak only, we do not warn if the assign is to a non-weak
13864         // variable, which will be valid for the current autorelease scope.
13865         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13866                              RHS.get()->getBeginLoc()))
13867           getCurFunction()->markSafeWeakUse(RHS.get());
13868 
13869       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13870         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13871       }
13872     }
13873   } else {
13874     // Compound assignment "x += y"
13875     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13876   }
13877 
13878   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13879                                RHS.get(), AA_Assigning))
13880     return QualType();
13881 
13882   CheckForNullPointerDereference(*this, LHSExpr);
13883 
13884   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13885     if (CompoundType.isNull()) {
13886       // C++2a [expr.ass]p5:
13887       //   A simple-assignment whose left operand is of a volatile-qualified
13888       //   type is deprecated unless the assignment is either a discarded-value
13889       //   expression or an unevaluated operand
13890       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13891     } else {
13892       // C++2a [expr.ass]p6:
13893       //   [Compound-assignment] expressions are deprecated if E1 has
13894       //   volatile-qualified type
13895       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13896     }
13897   }
13898 
13899   // C11 6.5.16p3: The type of an assignment expression is the type of the
13900   // left operand would have after lvalue conversion.
13901   // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13902   // qualified type, the value has the unqualified version of the type of the
13903   // lvalue; additionally, if the lvalue has atomic type, the value has the
13904   // non-atomic version of the type of the lvalue.
13905   // C++ 5.17p1: the type of the assignment expression is that of its left
13906   // operand.
13907   return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13908 }
13909 
13910 // Only ignore explicit casts to void.
13911 static bool IgnoreCommaOperand(const Expr *E) {
13912   E = E->IgnoreParens();
13913 
13914   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13915     if (CE->getCastKind() == CK_ToVoid) {
13916       return true;
13917     }
13918 
13919     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13920     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13921         CE->getSubExpr()->getType()->isDependentType()) {
13922       return true;
13923     }
13924   }
13925 
13926   return false;
13927 }
13928 
13929 // Look for instances where it is likely the comma operator is confused with
13930 // another operator.  There is an explicit list of acceptable expressions for
13931 // the left hand side of the comma operator, otherwise emit a warning.
13932 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13933   // No warnings in macros
13934   if (Loc.isMacroID())
13935     return;
13936 
13937   // Don't warn in template instantiations.
13938   if (inTemplateInstantiation())
13939     return;
13940 
13941   // Scope isn't fine-grained enough to explicitly list the specific cases, so
13942   // instead, skip more than needed, then call back into here with the
13943   // CommaVisitor in SemaStmt.cpp.
13944   // The listed locations are the initialization and increment portions
13945   // of a for loop.  The additional checks are on the condition of
13946   // if statements, do/while loops, and for loops.
13947   // Differences in scope flags for C89 mode requires the extra logic.
13948   const unsigned ForIncrementFlags =
13949       getLangOpts().C99 || getLangOpts().CPlusPlus
13950           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13951           : Scope::ContinueScope | Scope::BreakScope;
13952   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13953   const unsigned ScopeFlags = getCurScope()->getFlags();
13954   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13955       (ScopeFlags & ForInitFlags) == ForInitFlags)
13956     return;
13957 
13958   // If there are multiple comma operators used together, get the RHS of the
13959   // of the comma operator as the LHS.
13960   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13961     if (BO->getOpcode() != BO_Comma)
13962       break;
13963     LHS = BO->getRHS();
13964   }
13965 
13966   // Only allow some expressions on LHS to not warn.
13967   if (IgnoreCommaOperand(LHS))
13968     return;
13969 
13970   Diag(Loc, diag::warn_comma_operator);
13971   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13972       << LHS->getSourceRange()
13973       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13974                                     LangOpts.CPlusPlus ? "static_cast<void>("
13975                                                        : "(void)(")
13976       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13977                                     ")");
13978 }
13979 
13980 // C99 6.5.17
13981 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13982                                    SourceLocation Loc) {
13983   LHS = S.CheckPlaceholderExpr(LHS.get());
13984   RHS = S.CheckPlaceholderExpr(RHS.get());
13985   if (LHS.isInvalid() || RHS.isInvalid())
13986     return QualType();
13987 
13988   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13989   // operands, but not unary promotions.
13990   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13991 
13992   // So we treat the LHS as a ignored value, and in C++ we allow the
13993   // containing site to determine what should be done with the RHS.
13994   LHS = S.IgnoredValueConversions(LHS.get());
13995   if (LHS.isInvalid())
13996     return QualType();
13997 
13998   S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13999 
14000   if (!S.getLangOpts().CPlusPlus) {
14001     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
14002     if (RHS.isInvalid())
14003       return QualType();
14004     if (!RHS.get()->getType()->isVoidType())
14005       S.RequireCompleteType(Loc, RHS.get()->getType(),
14006                             diag::err_incomplete_type);
14007   }
14008 
14009   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14010     S.DiagnoseCommaOperator(LHS.get(), Loc);
14011 
14012   return RHS.get()->getType();
14013 }
14014 
14015 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14016 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14017 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14018                                                ExprValueKind &VK,
14019                                                ExprObjectKind &OK,
14020                                                SourceLocation OpLoc,
14021                                                bool IsInc, bool IsPrefix) {
14022   if (Op->isTypeDependent())
14023     return S.Context.DependentTy;
14024 
14025   QualType ResType = Op->getType();
14026   // Atomic types can be used for increment / decrement where the non-atomic
14027   // versions can, so ignore the _Atomic() specifier for the purpose of
14028   // checking.
14029   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14030     ResType = ResAtomicType->getValueType();
14031 
14032   assert(!ResType.isNull() && "no type for increment/decrement expression");
14033 
14034   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14035     // Decrement of bool is not allowed.
14036     if (!IsInc) {
14037       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14038       return QualType();
14039     }
14040     // Increment of bool sets it to true, but is deprecated.
14041     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14042                                               : diag::warn_increment_bool)
14043       << Op->getSourceRange();
14044   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14045     // Error on enum increments and decrements in C++ mode
14046     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14047     return QualType();
14048   } else if (ResType->isRealType()) {
14049     // OK!
14050   } else if (ResType->isPointerType()) {
14051     // C99 6.5.2.4p2, 6.5.6p2
14052     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14053       return QualType();
14054   } else if (ResType->isObjCObjectPointerType()) {
14055     // On modern runtimes, ObjC pointer arithmetic is forbidden.
14056     // Otherwise, we just need a complete type.
14057     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14058         checkArithmeticOnObjCPointer(S, OpLoc, Op))
14059       return QualType();
14060   } else if (ResType->isAnyComplexType()) {
14061     // C99 does not support ++/-- on complex types, we allow as an extension.
14062     S.Diag(OpLoc, diag::ext_integer_increment_complex)
14063       << ResType << Op->getSourceRange();
14064   } else if (ResType->isPlaceholderType()) {
14065     ExprResult PR = S.CheckPlaceholderExpr(Op);
14066     if (PR.isInvalid()) return QualType();
14067     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14068                                           IsInc, IsPrefix);
14069   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14070     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14071   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14072              (ResType->castAs<VectorType>()->getVectorKind() !=
14073               VectorType::AltiVecBool)) {
14074     // The z vector extensions allow ++ and -- for non-bool vectors.
14075   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
14076             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14077     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14078   } else {
14079     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14080       << ResType << int(IsInc) << Op->getSourceRange();
14081     return QualType();
14082   }
14083   // At this point, we know we have a real, complex or pointer type.
14084   // Now make sure the operand is a modifiable lvalue.
14085   if (CheckForModifiableLvalue(Op, OpLoc, S))
14086     return QualType();
14087   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14088     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14089     //   An operand with volatile-qualified type is deprecated
14090     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14091         << IsInc << ResType;
14092   }
14093   // In C++, a prefix increment is the same type as the operand. Otherwise
14094   // (in C or with postfix), the increment is the unqualified type of the
14095   // operand.
14096   if (IsPrefix && S.getLangOpts().CPlusPlus) {
14097     VK = VK_LValue;
14098     OK = Op->getObjectKind();
14099     return ResType;
14100   } else {
14101     VK = VK_PRValue;
14102     return ResType.getUnqualifiedType();
14103   }
14104 }
14105 
14106 
14107 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14108 /// This routine allows us to typecheck complex/recursive expressions
14109 /// where the declaration is needed for type checking. We only need to
14110 /// handle cases when the expression references a function designator
14111 /// or is an lvalue. Here are some examples:
14112 ///  - &(x) => x
14113 ///  - &*****f => f for f a function designator.
14114 ///  - &s.xx => s
14115 ///  - &s.zz[1].yy -> s, if zz is an array
14116 ///  - *(x + 1) -> x, if x is an array
14117 ///  - &"123"[2] -> 0
14118 ///  - & __real__ x -> x
14119 ///
14120 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14121 /// members.
14122 static ValueDecl *getPrimaryDecl(Expr *E) {
14123   switch (E->getStmtClass()) {
14124   case Stmt::DeclRefExprClass:
14125     return cast<DeclRefExpr>(E)->getDecl();
14126   case Stmt::MemberExprClass:
14127     // If this is an arrow operator, the address is an offset from
14128     // the base's value, so the object the base refers to is
14129     // irrelevant.
14130     if (cast<MemberExpr>(E)->isArrow())
14131       return nullptr;
14132     // Otherwise, the expression refers to a part of the base
14133     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14134   case Stmt::ArraySubscriptExprClass: {
14135     // FIXME: This code shouldn't be necessary!  We should catch the implicit
14136     // promotion of register arrays earlier.
14137     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14138     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14139       if (ICE->getSubExpr()->getType()->isArrayType())
14140         return getPrimaryDecl(ICE->getSubExpr());
14141     }
14142     return nullptr;
14143   }
14144   case Stmt::UnaryOperatorClass: {
14145     UnaryOperator *UO = cast<UnaryOperator>(E);
14146 
14147     switch(UO->getOpcode()) {
14148     case UO_Real:
14149     case UO_Imag:
14150     case UO_Extension:
14151       return getPrimaryDecl(UO->getSubExpr());
14152     default:
14153       return nullptr;
14154     }
14155   }
14156   case Stmt::ParenExprClass:
14157     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14158   case Stmt::ImplicitCastExprClass:
14159     // If the result of an implicit cast is an l-value, we care about
14160     // the sub-expression; otherwise, the result here doesn't matter.
14161     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14162   case Stmt::CXXUuidofExprClass:
14163     return cast<CXXUuidofExpr>(E)->getGuidDecl();
14164   default:
14165     return nullptr;
14166   }
14167 }
14168 
14169 namespace {
14170 enum {
14171   AO_Bit_Field = 0,
14172   AO_Vector_Element = 1,
14173   AO_Property_Expansion = 2,
14174   AO_Register_Variable = 3,
14175   AO_Matrix_Element = 4,
14176   AO_No_Error = 5
14177 };
14178 }
14179 /// Diagnose invalid operand for address of operations.
14180 ///
14181 /// \param Type The type of operand which cannot have its address taken.
14182 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14183                                          Expr *E, unsigned Type) {
14184   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14185 }
14186 
14187 /// CheckAddressOfOperand - The operand of & must be either a function
14188 /// designator or an lvalue designating an object. If it is an lvalue, the
14189 /// object cannot be declared with storage class register or be a bit field.
14190 /// Note: The usual conversions are *not* applied to the operand of the &
14191 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14192 /// In C++, the operand might be an overloaded function name, in which case
14193 /// we allow the '&' but retain the overloaded-function type.
14194 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14195   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14196     if (PTy->getKind() == BuiltinType::Overload) {
14197       Expr *E = OrigOp.get()->IgnoreParens();
14198       if (!isa<OverloadExpr>(E)) {
14199         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14200         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14201           << OrigOp.get()->getSourceRange();
14202         return QualType();
14203       }
14204 
14205       OverloadExpr *Ovl = cast<OverloadExpr>(E);
14206       if (isa<UnresolvedMemberExpr>(Ovl))
14207         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
14208           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14209             << OrigOp.get()->getSourceRange();
14210           return QualType();
14211         }
14212 
14213       return Context.OverloadTy;
14214     }
14215 
14216     if (PTy->getKind() == BuiltinType::UnknownAny)
14217       return Context.UnknownAnyTy;
14218 
14219     if (PTy->getKind() == BuiltinType::BoundMember) {
14220       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14221         << OrigOp.get()->getSourceRange();
14222       return QualType();
14223     }
14224 
14225     OrigOp = CheckPlaceholderExpr(OrigOp.get());
14226     if (OrigOp.isInvalid()) return QualType();
14227   }
14228 
14229   if (OrigOp.get()->isTypeDependent())
14230     return Context.DependentTy;
14231 
14232   assert(!OrigOp.get()->hasPlaceholderType());
14233 
14234   // Make sure to ignore parentheses in subsequent checks
14235   Expr *op = OrigOp.get()->IgnoreParens();
14236 
14237   // In OpenCL captures for blocks called as lambda functions
14238   // are located in the private address space. Blocks used in
14239   // enqueue_kernel can be located in a different address space
14240   // depending on a vendor implementation. Thus preventing
14241   // taking an address of the capture to avoid invalid AS casts.
14242   if (LangOpts.OpenCL) {
14243     auto* VarRef = dyn_cast<DeclRefExpr>(op);
14244     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14245       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14246       return QualType();
14247     }
14248   }
14249 
14250   if (getLangOpts().C99) {
14251     // Implement C99-only parts of addressof rules.
14252     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14253       if (uOp->getOpcode() == UO_Deref)
14254         // Per C99 6.5.3.2, the address of a deref always returns a valid result
14255         // (assuming the deref expression is valid).
14256         return uOp->getSubExpr()->getType();
14257     }
14258     // Technically, there should be a check for array subscript
14259     // expressions here, but the result of one is always an lvalue anyway.
14260   }
14261   ValueDecl *dcl = getPrimaryDecl(op);
14262 
14263   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14264     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14265                                            op->getBeginLoc()))
14266       return QualType();
14267 
14268   Expr::LValueClassification lval = op->ClassifyLValue(Context);
14269   unsigned AddressOfError = AO_No_Error;
14270 
14271   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14272     bool sfinae = (bool)isSFINAEContext();
14273     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14274                                   : diag::ext_typecheck_addrof_temporary)
14275       << op->getType() << op->getSourceRange();
14276     if (sfinae)
14277       return QualType();
14278     // Materialize the temporary as an lvalue so that we can take its address.
14279     OrigOp = op =
14280         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14281   } else if (isa<ObjCSelectorExpr>(op)) {
14282     return Context.getPointerType(op->getType());
14283   } else if (lval == Expr::LV_MemberFunction) {
14284     // If it's an instance method, make a member pointer.
14285     // The expression must have exactly the form &A::foo.
14286 
14287     // If the underlying expression isn't a decl ref, give up.
14288     if (!isa<DeclRefExpr>(op)) {
14289       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14290         << OrigOp.get()->getSourceRange();
14291       return QualType();
14292     }
14293     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14294     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14295 
14296     // The id-expression was parenthesized.
14297     if (OrigOp.get() != DRE) {
14298       Diag(OpLoc, diag::err_parens_pointer_member_function)
14299         << OrigOp.get()->getSourceRange();
14300 
14301     // The method was named without a qualifier.
14302     } else if (!DRE->getQualifier()) {
14303       if (MD->getParent()->getName().empty())
14304         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14305           << op->getSourceRange();
14306       else {
14307         SmallString<32> Str;
14308         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14309         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14310           << op->getSourceRange()
14311           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
14312       }
14313     }
14314 
14315     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14316     if (isa<CXXDestructorDecl>(MD))
14317       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
14318 
14319     QualType MPTy = Context.getMemberPointerType(
14320         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
14321     // Under the MS ABI, lock down the inheritance model now.
14322     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14323       (void)isCompleteType(OpLoc, MPTy);
14324     return MPTy;
14325   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14326     // C99 6.5.3.2p1
14327     // The operand must be either an l-value or a function designator
14328     if (!op->getType()->isFunctionType()) {
14329       // Use a special diagnostic for loads from property references.
14330       if (isa<PseudoObjectExpr>(op)) {
14331         AddressOfError = AO_Property_Expansion;
14332       } else {
14333         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14334           << op->getType() << op->getSourceRange();
14335         return QualType();
14336       }
14337     }
14338   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14339     // The operand cannot be a bit-field
14340     AddressOfError = AO_Bit_Field;
14341   } else if (op->getObjectKind() == OK_VectorComponent) {
14342     // The operand cannot be an element of a vector
14343     AddressOfError = AO_Vector_Element;
14344   } else if (op->getObjectKind() == OK_MatrixComponent) {
14345     // The operand cannot be an element of a matrix.
14346     AddressOfError = AO_Matrix_Element;
14347   } else if (dcl) { // C99 6.5.3.2p1
14348     // We have an lvalue with a decl. Make sure the decl is not declared
14349     // with the register storage-class specifier.
14350     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14351       // in C++ it is not error to take address of a register
14352       // variable (c++03 7.1.1P3)
14353       if (vd->getStorageClass() == SC_Register &&
14354           !getLangOpts().CPlusPlus) {
14355         AddressOfError = AO_Register_Variable;
14356       }
14357     } else if (isa<MSPropertyDecl>(dcl)) {
14358       AddressOfError = AO_Property_Expansion;
14359     } else if (isa<FunctionTemplateDecl>(dcl)) {
14360       return Context.OverloadTy;
14361     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14362       // Okay: we can take the address of a field.
14363       // Could be a pointer to member, though, if there is an explicit
14364       // scope qualifier for the class.
14365       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14366         DeclContext *Ctx = dcl->getDeclContext();
14367         if (Ctx && Ctx->isRecord()) {
14368           if (dcl->getType()->isReferenceType()) {
14369             Diag(OpLoc,
14370                  diag::err_cannot_form_pointer_to_member_of_reference_type)
14371               << dcl->getDeclName() << dcl->getType();
14372             return QualType();
14373           }
14374 
14375           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14376             Ctx = Ctx->getParent();
14377 
14378           QualType MPTy = Context.getMemberPointerType(
14379               op->getType(),
14380               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14381           // Under the MS ABI, lock down the inheritance model now.
14382           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14383             (void)isCompleteType(OpLoc, MPTy);
14384           return MPTy;
14385         }
14386       }
14387     } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
14388                     MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))
14389       llvm_unreachable("Unknown/unexpected decl type");
14390   }
14391 
14392   if (AddressOfError != AO_No_Error) {
14393     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14394     return QualType();
14395   }
14396 
14397   if (lval == Expr::LV_IncompleteVoidType) {
14398     // Taking the address of a void variable is technically illegal, but we
14399     // allow it in cases which are otherwise valid.
14400     // Example: "extern void x; void* y = &x;".
14401     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14402   }
14403 
14404   // If the operand has type "type", the result has type "pointer to type".
14405   if (op->getType()->isObjCObjectType())
14406     return Context.getObjCObjectPointerType(op->getType());
14407 
14408   CheckAddressOfPackedMember(op);
14409 
14410   return Context.getPointerType(op->getType());
14411 }
14412 
14413 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14414   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14415   if (!DRE)
14416     return;
14417   const Decl *D = DRE->getDecl();
14418   if (!D)
14419     return;
14420   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14421   if (!Param)
14422     return;
14423   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14424     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14425       return;
14426   if (FunctionScopeInfo *FD = S.getCurFunction())
14427     if (!FD->ModifiedNonNullParams.count(Param))
14428       FD->ModifiedNonNullParams.insert(Param);
14429 }
14430 
14431 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14432 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14433                                         SourceLocation OpLoc) {
14434   if (Op->isTypeDependent())
14435     return S.Context.DependentTy;
14436 
14437   ExprResult ConvResult = S.UsualUnaryConversions(Op);
14438   if (ConvResult.isInvalid())
14439     return QualType();
14440   Op = ConvResult.get();
14441   QualType OpTy = Op->getType();
14442   QualType Result;
14443 
14444   if (isa<CXXReinterpretCastExpr>(Op)) {
14445     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14446     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14447                                      Op->getSourceRange());
14448   }
14449 
14450   if (const PointerType *PT = OpTy->getAs<PointerType>())
14451   {
14452     Result = PT->getPointeeType();
14453   }
14454   else if (const ObjCObjectPointerType *OPT =
14455              OpTy->getAs<ObjCObjectPointerType>())
14456     Result = OPT->getPointeeType();
14457   else {
14458     ExprResult PR = S.CheckPlaceholderExpr(Op);
14459     if (PR.isInvalid()) return QualType();
14460     if (PR.get() != Op)
14461       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14462   }
14463 
14464   if (Result.isNull()) {
14465     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14466       << OpTy << Op->getSourceRange();
14467     return QualType();
14468   }
14469 
14470   // Note that per both C89 and C99, indirection is always legal, even if Result
14471   // is an incomplete type or void.  It would be possible to warn about
14472   // dereferencing a void pointer, but it's completely well-defined, and such a
14473   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
14474   // for pointers to 'void' but is fine for any other pointer type:
14475   //
14476   // C++ [expr.unary.op]p1:
14477   //   [...] the expression to which [the unary * operator] is applied shall
14478   //   be a pointer to an object type, or a pointer to a function type
14479   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
14480     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14481       << OpTy << Op->getSourceRange();
14482 
14483   // Dereferences are usually l-values...
14484   VK = VK_LValue;
14485 
14486   // ...except that certain expressions are never l-values in C.
14487   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14488     VK = VK_PRValue;
14489 
14490   return Result;
14491 }
14492 
14493 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14494   BinaryOperatorKind Opc;
14495   switch (Kind) {
14496   default: llvm_unreachable("Unknown binop!");
14497   case tok::periodstar:           Opc = BO_PtrMemD; break;
14498   case tok::arrowstar:            Opc = BO_PtrMemI; break;
14499   case tok::star:                 Opc = BO_Mul; break;
14500   case tok::slash:                Opc = BO_Div; break;
14501   case tok::percent:              Opc = BO_Rem; break;
14502   case tok::plus:                 Opc = BO_Add; break;
14503   case tok::minus:                Opc = BO_Sub; break;
14504   case tok::lessless:             Opc = BO_Shl; break;
14505   case tok::greatergreater:       Opc = BO_Shr; break;
14506   case tok::lessequal:            Opc = BO_LE; break;
14507   case tok::less:                 Opc = BO_LT; break;
14508   case tok::greaterequal:         Opc = BO_GE; break;
14509   case tok::greater:              Opc = BO_GT; break;
14510   case tok::exclaimequal:         Opc = BO_NE; break;
14511   case tok::equalequal:           Opc = BO_EQ; break;
14512   case tok::spaceship:            Opc = BO_Cmp; break;
14513   case tok::amp:                  Opc = BO_And; break;
14514   case tok::caret:                Opc = BO_Xor; break;
14515   case tok::pipe:                 Opc = BO_Or; break;
14516   case tok::ampamp:               Opc = BO_LAnd; break;
14517   case tok::pipepipe:             Opc = BO_LOr; break;
14518   case tok::equal:                Opc = BO_Assign; break;
14519   case tok::starequal:            Opc = BO_MulAssign; break;
14520   case tok::slashequal:           Opc = BO_DivAssign; break;
14521   case tok::percentequal:         Opc = BO_RemAssign; break;
14522   case tok::plusequal:            Opc = BO_AddAssign; break;
14523   case tok::minusequal:           Opc = BO_SubAssign; break;
14524   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
14525   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
14526   case tok::ampequal:             Opc = BO_AndAssign; break;
14527   case tok::caretequal:           Opc = BO_XorAssign; break;
14528   case tok::pipeequal:            Opc = BO_OrAssign; break;
14529   case tok::comma:                Opc = BO_Comma; break;
14530   }
14531   return Opc;
14532 }
14533 
14534 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
14535   tok::TokenKind Kind) {
14536   UnaryOperatorKind Opc;
14537   switch (Kind) {
14538   default: llvm_unreachable("Unknown unary op!");
14539   case tok::plusplus:     Opc = UO_PreInc; break;
14540   case tok::minusminus:   Opc = UO_PreDec; break;
14541   case tok::amp:          Opc = UO_AddrOf; break;
14542   case tok::star:         Opc = UO_Deref; break;
14543   case tok::plus:         Opc = UO_Plus; break;
14544   case tok::minus:        Opc = UO_Minus; break;
14545   case tok::tilde:        Opc = UO_Not; break;
14546   case tok::exclaim:      Opc = UO_LNot; break;
14547   case tok::kw___real:    Opc = UO_Real; break;
14548   case tok::kw___imag:    Opc = UO_Imag; break;
14549   case tok::kw___extension__: Opc = UO_Extension; break;
14550   }
14551   return Opc;
14552 }
14553 
14554 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14555 /// This warning suppressed in the event of macro expansions.
14556 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14557                                    SourceLocation OpLoc, bool IsBuiltin) {
14558   if (S.inTemplateInstantiation())
14559     return;
14560   if (S.isUnevaluatedContext())
14561     return;
14562   if (OpLoc.isInvalid() || OpLoc.isMacroID())
14563     return;
14564   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14565   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14566   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14567   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14568   if (!LHSDeclRef || !RHSDeclRef ||
14569       LHSDeclRef->getLocation().isMacroID() ||
14570       RHSDeclRef->getLocation().isMacroID())
14571     return;
14572   const ValueDecl *LHSDecl =
14573     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14574   const ValueDecl *RHSDecl =
14575     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14576   if (LHSDecl != RHSDecl)
14577     return;
14578   if (LHSDecl->getType().isVolatileQualified())
14579     return;
14580   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14581     if (RefTy->getPointeeType().isVolatileQualified())
14582       return;
14583 
14584   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14585                           : diag::warn_self_assignment_overloaded)
14586       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14587       << RHSExpr->getSourceRange();
14588 }
14589 
14590 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
14591 /// is usually indicative of introspection within the Objective-C pointer.
14592 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
14593                                           SourceLocation OpLoc) {
14594   if (!S.getLangOpts().ObjC)
14595     return;
14596 
14597   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14598   const Expr *LHS = L.get();
14599   const Expr *RHS = R.get();
14600 
14601   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14602     ObjCPointerExpr = LHS;
14603     OtherExpr = RHS;
14604   }
14605   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14606     ObjCPointerExpr = RHS;
14607     OtherExpr = LHS;
14608   }
14609 
14610   // This warning is deliberately made very specific to reduce false
14611   // positives with logic that uses '&' for hashing.  This logic mainly
14612   // looks for code trying to introspect into tagged pointers, which
14613   // code should generally never do.
14614   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14615     unsigned Diag = diag::warn_objc_pointer_masking;
14616     // Determine if we are introspecting the result of performSelectorXXX.
14617     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14618     // Special case messages to -performSelector and friends, which
14619     // can return non-pointer values boxed in a pointer value.
14620     // Some clients may wish to silence warnings in this subcase.
14621     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14622       Selector S = ME->getSelector();
14623       StringRef SelArg0 = S.getNameForSlot(0);
14624       if (SelArg0.startswith("performSelector"))
14625         Diag = diag::warn_objc_pointer_masking_performSelector;
14626     }
14627 
14628     S.Diag(OpLoc, Diag)
14629       << ObjCPointerExpr->getSourceRange();
14630   }
14631 }
14632 
14633 static NamedDecl *getDeclFromExpr(Expr *E) {
14634   if (!E)
14635     return nullptr;
14636   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14637     return DRE->getDecl();
14638   if (auto *ME = dyn_cast<MemberExpr>(E))
14639     return ME->getMemberDecl();
14640   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14641     return IRE->getDecl();
14642   return nullptr;
14643 }
14644 
14645 // This helper function promotes a binary operator's operands (which are of a
14646 // half vector type) to a vector of floats and then truncates the result to
14647 // a vector of either half or short.
14648 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
14649                                       BinaryOperatorKind Opc, QualType ResultTy,
14650                                       ExprValueKind VK, ExprObjectKind OK,
14651                                       bool IsCompAssign, SourceLocation OpLoc,
14652                                       FPOptionsOverride FPFeatures) {
14653   auto &Context = S.getASTContext();
14654   assert((isVector(ResultTy, Context.HalfTy) ||
14655           isVector(ResultTy, Context.ShortTy)) &&
14656          "Result must be a vector of half or short");
14657   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14658          isVector(RHS.get()->getType(), Context.HalfTy) &&
14659          "both operands expected to be a half vector");
14660 
14661   RHS = convertVector(RHS.get(), Context.FloatTy, S);
14662   QualType BinOpResTy = RHS.get()->getType();
14663 
14664   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14665   // change BinOpResTy to a vector of ints.
14666   if (isVector(ResultTy, Context.ShortTy))
14667     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14668 
14669   if (IsCompAssign)
14670     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14671                                           ResultTy, VK, OK, OpLoc, FPFeatures,
14672                                           BinOpResTy, BinOpResTy);
14673 
14674   LHS = convertVector(LHS.get(), Context.FloatTy, S);
14675   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14676                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
14677   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14678 }
14679 
14680 static std::pair<ExprResult, ExprResult>
14681 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14682                            Expr *RHSExpr) {
14683   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14684   if (!S.Context.isDependenceAllowed()) {
14685     // C cannot handle TypoExpr nodes on either side of a binop because it
14686     // doesn't handle dependent types properly, so make sure any TypoExprs have
14687     // been dealt with before checking the operands.
14688     LHS = S.CorrectDelayedTyposInExpr(LHS);
14689     RHS = S.CorrectDelayedTyposInExpr(
14690         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14691         [Opc, LHS](Expr *E) {
14692           if (Opc != BO_Assign)
14693             return ExprResult(E);
14694           // Avoid correcting the RHS to the same Expr as the LHS.
14695           Decl *D = getDeclFromExpr(E);
14696           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14697         });
14698   }
14699   return std::make_pair(LHS, RHS);
14700 }
14701 
14702 /// Returns true if conversion between vectors of halfs and vectors of floats
14703 /// is needed.
14704 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14705                                      Expr *E0, Expr *E1 = nullptr) {
14706   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14707       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14708     return false;
14709 
14710   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14711     QualType Ty = E->IgnoreImplicit()->getType();
14712 
14713     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14714     // to vectors of floats. Although the element type of the vectors is __fp16,
14715     // the vectors shouldn't be treated as storage-only types. See the
14716     // discussion here: https://reviews.llvm.org/rG825235c140e7
14717     if (const VectorType *VT = Ty->getAs<VectorType>()) {
14718       if (VT->getVectorKind() == VectorType::NeonVector)
14719         return false;
14720       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14721     }
14722     return false;
14723   };
14724 
14725   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14726 }
14727 
14728 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
14729 /// operator @p Opc at location @c TokLoc. This routine only supports
14730 /// built-in operations; ActOnBinOp handles overloaded operators.
14731 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14732                                     BinaryOperatorKind Opc,
14733                                     Expr *LHSExpr, Expr *RHSExpr) {
14734   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14735     // The syntax only allows initializer lists on the RHS of assignment,
14736     // so we don't need to worry about accepting invalid code for
14737     // non-assignment operators.
14738     // C++11 5.17p9:
14739     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14740     //   of x = {} is x = T().
14741     InitializationKind Kind = InitializationKind::CreateDirectList(
14742         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14743     InitializedEntity Entity =
14744         InitializedEntity::InitializeTemporary(LHSExpr->getType());
14745     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14746     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14747     if (Init.isInvalid())
14748       return Init;
14749     RHSExpr = Init.get();
14750   }
14751 
14752   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14753   QualType ResultTy;     // Result type of the binary operator.
14754   // The following two variables are used for compound assignment operators
14755   QualType CompLHSTy;    // Type of LHS after promotions for computation
14756   QualType CompResultTy; // Type of computation result
14757   ExprValueKind VK = VK_PRValue;
14758   ExprObjectKind OK = OK_Ordinary;
14759   bool ConvertHalfVec = false;
14760 
14761   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14762   if (!LHS.isUsable() || !RHS.isUsable())
14763     return ExprError();
14764 
14765   if (getLangOpts().OpenCL) {
14766     QualType LHSTy = LHSExpr->getType();
14767     QualType RHSTy = RHSExpr->getType();
14768     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14769     // the ATOMIC_VAR_INIT macro.
14770     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14771       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14772       if (BO_Assign == Opc)
14773         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14774       else
14775         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14776       return ExprError();
14777     }
14778 
14779     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14780     // only with a builtin functions and therefore should be disallowed here.
14781     if (LHSTy->isImageType() || RHSTy->isImageType() ||
14782         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14783         LHSTy->isPipeType() || RHSTy->isPipeType() ||
14784         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14785       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14786       return ExprError();
14787     }
14788   }
14789 
14790   checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14791   checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14792 
14793   switch (Opc) {
14794   case BO_Assign:
14795     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14796     if (getLangOpts().CPlusPlus &&
14797         LHS.get()->getObjectKind() != OK_ObjCProperty) {
14798       VK = LHS.get()->getValueKind();
14799       OK = LHS.get()->getObjectKind();
14800     }
14801     if (!ResultTy.isNull()) {
14802       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14803       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14804 
14805       // Avoid copying a block to the heap if the block is assigned to a local
14806       // auto variable that is declared in the same scope as the block. This
14807       // optimization is unsafe if the local variable is declared in an outer
14808       // scope. For example:
14809       //
14810       // BlockTy b;
14811       // {
14812       //   b = ^{...};
14813       // }
14814       // // It is unsafe to invoke the block here if it wasn't copied to the
14815       // // heap.
14816       // b();
14817 
14818       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14819         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14820           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14821             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14822               BE->getBlockDecl()->setCanAvoidCopyToHeap();
14823 
14824       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14825         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14826                               NTCUC_Assignment, NTCUK_Copy);
14827     }
14828     RecordModifiableNonNullParam(*this, LHS.get());
14829     break;
14830   case BO_PtrMemD:
14831   case BO_PtrMemI:
14832     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14833                                             Opc == BO_PtrMemI);
14834     break;
14835   case BO_Mul:
14836   case BO_Div:
14837     ConvertHalfVec = true;
14838     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14839                                            Opc == BO_Div);
14840     break;
14841   case BO_Rem:
14842     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14843     break;
14844   case BO_Add:
14845     ConvertHalfVec = true;
14846     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14847     break;
14848   case BO_Sub:
14849     ConvertHalfVec = true;
14850     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14851     break;
14852   case BO_Shl:
14853   case BO_Shr:
14854     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14855     break;
14856   case BO_LE:
14857   case BO_LT:
14858   case BO_GE:
14859   case BO_GT:
14860     ConvertHalfVec = true;
14861     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14862     break;
14863   case BO_EQ:
14864   case BO_NE:
14865     ConvertHalfVec = true;
14866     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14867     break;
14868   case BO_Cmp:
14869     ConvertHalfVec = true;
14870     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14871     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14872     break;
14873   case BO_And:
14874     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14875     LLVM_FALLTHROUGH;
14876   case BO_Xor:
14877   case BO_Or:
14878     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14879     break;
14880   case BO_LAnd:
14881   case BO_LOr:
14882     ConvertHalfVec = true;
14883     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14884     break;
14885   case BO_MulAssign:
14886   case BO_DivAssign:
14887     ConvertHalfVec = true;
14888     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14889                                                Opc == BO_DivAssign);
14890     CompLHSTy = CompResultTy;
14891     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14892       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14893     break;
14894   case BO_RemAssign:
14895     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14896     CompLHSTy = CompResultTy;
14897     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14898       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14899     break;
14900   case BO_AddAssign:
14901     ConvertHalfVec = true;
14902     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14903     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14904       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14905     break;
14906   case BO_SubAssign:
14907     ConvertHalfVec = true;
14908     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14909     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14910       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14911     break;
14912   case BO_ShlAssign:
14913   case BO_ShrAssign:
14914     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14915     CompLHSTy = CompResultTy;
14916     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14917       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14918     break;
14919   case BO_AndAssign:
14920   case BO_OrAssign: // fallthrough
14921     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14922     LLVM_FALLTHROUGH;
14923   case BO_XorAssign:
14924     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14925     CompLHSTy = CompResultTy;
14926     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14927       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14928     break;
14929   case BO_Comma:
14930     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14931     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14932       VK = RHS.get()->getValueKind();
14933       OK = RHS.get()->getObjectKind();
14934     }
14935     break;
14936   }
14937   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14938     return ExprError();
14939 
14940   // Some of the binary operations require promoting operands of half vector to
14941   // float vectors and truncating the result back to half vector. For now, we do
14942   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14943   // arm64).
14944   assert(
14945       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14946                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
14947       "both sides are half vectors or neither sides are");
14948   ConvertHalfVec =
14949       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14950 
14951   // Check for array bounds violations for both sides of the BinaryOperator
14952   CheckArrayAccess(LHS.get());
14953   CheckArrayAccess(RHS.get());
14954 
14955   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14956     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14957                                                  &Context.Idents.get("object_setClass"),
14958                                                  SourceLocation(), LookupOrdinaryName);
14959     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14960       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14961       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14962           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14963                                         "object_setClass(")
14964           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14965                                           ",")
14966           << FixItHint::CreateInsertion(RHSLocEnd, ")");
14967     }
14968     else
14969       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14970   }
14971   else if (const ObjCIvarRefExpr *OIRE =
14972            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14973     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14974 
14975   // Opc is not a compound assignment if CompResultTy is null.
14976   if (CompResultTy.isNull()) {
14977     if (ConvertHalfVec)
14978       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14979                                  OpLoc, CurFPFeatureOverrides());
14980     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14981                                   VK, OK, OpLoc, CurFPFeatureOverrides());
14982   }
14983 
14984   // Handle compound assignments.
14985   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14986       OK_ObjCProperty) {
14987     VK = VK_LValue;
14988     OK = LHS.get()->getObjectKind();
14989   }
14990 
14991   // The LHS is not converted to the result type for fixed-point compound
14992   // assignment as the common type is computed on demand. Reset the CompLHSTy
14993   // to the LHS type we would have gotten after unary conversions.
14994   if (CompResultTy->isFixedPointType())
14995     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14996 
14997   if (ConvertHalfVec)
14998     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14999                                OpLoc, CurFPFeatureOverrides());
15000 
15001   return CompoundAssignOperator::Create(
15002       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15003       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15004 }
15005 
15006 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15007 /// operators are mixed in a way that suggests that the programmer forgot that
15008 /// comparison operators have higher precedence. The most typical example of
15009 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15010 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15011                                       SourceLocation OpLoc, Expr *LHSExpr,
15012                                       Expr *RHSExpr) {
15013   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15014   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15015 
15016   // Check that one of the sides is a comparison operator and the other isn't.
15017   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15018   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15019   if (isLeftComp == isRightComp)
15020     return;
15021 
15022   // Bitwise operations are sometimes used as eager logical ops.
15023   // Don't diagnose this.
15024   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15025   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15026   if (isLeftBitwise || isRightBitwise)
15027     return;
15028 
15029   SourceRange DiagRange = isLeftComp
15030                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15031                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
15032   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15033   SourceRange ParensRange =
15034       isLeftComp
15035           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15036           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15037 
15038   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15039     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15040   SuggestParentheses(Self, OpLoc,
15041     Self.PDiag(diag::note_precedence_silence) << OpStr,
15042     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15043   SuggestParentheses(Self, OpLoc,
15044     Self.PDiag(diag::note_precedence_bitwise_first)
15045       << BinaryOperator::getOpcodeStr(Opc),
15046     ParensRange);
15047 }
15048 
15049 /// It accepts a '&&' expr that is inside a '||' one.
15050 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15051 /// in parentheses.
15052 static void
15053 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15054                                        BinaryOperator *Bop) {
15055   assert(Bop->getOpcode() == BO_LAnd);
15056   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15057       << Bop->getSourceRange() << OpLoc;
15058   SuggestParentheses(Self, Bop->getOperatorLoc(),
15059     Self.PDiag(diag::note_precedence_silence)
15060       << Bop->getOpcodeStr(),
15061     Bop->getSourceRange());
15062 }
15063 
15064 /// Returns true if the given expression can be evaluated as a constant
15065 /// 'true'.
15066 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
15067   bool Res;
15068   return !E->isValueDependent() &&
15069          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
15070 }
15071 
15072 /// Returns true if the given expression can be evaluated as a constant
15073 /// 'false'.
15074 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
15075   bool Res;
15076   return !E->isValueDependent() &&
15077          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
15078 }
15079 
15080 /// Look for '&&' in the left hand of a '||' expr.
15081 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15082                                              Expr *LHSExpr, Expr *RHSExpr) {
15083   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15084     if (Bop->getOpcode() == BO_LAnd) {
15085       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
15086       if (EvaluatesAsFalse(S, RHSExpr))
15087         return;
15088       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
15089       if (!EvaluatesAsTrue(S, Bop->getLHS()))
15090         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15091     } else if (Bop->getOpcode() == BO_LOr) {
15092       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15093         // If it's "a || b && 1 || c" we didn't warn earlier for
15094         // "a || b && 1", but warn now.
15095         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
15096           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15097       }
15098     }
15099   }
15100 }
15101 
15102 /// Look for '&&' in the right hand of a '||' expr.
15103 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15104                                              Expr *LHSExpr, Expr *RHSExpr) {
15105   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15106     if (Bop->getOpcode() == BO_LAnd) {
15107       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
15108       if (EvaluatesAsFalse(S, LHSExpr))
15109         return;
15110       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
15111       if (!EvaluatesAsTrue(S, Bop->getRHS()))
15112         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15113     }
15114   }
15115 }
15116 
15117 /// Look for bitwise op in the left or right hand of a bitwise op with
15118 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
15119 /// the '&' expression in parentheses.
15120 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15121                                          SourceLocation OpLoc, Expr *SubExpr) {
15122   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15123     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15124       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15125         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15126         << Bop->getSourceRange() << OpLoc;
15127       SuggestParentheses(S, Bop->getOperatorLoc(),
15128         S.PDiag(diag::note_precedence_silence)
15129           << Bop->getOpcodeStr(),
15130         Bop->getSourceRange());
15131     }
15132   }
15133 }
15134 
15135 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15136                                     Expr *SubExpr, StringRef Shift) {
15137   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15138     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15139       StringRef Op = Bop->getOpcodeStr();
15140       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15141           << Bop->getSourceRange() << OpLoc << Shift << Op;
15142       SuggestParentheses(S, Bop->getOperatorLoc(),
15143           S.PDiag(diag::note_precedence_silence) << Op,
15144           Bop->getSourceRange());
15145     }
15146   }
15147 }
15148 
15149 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15150                                  Expr *LHSExpr, Expr *RHSExpr) {
15151   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15152   if (!OCE)
15153     return;
15154 
15155   FunctionDecl *FD = OCE->getDirectCallee();
15156   if (!FD || !FD->isOverloadedOperator())
15157     return;
15158 
15159   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15160   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15161     return;
15162 
15163   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15164       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15165       << (Kind == OO_LessLess);
15166   SuggestParentheses(S, OCE->getOperatorLoc(),
15167                      S.PDiag(diag::note_precedence_silence)
15168                          << (Kind == OO_LessLess ? "<<" : ">>"),
15169                      OCE->getSourceRange());
15170   SuggestParentheses(
15171       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15172       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15173 }
15174 
15175 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15176 /// precedence.
15177 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15178                                     SourceLocation OpLoc, Expr *LHSExpr,
15179                                     Expr *RHSExpr){
15180   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15181   if (BinaryOperator::isBitwiseOp(Opc))
15182     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15183 
15184   // Diagnose "arg1 & arg2 | arg3"
15185   if ((Opc == BO_Or || Opc == BO_Xor) &&
15186       !OpLoc.isMacroID()/* Don't warn in macros. */) {
15187     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15188     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15189   }
15190 
15191   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15192   // We don't warn for 'assert(a || b && "bad")' since this is safe.
15193   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15194     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15195     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15196   }
15197 
15198   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15199       || Opc == BO_Shr) {
15200     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15201     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15202     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15203   }
15204 
15205   // Warn on overloaded shift operators and comparisons, such as:
15206   // cout << 5 == 4;
15207   if (BinaryOperator::isComparisonOp(Opc))
15208     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15209 }
15210 
15211 // Binary Operators.  'Tok' is the token for the operator.
15212 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15213                             tok::TokenKind Kind,
15214                             Expr *LHSExpr, Expr *RHSExpr) {
15215   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15216   assert(LHSExpr && "ActOnBinOp(): missing left expression");
15217   assert(RHSExpr && "ActOnBinOp(): missing right expression");
15218 
15219   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15220   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15221 
15222   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15223 }
15224 
15225 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15226                        UnresolvedSetImpl &Functions) {
15227   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15228   if (OverOp != OO_None && OverOp != OO_Equal)
15229     LookupOverloadedOperatorName(OverOp, S, Functions);
15230 
15231   // In C++20 onwards, we may have a second operator to look up.
15232   if (getLangOpts().CPlusPlus20) {
15233     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
15234       LookupOverloadedOperatorName(ExtraOp, S, Functions);
15235   }
15236 }
15237 
15238 /// Build an overloaded binary operator expression in the given scope.
15239 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15240                                        BinaryOperatorKind Opc,
15241                                        Expr *LHS, Expr *RHS) {
15242   switch (Opc) {
15243   case BO_Assign:
15244   case BO_DivAssign:
15245   case BO_RemAssign:
15246   case BO_SubAssign:
15247   case BO_AndAssign:
15248   case BO_OrAssign:
15249   case BO_XorAssign:
15250     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15251     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15252     break;
15253   default:
15254     break;
15255   }
15256 
15257   // Find all of the overloaded operators visible from this point.
15258   UnresolvedSet<16> Functions;
15259   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15260 
15261   // Build the (potentially-overloaded, potentially-dependent)
15262   // binary operation.
15263   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15264 }
15265 
15266 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15267                             BinaryOperatorKind Opc,
15268                             Expr *LHSExpr, Expr *RHSExpr) {
15269   ExprResult LHS, RHS;
15270   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15271   if (!LHS.isUsable() || !RHS.isUsable())
15272     return ExprError();
15273   LHSExpr = LHS.get();
15274   RHSExpr = RHS.get();
15275 
15276   // We want to end up calling one of checkPseudoObjectAssignment
15277   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15278   // both expressions are overloadable or either is type-dependent),
15279   // or CreateBuiltinBinOp (in any other case).  We also want to get
15280   // any placeholder types out of the way.
15281 
15282   // Handle pseudo-objects in the LHS.
15283   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15284     // Assignments with a pseudo-object l-value need special analysis.
15285     if (pty->getKind() == BuiltinType::PseudoObject &&
15286         BinaryOperator::isAssignmentOp(Opc))
15287       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15288 
15289     // Don't resolve overloads if the other type is overloadable.
15290     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15291       // We can't actually test that if we still have a placeholder,
15292       // though.  Fortunately, none of the exceptions we see in that
15293       // code below are valid when the LHS is an overload set.  Note
15294       // that an overload set can be dependently-typed, but it never
15295       // instantiates to having an overloadable type.
15296       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15297       if (resolvedRHS.isInvalid()) return ExprError();
15298       RHSExpr = resolvedRHS.get();
15299 
15300       if (RHSExpr->isTypeDependent() ||
15301           RHSExpr->getType()->isOverloadableType())
15302         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15303     }
15304 
15305     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15306     // template, diagnose the missing 'template' keyword instead of diagnosing
15307     // an invalid use of a bound member function.
15308     //
15309     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15310     // to C++1z [over.over]/1.4, but we already checked for that case above.
15311     if (Opc == BO_LT && inTemplateInstantiation() &&
15312         (pty->getKind() == BuiltinType::BoundMember ||
15313          pty->getKind() == BuiltinType::Overload)) {
15314       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15315       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15316           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
15317             return isa<FunctionTemplateDecl>(ND);
15318           })) {
15319         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15320                                 : OE->getNameLoc(),
15321              diag::err_template_kw_missing)
15322           << OE->getName().getAsString() << "";
15323         return ExprError();
15324       }
15325     }
15326 
15327     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15328     if (LHS.isInvalid()) return ExprError();
15329     LHSExpr = LHS.get();
15330   }
15331 
15332   // Handle pseudo-objects in the RHS.
15333   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15334     // An overload in the RHS can potentially be resolved by the type
15335     // being assigned to.
15336     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15337       if (getLangOpts().CPlusPlus &&
15338           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15339            LHSExpr->getType()->isOverloadableType()))
15340         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15341 
15342       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15343     }
15344 
15345     // Don't resolve overloads if the other type is overloadable.
15346     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15347         LHSExpr->getType()->isOverloadableType())
15348       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15349 
15350     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15351     if (!resolvedRHS.isUsable()) return ExprError();
15352     RHSExpr = resolvedRHS.get();
15353   }
15354 
15355   if (getLangOpts().CPlusPlus) {
15356     // If either expression is type-dependent, always build an
15357     // overloaded op.
15358     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
15359       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15360 
15361     // Otherwise, build an overloaded op if either expression has an
15362     // overloadable type.
15363     if (LHSExpr->getType()->isOverloadableType() ||
15364         RHSExpr->getType()->isOverloadableType())
15365       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15366   }
15367 
15368   if (getLangOpts().RecoveryAST &&
15369       (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15370     assert(!getLangOpts().CPlusPlus);
15371     assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15372            "Should only occur in error-recovery path.");
15373     if (BinaryOperator::isCompoundAssignmentOp(Opc))
15374       // C [6.15.16] p3:
15375       // An assignment expression has the value of the left operand after the
15376       // assignment, but is not an lvalue.
15377       return CompoundAssignOperator::Create(
15378           Context, LHSExpr, RHSExpr, Opc,
15379           LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
15380           OpLoc, CurFPFeatureOverrides());
15381     QualType ResultType;
15382     switch (Opc) {
15383     case BO_Assign:
15384       ResultType = LHSExpr->getType().getUnqualifiedType();
15385       break;
15386     case BO_LT:
15387     case BO_GT:
15388     case BO_LE:
15389     case BO_GE:
15390     case BO_EQ:
15391     case BO_NE:
15392     case BO_LAnd:
15393     case BO_LOr:
15394       // These operators have a fixed result type regardless of operands.
15395       ResultType = Context.IntTy;
15396       break;
15397     case BO_Comma:
15398       ResultType = RHSExpr->getType();
15399       break;
15400     default:
15401       ResultType = Context.DependentTy;
15402       break;
15403     }
15404     return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15405                                   VK_PRValue, OK_Ordinary, OpLoc,
15406                                   CurFPFeatureOverrides());
15407   }
15408 
15409   // Build a built-in binary operation.
15410   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15411 }
15412 
15413 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
15414   if (T.isNull() || T->isDependentType())
15415     return false;
15416 
15417   if (!T->isPromotableIntegerType())
15418     return true;
15419 
15420   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15421 }
15422 
15423 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
15424                                       UnaryOperatorKind Opc,
15425                                       Expr *InputExpr) {
15426   ExprResult Input = InputExpr;
15427   ExprValueKind VK = VK_PRValue;
15428   ExprObjectKind OK = OK_Ordinary;
15429   QualType resultType;
15430   bool CanOverflow = false;
15431 
15432   bool ConvertHalfVec = false;
15433   if (getLangOpts().OpenCL) {
15434     QualType Ty = InputExpr->getType();
15435     // The only legal unary operation for atomics is '&'.
15436     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15437     // OpenCL special types - image, sampler, pipe, and blocks are to be used
15438     // only with a builtin functions and therefore should be disallowed here.
15439         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15440         || Ty->isBlockPointerType())) {
15441       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15442                        << InputExpr->getType()
15443                        << Input.get()->getSourceRange());
15444     }
15445   }
15446 
15447   if (getLangOpts().HLSL) {
15448     if (Opc == UO_AddrOf)
15449       return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15450     if (Opc == UO_Deref)
15451       return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15452   }
15453 
15454   switch (Opc) {
15455   case UO_PreInc:
15456   case UO_PreDec:
15457   case UO_PostInc:
15458   case UO_PostDec:
15459     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
15460                                                 OpLoc,
15461                                                 Opc == UO_PreInc ||
15462                                                 Opc == UO_PostInc,
15463                                                 Opc == UO_PreInc ||
15464                                                 Opc == UO_PreDec);
15465     CanOverflow = isOverflowingIntegerType(Context, resultType);
15466     break;
15467   case UO_AddrOf:
15468     resultType = CheckAddressOfOperand(Input, OpLoc);
15469     CheckAddressOfNoDeref(InputExpr);
15470     RecordModifiableNonNullParam(*this, InputExpr);
15471     break;
15472   case UO_Deref: {
15473     Input = DefaultFunctionArrayLvalueConversion(Input.get());
15474     if (Input.isInvalid()) return ExprError();
15475     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
15476     break;
15477   }
15478   case UO_Plus:
15479   case UO_Minus:
15480     CanOverflow = Opc == UO_Minus &&
15481                   isOverflowingIntegerType(Context, Input.get()->getType());
15482     Input = UsualUnaryConversions(Input.get());
15483     if (Input.isInvalid()) return ExprError();
15484     // Unary plus and minus require promoting an operand of half vector to a
15485     // float vector and truncating the result back to a half vector. For now, we
15486     // do this only when HalfArgsAndReturns is set (that is, when the target is
15487     // arm or arm64).
15488     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15489 
15490     // If the operand is a half vector, promote it to a float vector.
15491     if (ConvertHalfVec)
15492       Input = convertVector(Input.get(), Context.FloatTy, *this);
15493     resultType = Input.get()->getType();
15494     if (resultType->isDependentType())
15495       break;
15496     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15497       break;
15498     else if (resultType->isVectorType() &&
15499              // The z vector extensions don't allow + or - with bool vectors.
15500              (!Context.getLangOpts().ZVector ||
15501               resultType->castAs<VectorType>()->getVectorKind() !=
15502               VectorType::AltiVecBool))
15503       break;
15504     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15505              Opc == UO_Plus &&
15506              resultType->isPointerType())
15507       break;
15508 
15509     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15510       << resultType << Input.get()->getSourceRange());
15511 
15512   case UO_Not: // bitwise complement
15513     Input = UsualUnaryConversions(Input.get());
15514     if (Input.isInvalid())
15515       return ExprError();
15516     resultType = Input.get()->getType();
15517     if (resultType->isDependentType())
15518       break;
15519     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15520     if (resultType->isComplexType() || resultType->isComplexIntegerType())
15521       // C99 does not support '~' for complex conjugation.
15522       Diag(OpLoc, diag::ext_integer_complement_complex)
15523           << resultType << Input.get()->getSourceRange();
15524     else if (resultType->hasIntegerRepresentation())
15525       break;
15526     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15527       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15528       // on vector float types.
15529       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15530       if (!T->isIntegerType())
15531         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15532                           << resultType << Input.get()->getSourceRange());
15533     } else {
15534       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15535                        << resultType << Input.get()->getSourceRange());
15536     }
15537     break;
15538 
15539   case UO_LNot: // logical negation
15540     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15541     Input = DefaultFunctionArrayLvalueConversion(Input.get());
15542     if (Input.isInvalid()) return ExprError();
15543     resultType = Input.get()->getType();
15544 
15545     // Though we still have to promote half FP to float...
15546     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15547       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
15548       resultType = Context.FloatTy;
15549     }
15550 
15551     if (resultType->isDependentType())
15552       break;
15553     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15554       // C99 6.5.3.3p1: ok, fallthrough;
15555       if (Context.getLangOpts().CPlusPlus) {
15556         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15557         // operand contextually converted to bool.
15558         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15559                                   ScalarTypeToBooleanCastKind(resultType));
15560       } else if (Context.getLangOpts().OpenCL &&
15561                  Context.getLangOpts().OpenCLVersion < 120) {
15562         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15563         // operate on scalar float types.
15564         if (!resultType->isIntegerType() && !resultType->isPointerType())
15565           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15566                            << resultType << Input.get()->getSourceRange());
15567       }
15568     } else if (resultType->isExtVectorType()) {
15569       if (Context.getLangOpts().OpenCL &&
15570           Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15571         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15572         // operate on vector float types.
15573         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15574         if (!T->isIntegerType())
15575           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15576                            << resultType << Input.get()->getSourceRange());
15577       }
15578       // Vector logical not returns the signed variant of the operand type.
15579       resultType = GetSignedVectorType(resultType);
15580       break;
15581     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
15582       const VectorType *VTy = resultType->castAs<VectorType>();
15583       if (VTy->getVectorKind() != VectorType::GenericVector)
15584         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15585                          << resultType << Input.get()->getSourceRange());
15586 
15587       // Vector logical not returns the signed variant of the operand type.
15588       resultType = GetSignedVectorType(resultType);
15589       break;
15590     } else {
15591       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15592         << resultType << Input.get()->getSourceRange());
15593     }
15594 
15595     // LNot always has type int. C99 6.5.3.3p5.
15596     // In C++, it's bool. C++ 5.3.1p8
15597     resultType = Context.getLogicalOperationType();
15598     break;
15599   case UO_Real:
15600   case UO_Imag:
15601     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15602     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
15603     // complex l-values to ordinary l-values and all other values to r-values.
15604     if (Input.isInvalid()) return ExprError();
15605     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15606       if (Input.get()->isGLValue() &&
15607           Input.get()->getObjectKind() == OK_Ordinary)
15608         VK = Input.get()->getValueKind();
15609     } else if (!getLangOpts().CPlusPlus) {
15610       // In C, a volatile scalar is read by __imag. In C++, it is not.
15611       Input = DefaultLvalueConversion(Input.get());
15612     }
15613     break;
15614   case UO_Extension:
15615     resultType = Input.get()->getType();
15616     VK = Input.get()->getValueKind();
15617     OK = Input.get()->getObjectKind();
15618     break;
15619   case UO_Coawait:
15620     // It's unnecessary to represent the pass-through operator co_await in the
15621     // AST; just return the input expression instead.
15622     assert(!Input.get()->getType()->isDependentType() &&
15623                    "the co_await expression must be non-dependant before "
15624                    "building operator co_await");
15625     return Input;
15626   }
15627   if (resultType.isNull() || Input.isInvalid())
15628     return ExprError();
15629 
15630   // Check for array bounds violations in the operand of the UnaryOperator,
15631   // except for the '*' and '&' operators that have to be handled specially
15632   // by CheckArrayAccess (as there are special cases like &array[arraysize]
15633   // that are explicitly defined as valid by the standard).
15634   if (Opc != UO_AddrOf && Opc != UO_Deref)
15635     CheckArrayAccess(Input.get());
15636 
15637   auto *UO =
15638       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15639                             OpLoc, CanOverflow, CurFPFeatureOverrides());
15640 
15641   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15642       !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15643       !isUnevaluatedContext())
15644     ExprEvalContexts.back().PossibleDerefs.insert(UO);
15645 
15646   // Convert the result back to a half vector.
15647   if (ConvertHalfVec)
15648     return convertVector(UO, Context.HalfTy, *this);
15649   return UO;
15650 }
15651 
15652 /// Determine whether the given expression is a qualified member
15653 /// access expression, of a form that could be turned into a pointer to member
15654 /// with the address-of operator.
15655 bool Sema::isQualifiedMemberAccess(Expr *E) {
15656   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15657     if (!DRE->getQualifier())
15658       return false;
15659 
15660     ValueDecl *VD = DRE->getDecl();
15661     if (!VD->isCXXClassMember())
15662       return false;
15663 
15664     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15665       return true;
15666     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15667       return Method->isInstance();
15668 
15669     return false;
15670   }
15671 
15672   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15673     if (!ULE->getQualifier())
15674       return false;
15675 
15676     for (NamedDecl *D : ULE->decls()) {
15677       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15678         if (Method->isInstance())
15679           return true;
15680       } else {
15681         // Overload set does not contain methods.
15682         break;
15683       }
15684     }
15685 
15686     return false;
15687   }
15688 
15689   return false;
15690 }
15691 
15692 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15693                               UnaryOperatorKind Opc, Expr *Input) {
15694   // First things first: handle placeholders so that the
15695   // overloaded-operator check considers the right type.
15696   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15697     // Increment and decrement of pseudo-object references.
15698     if (pty->getKind() == BuiltinType::PseudoObject &&
15699         UnaryOperator::isIncrementDecrementOp(Opc))
15700       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15701 
15702     // extension is always a builtin operator.
15703     if (Opc == UO_Extension)
15704       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15705 
15706     // & gets special logic for several kinds of placeholder.
15707     // The builtin code knows what to do.
15708     if (Opc == UO_AddrOf &&
15709         (pty->getKind() == BuiltinType::Overload ||
15710          pty->getKind() == BuiltinType::UnknownAny ||
15711          pty->getKind() == BuiltinType::BoundMember))
15712       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15713 
15714     // Anything else needs to be handled now.
15715     ExprResult Result = CheckPlaceholderExpr(Input);
15716     if (Result.isInvalid()) return ExprError();
15717     Input = Result.get();
15718   }
15719 
15720   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15721       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15722       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15723     // Find all of the overloaded operators visible from this point.
15724     UnresolvedSet<16> Functions;
15725     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15726     if (S && OverOp != OO_None)
15727       LookupOverloadedOperatorName(OverOp, S, Functions);
15728 
15729     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15730   }
15731 
15732   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15733 }
15734 
15735 // Unary Operators.  'Tok' is the token for the operator.
15736 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
15737                               tok::TokenKind Op, Expr *Input) {
15738   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
15739 }
15740 
15741 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15742 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15743                                 LabelDecl *TheDecl) {
15744   TheDecl->markUsed(Context);
15745   // Create the AST node.  The address of a label always has type 'void*'.
15746   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
15747                                      Context.getPointerType(Context.VoidTy));
15748 }
15749 
15750 void Sema::ActOnStartStmtExpr() {
15751   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15752 }
15753 
15754 void Sema::ActOnStmtExprError() {
15755   // Note that function is also called by TreeTransform when leaving a
15756   // StmtExpr scope without rebuilding anything.
15757 
15758   DiscardCleanupsInEvaluationContext();
15759   PopExpressionEvaluationContext();
15760 }
15761 
15762 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15763                                SourceLocation RPLoc) {
15764   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15765 }
15766 
15767 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15768                                SourceLocation RPLoc, unsigned TemplateDepth) {
15769   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15770   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15771 
15772   if (hasAnyUnrecoverableErrorsInThisFunction())
15773     DiscardCleanupsInEvaluationContext();
15774   assert(!Cleanup.exprNeedsCleanups() &&
15775          "cleanups within StmtExpr not correctly bound!");
15776   PopExpressionEvaluationContext();
15777 
15778   // FIXME: there are a variety of strange constraints to enforce here, for
15779   // example, it is not possible to goto into a stmt expression apparently.
15780   // More semantic analysis is needed.
15781 
15782   // If there are sub-stmts in the compound stmt, take the type of the last one
15783   // as the type of the stmtexpr.
15784   QualType Ty = Context.VoidTy;
15785   bool StmtExprMayBindToTemp = false;
15786   if (!Compound->body_empty()) {
15787     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15788     if (const auto *LastStmt =
15789             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15790       if (const Expr *Value = LastStmt->getExprStmt()) {
15791         StmtExprMayBindToTemp = true;
15792         Ty = Value->getType();
15793       }
15794     }
15795   }
15796 
15797   // FIXME: Check that expression type is complete/non-abstract; statement
15798   // expressions are not lvalues.
15799   Expr *ResStmtExpr =
15800       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15801   if (StmtExprMayBindToTemp)
15802     return MaybeBindToTemporary(ResStmtExpr);
15803   return ResStmtExpr;
15804 }
15805 
15806 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15807   if (ER.isInvalid())
15808     return ExprError();
15809 
15810   // Do function/array conversion on the last expression, but not
15811   // lvalue-to-rvalue.  However, initialize an unqualified type.
15812   ER = DefaultFunctionArrayConversion(ER.get());
15813   if (ER.isInvalid())
15814     return ExprError();
15815   Expr *E = ER.get();
15816 
15817   if (E->isTypeDependent())
15818     return E;
15819 
15820   // In ARC, if the final expression ends in a consume, splice
15821   // the consume out and bind it later.  In the alternate case
15822   // (when dealing with a retainable type), the result
15823   // initialization will create a produce.  In both cases the
15824   // result will be +1, and we'll need to balance that out with
15825   // a bind.
15826   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15827   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15828     return Cast->getSubExpr();
15829 
15830   // FIXME: Provide a better location for the initialization.
15831   return PerformCopyInitialization(
15832       InitializedEntity::InitializeStmtExprResult(
15833           E->getBeginLoc(), E->getType().getUnqualifiedType()),
15834       SourceLocation(), E);
15835 }
15836 
15837 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15838                                       TypeSourceInfo *TInfo,
15839                                       ArrayRef<OffsetOfComponent> Components,
15840                                       SourceLocation RParenLoc) {
15841   QualType ArgTy = TInfo->getType();
15842   bool Dependent = ArgTy->isDependentType();
15843   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15844 
15845   // We must have at least one component that refers to the type, and the first
15846   // one is known to be a field designator.  Verify that the ArgTy represents
15847   // a struct/union/class.
15848   if (!Dependent && !ArgTy->isRecordType())
15849     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15850                        << ArgTy << TypeRange);
15851 
15852   // Type must be complete per C99 7.17p3 because a declaring a variable
15853   // with an incomplete type would be ill-formed.
15854   if (!Dependent
15855       && RequireCompleteType(BuiltinLoc, ArgTy,
15856                              diag::err_offsetof_incomplete_type, TypeRange))
15857     return ExprError();
15858 
15859   bool DidWarnAboutNonPOD = false;
15860   QualType CurrentType = ArgTy;
15861   SmallVector<OffsetOfNode, 4> Comps;
15862   SmallVector<Expr*, 4> Exprs;
15863   for (const OffsetOfComponent &OC : Components) {
15864     if (OC.isBrackets) {
15865       // Offset of an array sub-field.  TODO: Should we allow vector elements?
15866       if (!CurrentType->isDependentType()) {
15867         const ArrayType *AT = Context.getAsArrayType(CurrentType);
15868         if(!AT)
15869           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15870                            << CurrentType);
15871         CurrentType = AT->getElementType();
15872       } else
15873         CurrentType = Context.DependentTy;
15874 
15875       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15876       if (IdxRval.isInvalid())
15877         return ExprError();
15878       Expr *Idx = IdxRval.get();
15879 
15880       // The expression must be an integral expression.
15881       // FIXME: An integral constant expression?
15882       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15883           !Idx->getType()->isIntegerType())
15884         return ExprError(
15885             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15886             << Idx->getSourceRange());
15887 
15888       // Record this array index.
15889       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15890       Exprs.push_back(Idx);
15891       continue;
15892     }
15893 
15894     // Offset of a field.
15895     if (CurrentType->isDependentType()) {
15896       // We have the offset of a field, but we can't look into the dependent
15897       // type. Just record the identifier of the field.
15898       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15899       CurrentType = Context.DependentTy;
15900       continue;
15901     }
15902 
15903     // We need to have a complete type to look into.
15904     if (RequireCompleteType(OC.LocStart, CurrentType,
15905                             diag::err_offsetof_incomplete_type))
15906       return ExprError();
15907 
15908     // Look for the designated field.
15909     const RecordType *RC = CurrentType->getAs<RecordType>();
15910     if (!RC)
15911       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15912                        << CurrentType);
15913     RecordDecl *RD = RC->getDecl();
15914 
15915     // C++ [lib.support.types]p5:
15916     //   The macro offsetof accepts a restricted set of type arguments in this
15917     //   International Standard. type shall be a POD structure or a POD union
15918     //   (clause 9).
15919     // C++11 [support.types]p4:
15920     //   If type is not a standard-layout class (Clause 9), the results are
15921     //   undefined.
15922     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15923       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15924       unsigned DiagID =
15925         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15926                             : diag::ext_offsetof_non_pod_type;
15927 
15928       if (!IsSafe && !DidWarnAboutNonPOD &&
15929           DiagRuntimeBehavior(BuiltinLoc, nullptr,
15930                               PDiag(DiagID)
15931                               << SourceRange(Components[0].LocStart, OC.LocEnd)
15932                               << CurrentType))
15933         DidWarnAboutNonPOD = true;
15934     }
15935 
15936     // Look for the field.
15937     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15938     LookupQualifiedName(R, RD);
15939     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15940     IndirectFieldDecl *IndirectMemberDecl = nullptr;
15941     if (!MemberDecl) {
15942       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15943         MemberDecl = IndirectMemberDecl->getAnonField();
15944     }
15945 
15946     if (!MemberDecl)
15947       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15948                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15949                                                               OC.LocEnd));
15950 
15951     // C99 7.17p3:
15952     //   (If the specified member is a bit-field, the behavior is undefined.)
15953     //
15954     // We diagnose this as an error.
15955     if (MemberDecl->isBitField()) {
15956       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15957         << MemberDecl->getDeclName()
15958         << SourceRange(BuiltinLoc, RParenLoc);
15959       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15960       return ExprError();
15961     }
15962 
15963     RecordDecl *Parent = MemberDecl->getParent();
15964     if (IndirectMemberDecl)
15965       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15966 
15967     // If the member was found in a base class, introduce OffsetOfNodes for
15968     // the base class indirections.
15969     CXXBasePaths Paths;
15970     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15971                       Paths)) {
15972       if (Paths.getDetectedVirtual()) {
15973         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15974           << MemberDecl->getDeclName()
15975           << SourceRange(BuiltinLoc, RParenLoc);
15976         return ExprError();
15977       }
15978 
15979       CXXBasePath &Path = Paths.front();
15980       for (const CXXBasePathElement &B : Path)
15981         Comps.push_back(OffsetOfNode(B.Base));
15982     }
15983 
15984     if (IndirectMemberDecl) {
15985       for (auto *FI : IndirectMemberDecl->chain()) {
15986         assert(isa<FieldDecl>(FI));
15987         Comps.push_back(OffsetOfNode(OC.LocStart,
15988                                      cast<FieldDecl>(FI), OC.LocEnd));
15989       }
15990     } else
15991       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15992 
15993     CurrentType = MemberDecl->getType().getNonReferenceType();
15994   }
15995 
15996   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15997                               Comps, Exprs, RParenLoc);
15998 }
15999 
16000 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
16001                                       SourceLocation BuiltinLoc,
16002                                       SourceLocation TypeLoc,
16003                                       ParsedType ParsedArgTy,
16004                                       ArrayRef<OffsetOfComponent> Components,
16005                                       SourceLocation RParenLoc) {
16006 
16007   TypeSourceInfo *ArgTInfo;
16008   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16009   if (ArgTy.isNull())
16010     return ExprError();
16011 
16012   if (!ArgTInfo)
16013     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16014 
16015   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16016 }
16017 
16018 
16019 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16020                                  Expr *CondExpr,
16021                                  Expr *LHSExpr, Expr *RHSExpr,
16022                                  SourceLocation RPLoc) {
16023   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16024 
16025   ExprValueKind VK = VK_PRValue;
16026   ExprObjectKind OK = OK_Ordinary;
16027   QualType resType;
16028   bool CondIsTrue = false;
16029   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16030     resType = Context.DependentTy;
16031   } else {
16032     // The conditional expression is required to be a constant expression.
16033     llvm::APSInt condEval(32);
16034     ExprResult CondICE = VerifyIntegerConstantExpression(
16035         CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16036     if (CondICE.isInvalid())
16037       return ExprError();
16038     CondExpr = CondICE.get();
16039     CondIsTrue = condEval.getZExtValue();
16040 
16041     // If the condition is > zero, then the AST type is the same as the LHSExpr.
16042     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16043 
16044     resType = ActiveExpr->getType();
16045     VK = ActiveExpr->getValueKind();
16046     OK = ActiveExpr->getObjectKind();
16047   }
16048 
16049   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16050                                   resType, VK, OK, RPLoc, CondIsTrue);
16051 }
16052 
16053 //===----------------------------------------------------------------------===//
16054 // Clang Extensions.
16055 //===----------------------------------------------------------------------===//
16056 
16057 /// ActOnBlockStart - This callback is invoked when a block literal is started.
16058 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16059   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
16060 
16061   if (LangOpts.CPlusPlus) {
16062     MangleNumberingContext *MCtx;
16063     Decl *ManglingContextDecl;
16064     std::tie(MCtx, ManglingContextDecl) =
16065         getCurrentMangleNumberContext(Block->getDeclContext());
16066     if (MCtx) {
16067       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16068       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16069     }
16070   }
16071 
16072   PushBlockScope(CurScope, Block);
16073   CurContext->addDecl(Block);
16074   if (CurScope)
16075     PushDeclContext(CurScope, Block);
16076   else
16077     CurContext = Block;
16078 
16079   getCurBlock()->HasImplicitReturnType = true;
16080 
16081   // Enter a new evaluation context to insulate the block from any
16082   // cleanups from the enclosing full-expression.
16083   PushExpressionEvaluationContext(
16084       ExpressionEvaluationContext::PotentiallyEvaluated);
16085 }
16086 
16087 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16088                                Scope *CurScope) {
16089   assert(ParamInfo.getIdentifier() == nullptr &&
16090          "block-id should have no identifier!");
16091   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16092   BlockScopeInfo *CurBlock = getCurBlock();
16093 
16094   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
16095   QualType T = Sig->getType();
16096 
16097   // FIXME: We should allow unexpanded parameter packs here, but that would,
16098   // in turn, make the block expression contain unexpanded parameter packs.
16099   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16100     // Drop the parameters.
16101     FunctionProtoType::ExtProtoInfo EPI;
16102     EPI.HasTrailingReturn = false;
16103     EPI.TypeQuals.addConst();
16104     T = Context.getFunctionType(Context.DependentTy, None, EPI);
16105     Sig = Context.getTrivialTypeSourceInfo(T);
16106   }
16107 
16108   // GetTypeForDeclarator always produces a function type for a block
16109   // literal signature.  Furthermore, it is always a FunctionProtoType
16110   // unless the function was written with a typedef.
16111   assert(T->isFunctionType() &&
16112          "GetTypeForDeclarator made a non-function block signature");
16113 
16114   // Look for an explicit signature in that function type.
16115   FunctionProtoTypeLoc ExplicitSignature;
16116 
16117   if ((ExplicitSignature = Sig->getTypeLoc()
16118                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
16119 
16120     // Check whether that explicit signature was synthesized by
16121     // GetTypeForDeclarator.  If so, don't save that as part of the
16122     // written signature.
16123     if (ExplicitSignature.getLocalRangeBegin() ==
16124         ExplicitSignature.getLocalRangeEnd()) {
16125       // This would be much cheaper if we stored TypeLocs instead of
16126       // TypeSourceInfos.
16127       TypeLoc Result = ExplicitSignature.getReturnLoc();
16128       unsigned Size = Result.getFullDataSize();
16129       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16130       Sig->getTypeLoc().initializeFullCopy(Result, Size);
16131 
16132       ExplicitSignature = FunctionProtoTypeLoc();
16133     }
16134   }
16135 
16136   CurBlock->TheDecl->setSignatureAsWritten(Sig);
16137   CurBlock->FunctionType = T;
16138 
16139   const auto *Fn = T->castAs<FunctionType>();
16140   QualType RetTy = Fn->getReturnType();
16141   bool isVariadic =
16142       (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16143 
16144   CurBlock->TheDecl->setIsVariadic(isVariadic);
16145 
16146   // Context.DependentTy is used as a placeholder for a missing block
16147   // return type.  TODO:  what should we do with declarators like:
16148   //   ^ * { ... }
16149   // If the answer is "apply template argument deduction"....
16150   if (RetTy != Context.DependentTy) {
16151     CurBlock->ReturnType = RetTy;
16152     CurBlock->TheDecl->setBlockMissingReturnType(false);
16153     CurBlock->HasImplicitReturnType = false;
16154   }
16155 
16156   // Push block parameters from the declarator if we had them.
16157   SmallVector<ParmVarDecl*, 8> Params;
16158   if (ExplicitSignature) {
16159     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16160       ParmVarDecl *Param = ExplicitSignature.getParam(I);
16161       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16162           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16163         // Diagnose this as an extension in C17 and earlier.
16164         if (!getLangOpts().C2x)
16165           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
16166       }
16167       Params.push_back(Param);
16168     }
16169 
16170   // Fake up parameter variables if we have a typedef, like
16171   //   ^ fntype { ... }
16172   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16173     for (const auto &I : Fn->param_types()) {
16174       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16175           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16176       Params.push_back(Param);
16177     }
16178   }
16179 
16180   // Set the parameters on the block decl.
16181   if (!Params.empty()) {
16182     CurBlock->TheDecl->setParams(Params);
16183     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
16184                              /*CheckParameterNames=*/false);
16185   }
16186 
16187   // Finally we can process decl attributes.
16188   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16189 
16190   // Put the parameter variables in scope.
16191   for (auto AI : CurBlock->TheDecl->parameters()) {
16192     AI->setOwningFunction(CurBlock->TheDecl);
16193 
16194     // If this has an identifier, add it to the scope stack.
16195     if (AI->getIdentifier()) {
16196       CheckShadow(CurBlock->TheScope, AI);
16197 
16198       PushOnScopeChains(AI, CurBlock->TheScope);
16199     }
16200   }
16201 }
16202 
16203 /// ActOnBlockError - If there is an error parsing a block, this callback
16204 /// is invoked to pop the information about the block from the action impl.
16205 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16206   // Leave the expression-evaluation context.
16207   DiscardCleanupsInEvaluationContext();
16208   PopExpressionEvaluationContext();
16209 
16210   // Pop off CurBlock, handle nested blocks.
16211   PopDeclContext();
16212   PopFunctionScopeInfo();
16213 }
16214 
16215 /// ActOnBlockStmtExpr - This is called when the body of a block statement
16216 /// literal was successfully completed.  ^(int x){...}
16217 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16218                                     Stmt *Body, Scope *CurScope) {
16219   // If blocks are disabled, emit an error.
16220   if (!LangOpts.Blocks)
16221     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16222 
16223   // Leave the expression-evaluation context.
16224   if (hasAnyUnrecoverableErrorsInThisFunction())
16225     DiscardCleanupsInEvaluationContext();
16226   assert(!Cleanup.exprNeedsCleanups() &&
16227          "cleanups within block not correctly bound!");
16228   PopExpressionEvaluationContext();
16229 
16230   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16231   BlockDecl *BD = BSI->TheDecl;
16232 
16233   if (BSI->HasImplicitReturnType)
16234     deduceClosureReturnType(*BSI);
16235 
16236   QualType RetTy = Context.VoidTy;
16237   if (!BSI->ReturnType.isNull())
16238     RetTy = BSI->ReturnType;
16239 
16240   bool NoReturn = BD->hasAttr<NoReturnAttr>();
16241   QualType BlockTy;
16242 
16243   // If the user wrote a function type in some form, try to use that.
16244   if (!BSI->FunctionType.isNull()) {
16245     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16246 
16247     FunctionType::ExtInfo Ext = FTy->getExtInfo();
16248     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16249 
16250     // Turn protoless block types into nullary block types.
16251     if (isa<FunctionNoProtoType>(FTy)) {
16252       FunctionProtoType::ExtProtoInfo EPI;
16253       EPI.ExtInfo = Ext;
16254       BlockTy = Context.getFunctionType(RetTy, None, EPI);
16255 
16256     // Otherwise, if we don't need to change anything about the function type,
16257     // preserve its sugar structure.
16258     } else if (FTy->getReturnType() == RetTy &&
16259                (!NoReturn || FTy->getNoReturnAttr())) {
16260       BlockTy = BSI->FunctionType;
16261 
16262     // Otherwise, make the minimal modifications to the function type.
16263     } else {
16264       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16265       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16266       EPI.TypeQuals = Qualifiers();
16267       EPI.ExtInfo = Ext;
16268       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16269     }
16270 
16271   // If we don't have a function type, just build one from nothing.
16272   } else {
16273     FunctionProtoType::ExtProtoInfo EPI;
16274     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16275     BlockTy = Context.getFunctionType(RetTy, None, EPI);
16276   }
16277 
16278   DiagnoseUnusedParameters(BD->parameters());
16279   BlockTy = Context.getBlockPointerType(BlockTy);
16280 
16281   // If needed, diagnose invalid gotos and switches in the block.
16282   if (getCurFunction()->NeedsScopeChecking() &&
16283       !PP.isCodeCompletionEnabled())
16284     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16285 
16286   BD->setBody(cast<CompoundStmt>(Body));
16287 
16288   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16289     DiagnoseUnguardedAvailabilityViolations(BD);
16290 
16291   // Try to apply the named return value optimization. We have to check again
16292   // if we can do this, though, because blocks keep return statements around
16293   // to deduce an implicit return type.
16294   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16295       !BD->isDependentContext())
16296     computeNRVO(Body, BSI);
16297 
16298   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
16299       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
16300     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
16301                           NTCUK_Destruct|NTCUK_Copy);
16302 
16303   PopDeclContext();
16304 
16305   // Set the captured variables on the block.
16306   SmallVector<BlockDecl::Capture, 4> Captures;
16307   for (Capture &Cap : BSI->Captures) {
16308     if (Cap.isInvalid() || Cap.isThisCapture())
16309       continue;
16310 
16311     VarDecl *Var = Cap.getVariable();
16312     Expr *CopyExpr = nullptr;
16313     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16314       if (const RecordType *Record =
16315               Cap.getCaptureType()->getAs<RecordType>()) {
16316         // The capture logic needs the destructor, so make sure we mark it.
16317         // Usually this is unnecessary because most local variables have
16318         // their destructors marked at declaration time, but parameters are
16319         // an exception because it's technically only the call site that
16320         // actually requires the destructor.
16321         if (isa<ParmVarDecl>(Var))
16322           FinalizeVarWithDestructor(Var, Record);
16323 
16324         // Enter a separate potentially-evaluated context while building block
16325         // initializers to isolate their cleanups from those of the block
16326         // itself.
16327         // FIXME: Is this appropriate even when the block itself occurs in an
16328         // unevaluated operand?
16329         EnterExpressionEvaluationContext EvalContext(
16330             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16331 
16332         SourceLocation Loc = Cap.getLocation();
16333 
16334         ExprResult Result = BuildDeclarationNameExpr(
16335             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16336 
16337         // According to the blocks spec, the capture of a variable from
16338         // the stack requires a const copy constructor.  This is not true
16339         // of the copy/move done to move a __block variable to the heap.
16340         if (!Result.isInvalid() &&
16341             !Result.get()->getType().isConstQualified()) {
16342           Result = ImpCastExprToType(Result.get(),
16343                                      Result.get()->getType().withConst(),
16344                                      CK_NoOp, VK_LValue);
16345         }
16346 
16347         if (!Result.isInvalid()) {
16348           Result = PerformCopyInitialization(
16349               InitializedEntity::InitializeBlock(Var->getLocation(),
16350                                                  Cap.getCaptureType()),
16351               Loc, Result.get());
16352         }
16353 
16354         // Build a full-expression copy expression if initialization
16355         // succeeded and used a non-trivial constructor.  Recover from
16356         // errors by pretending that the copy isn't necessary.
16357         if (!Result.isInvalid() &&
16358             !cast<CXXConstructExpr>(Result.get())->getConstructor()
16359                 ->isTrivial()) {
16360           Result = MaybeCreateExprWithCleanups(Result);
16361           CopyExpr = Result.get();
16362         }
16363       }
16364     }
16365 
16366     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16367                               CopyExpr);
16368     Captures.push_back(NewCap);
16369   }
16370   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16371 
16372   // Pop the block scope now but keep it alive to the end of this function.
16373   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
16374   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16375 
16376   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16377 
16378   // If the block isn't obviously global, i.e. it captures anything at
16379   // all, then we need to do a few things in the surrounding context:
16380   if (Result->getBlockDecl()->hasCaptures()) {
16381     // First, this expression has a new cleanup object.
16382     ExprCleanupObjects.push_back(Result->getBlockDecl());
16383     Cleanup.setExprNeedsCleanups(true);
16384 
16385     // It also gets a branch-protected scope if any of the captured
16386     // variables needs destruction.
16387     for (const auto &CI : Result->getBlockDecl()->captures()) {
16388       const VarDecl *var = CI.getVariable();
16389       if (var->getType().isDestructedType() != QualType::DK_none) {
16390         setFunctionHasBranchProtectedScope();
16391         break;
16392       }
16393     }
16394   }
16395 
16396   if (getCurFunction())
16397     getCurFunction()->addBlock(BD);
16398 
16399   return Result;
16400 }
16401 
16402 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
16403                             SourceLocation RPLoc) {
16404   TypeSourceInfo *TInfo;
16405   GetTypeFromParser(Ty, &TInfo);
16406   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16407 }
16408 
16409 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
16410                                 Expr *E, TypeSourceInfo *TInfo,
16411                                 SourceLocation RPLoc) {
16412   Expr *OrigExpr = E;
16413   bool IsMS = false;
16414 
16415   // CUDA device code does not support varargs.
16416   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16417     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16418       CUDAFunctionTarget T = IdentifyCUDATarget(F);
16419       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
16420         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16421     }
16422   }
16423 
16424   // NVPTX does not support va_arg expression.
16425   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
16426       Context.getTargetInfo().getTriple().isNVPTX())
16427     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16428 
16429   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16430   // as Microsoft ABI on an actual Microsoft platform, where
16431   // __builtin_ms_va_list and __builtin_va_list are the same.)
16432   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16433       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16434     QualType MSVaListType = Context.getBuiltinMSVaListType();
16435     if (Context.hasSameType(MSVaListType, E->getType())) {
16436       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16437         return ExprError();
16438       IsMS = true;
16439     }
16440   }
16441 
16442   // Get the va_list type
16443   QualType VaListType = Context.getBuiltinVaListType();
16444   if (!IsMS) {
16445     if (VaListType->isArrayType()) {
16446       // Deal with implicit array decay; for example, on x86-64,
16447       // va_list is an array, but it's supposed to decay to
16448       // a pointer for va_arg.
16449       VaListType = Context.getArrayDecayedType(VaListType);
16450       // Make sure the input expression also decays appropriately.
16451       ExprResult Result = UsualUnaryConversions(E);
16452       if (Result.isInvalid())
16453         return ExprError();
16454       E = Result.get();
16455     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16456       // If va_list is a record type and we are compiling in C++ mode,
16457       // check the argument using reference binding.
16458       InitializedEntity Entity = InitializedEntity::InitializeParameter(
16459           Context, Context.getLValueReferenceType(VaListType), false);
16460       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
16461       if (Init.isInvalid())
16462         return ExprError();
16463       E = Init.getAs<Expr>();
16464     } else {
16465       // Otherwise, the va_list argument must be an l-value because
16466       // it is modified by va_arg.
16467       if (!E->isTypeDependent() &&
16468           CheckForModifiableLvalue(E, BuiltinLoc, *this))
16469         return ExprError();
16470     }
16471   }
16472 
16473   if (!IsMS && !E->isTypeDependent() &&
16474       !Context.hasSameType(VaListType, E->getType()))
16475     return ExprError(
16476         Diag(E->getBeginLoc(),
16477              diag::err_first_argument_to_va_arg_not_of_type_va_list)
16478         << OrigExpr->getType() << E->getSourceRange());
16479 
16480   if (!TInfo->getType()->isDependentType()) {
16481     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16482                             diag::err_second_parameter_to_va_arg_incomplete,
16483                             TInfo->getTypeLoc()))
16484       return ExprError();
16485 
16486     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
16487                                TInfo->getType(),
16488                                diag::err_second_parameter_to_va_arg_abstract,
16489                                TInfo->getTypeLoc()))
16490       return ExprError();
16491 
16492     if (!TInfo->getType().isPODType(Context)) {
16493       Diag(TInfo->getTypeLoc().getBeginLoc(),
16494            TInfo->getType()->isObjCLifetimeType()
16495              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16496              : diag::warn_second_parameter_to_va_arg_not_pod)
16497         << TInfo->getType()
16498         << TInfo->getTypeLoc().getSourceRange();
16499     }
16500 
16501     // Check for va_arg where arguments of the given type will be promoted
16502     // (i.e. this va_arg is guaranteed to have undefined behavior).
16503     QualType PromoteType;
16504     if (TInfo->getType()->isPromotableIntegerType()) {
16505       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16506       // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16507       // and C2x 7.16.1.1p2 says, in part:
16508       //   If type is not compatible with the type of the actual next argument
16509       //   (as promoted according to the default argument promotions), the
16510       //   behavior is undefined, except for the following cases:
16511       //     - both types are pointers to qualified or unqualified versions of
16512       //       compatible types;
16513       //     - one type is a signed integer type, the other type is the
16514       //       corresponding unsigned integer type, and the value is
16515       //       representable in both types;
16516       //     - one type is pointer to qualified or unqualified void and the
16517       //       other is a pointer to a qualified or unqualified character type.
16518       // Given that type compatibility is the primary requirement (ignoring
16519       // qualifications), you would think we could call typesAreCompatible()
16520       // directly to test this. However, in C++, that checks for *same type*,
16521       // which causes false positives when passing an enumeration type to
16522       // va_arg. Instead, get the underlying type of the enumeration and pass
16523       // that.
16524       QualType UnderlyingType = TInfo->getType();
16525       if (const auto *ET = UnderlyingType->getAs<EnumType>())
16526         UnderlyingType = ET->getDecl()->getIntegerType();
16527       if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16528                                      /*CompareUnqualified*/ true))
16529         PromoteType = QualType();
16530 
16531       // If the types are still not compatible, we need to test whether the
16532       // promoted type and the underlying type are the same except for
16533       // signedness. Ask the AST for the correctly corresponding type and see
16534       // if that's compatible.
16535       if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16536           PromoteType->isUnsignedIntegerType() !=
16537               UnderlyingType->isUnsignedIntegerType()) {
16538         UnderlyingType =
16539             UnderlyingType->isUnsignedIntegerType()
16540                 ? Context.getCorrespondingSignedType(UnderlyingType)
16541                 : Context.getCorrespondingUnsignedType(UnderlyingType);
16542         if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16543                                        /*CompareUnqualified*/ true))
16544           PromoteType = QualType();
16545       }
16546     }
16547     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16548       PromoteType = Context.DoubleTy;
16549     if (!PromoteType.isNull())
16550       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
16551                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16552                           << TInfo->getType()
16553                           << PromoteType
16554                           << TInfo->getTypeLoc().getSourceRange());
16555   }
16556 
16557   QualType T = TInfo->getType().getNonLValueExprType(Context);
16558   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16559 }
16560 
16561 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
16562   // The type of __null will be int or long, depending on the size of
16563   // pointers on the target.
16564   QualType Ty;
16565   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
16566   if (pw == Context.getTargetInfo().getIntWidth())
16567     Ty = Context.IntTy;
16568   else if (pw == Context.getTargetInfo().getLongWidth())
16569     Ty = Context.LongTy;
16570   else if (pw == Context.getTargetInfo().getLongLongWidth())
16571     Ty = Context.LongLongTy;
16572   else {
16573     llvm_unreachable("I don't know size of pointer!");
16574   }
16575 
16576   return new (Context) GNUNullExpr(Ty, TokenLoc);
16577 }
16578 
16579 static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
16580   CXXRecordDecl *ImplDecl = nullptr;
16581 
16582   // Fetch the std::source_location::__impl decl.
16583   if (NamespaceDecl *Std = S.getStdNamespace()) {
16584     LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16585                           Loc, Sema::LookupOrdinaryName);
16586     if (S.LookupQualifiedName(ResultSL, Std)) {
16587       if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16588         LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16589                                 Loc, Sema::LookupOrdinaryName);
16590         if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16591             S.LookupQualifiedName(ResultImpl, SLDecl)) {
16592           ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16593         }
16594       }
16595     }
16596   }
16597 
16598   if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16599     S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16600     return nullptr;
16601   }
16602 
16603   // Verify that __impl is a trivial struct type, with no base classes, and with
16604   // only the four expected fields.
16605   if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16606       ImplDecl->getNumBases() != 0) {
16607     S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16608     return nullptr;
16609   }
16610 
16611   unsigned Count = 0;
16612   for (FieldDecl *F : ImplDecl->fields()) {
16613     StringRef Name = F->getName();
16614 
16615     if (Name == "_M_file_name") {
16616       if (F->getType() !=
16617           S.Context.getPointerType(S.Context.CharTy.withConst()))
16618         break;
16619       Count++;
16620     } else if (Name == "_M_function_name") {
16621       if (F->getType() !=
16622           S.Context.getPointerType(S.Context.CharTy.withConst()))
16623         break;
16624       Count++;
16625     } else if (Name == "_M_line") {
16626       if (!F->getType()->isIntegerType())
16627         break;
16628       Count++;
16629     } else if (Name == "_M_column") {
16630       if (!F->getType()->isIntegerType())
16631         break;
16632       Count++;
16633     } else {
16634       Count = 100; // invalid
16635       break;
16636     }
16637   }
16638   if (Count != 4) {
16639     S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16640     return nullptr;
16641   }
16642 
16643   return ImplDecl;
16644 }
16645 
16646 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
16647                                     SourceLocation BuiltinLoc,
16648                                     SourceLocation RPLoc) {
16649   QualType ResultTy;
16650   switch (Kind) {
16651   case SourceLocExpr::File:
16652   case SourceLocExpr::Function: {
16653     QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
16654     ResultTy =
16655         Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
16656     break;
16657   }
16658   case SourceLocExpr::Line:
16659   case SourceLocExpr::Column:
16660     ResultTy = Context.UnsignedIntTy;
16661     break;
16662   case SourceLocExpr::SourceLocStruct:
16663     if (!StdSourceLocationImplDecl) {
16664       StdSourceLocationImplDecl =
16665           LookupStdSourceLocationImpl(*this, BuiltinLoc);
16666       if (!StdSourceLocationImplDecl)
16667         return ExprError();
16668     }
16669     ResultTy = Context.getPointerType(
16670         Context.getRecordType(StdSourceLocationImplDecl).withConst());
16671     break;
16672   }
16673 
16674   return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16675 }
16676 
16677 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
16678                                     QualType ResultTy,
16679                                     SourceLocation BuiltinLoc,
16680                                     SourceLocation RPLoc,
16681                                     DeclContext *ParentContext) {
16682   return new (Context)
16683       SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16684 }
16685 
16686 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
16687                                         bool Diagnose) {
16688   if (!getLangOpts().ObjC)
16689     return false;
16690 
16691   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
16692   if (!PT)
16693     return false;
16694   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
16695 
16696   // Ignore any parens, implicit casts (should only be
16697   // array-to-pointer decays), and not-so-opaque values.  The last is
16698   // important for making this trigger for property assignments.
16699   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
16700   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
16701     if (OV->getSourceExpr())
16702       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
16703 
16704   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
16705     if (!PT->isObjCIdType() &&
16706         !(ID && ID->getIdentifier()->isStr("NSString")))
16707       return false;
16708     if (!SL->isAscii())
16709       return false;
16710 
16711     if (Diagnose) {
16712       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
16713           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
16714       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
16715     }
16716     return true;
16717   }
16718 
16719   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
16720       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
16721       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
16722       !SrcExpr->isNullPointerConstant(
16723           getASTContext(), Expr::NPC_NeverValueDependent)) {
16724     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
16725       return false;
16726     if (Diagnose) {
16727       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
16728           << /*number*/1
16729           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
16730       Expr *NumLit =
16731           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
16732       if (NumLit)
16733         Exp = NumLit;
16734     }
16735     return true;
16736   }
16737 
16738   return false;
16739 }
16740 
16741 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
16742                                               const Expr *SrcExpr) {
16743   if (!DstType->isFunctionPointerType() ||
16744       !SrcExpr->getType()->isFunctionType())
16745     return false;
16746 
16747   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16748   if (!DRE)
16749     return false;
16750 
16751   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16752   if (!FD)
16753     return false;
16754 
16755   return !S.checkAddressOfFunctionIsAvailable(FD,
16756                                               /*Complain=*/true,
16757                                               SrcExpr->getBeginLoc());
16758 }
16759 
16760 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16761                                     SourceLocation Loc,
16762                                     QualType DstType, QualType SrcType,
16763                                     Expr *SrcExpr, AssignmentAction Action,
16764                                     bool *Complained) {
16765   if (Complained)
16766     *Complained = false;
16767 
16768   // Decode the result (notice that AST's are still created for extensions).
16769   bool CheckInferredResultType = false;
16770   bool isInvalid = false;
16771   unsigned DiagKind = 0;
16772   ConversionFixItGenerator ConvHints;
16773   bool MayHaveConvFixit = false;
16774   bool MayHaveFunctionDiff = false;
16775   const ObjCInterfaceDecl *IFace = nullptr;
16776   const ObjCProtocolDecl *PDecl = nullptr;
16777 
16778   switch (ConvTy) {
16779   case Compatible:
16780       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16781       return false;
16782 
16783   case PointerToInt:
16784     if (getLangOpts().CPlusPlus) {
16785       DiagKind = diag::err_typecheck_convert_pointer_int;
16786       isInvalid = true;
16787     } else {
16788       DiagKind = diag::ext_typecheck_convert_pointer_int;
16789     }
16790     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16791     MayHaveConvFixit = true;
16792     break;
16793   case IntToPointer:
16794     if (getLangOpts().CPlusPlus) {
16795       DiagKind = diag::err_typecheck_convert_int_pointer;
16796       isInvalid = true;
16797     } else {
16798       DiagKind = diag::ext_typecheck_convert_int_pointer;
16799     }
16800     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16801     MayHaveConvFixit = true;
16802     break;
16803   case IncompatibleFunctionPointer:
16804     if (getLangOpts().CPlusPlus) {
16805       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16806       isInvalid = true;
16807     } else {
16808       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16809     }
16810     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16811     MayHaveConvFixit = true;
16812     break;
16813   case IncompatiblePointer:
16814     if (Action == AA_Passing_CFAudited) {
16815       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16816     } else if (getLangOpts().CPlusPlus) {
16817       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16818       isInvalid = true;
16819     } else {
16820       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16821     }
16822     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16823       SrcType->isObjCObjectPointerType();
16824     if (!CheckInferredResultType) {
16825       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16826     } else if (CheckInferredResultType) {
16827       SrcType = SrcType.getUnqualifiedType();
16828       DstType = DstType.getUnqualifiedType();
16829     }
16830     MayHaveConvFixit = true;
16831     break;
16832   case IncompatiblePointerSign:
16833     if (getLangOpts().CPlusPlus) {
16834       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16835       isInvalid = true;
16836     } else {
16837       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16838     }
16839     break;
16840   case FunctionVoidPointer:
16841     if (getLangOpts().CPlusPlus) {
16842       DiagKind = diag::err_typecheck_convert_pointer_void_func;
16843       isInvalid = true;
16844     } else {
16845       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16846     }
16847     break;
16848   case IncompatiblePointerDiscardsQualifiers: {
16849     // Perform array-to-pointer decay if necessary.
16850     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16851 
16852     isInvalid = true;
16853 
16854     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16855     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16856     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16857       DiagKind = diag::err_typecheck_incompatible_address_space;
16858       break;
16859 
16860     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16861       DiagKind = diag::err_typecheck_incompatible_ownership;
16862       break;
16863     }
16864 
16865     llvm_unreachable("unknown error case for discarding qualifiers!");
16866     // fallthrough
16867   }
16868   case CompatiblePointerDiscardsQualifiers:
16869     // If the qualifiers lost were because we were applying the
16870     // (deprecated) C++ conversion from a string literal to a char*
16871     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
16872     // Ideally, this check would be performed in
16873     // checkPointerTypesForAssignment. However, that would require a
16874     // bit of refactoring (so that the second argument is an
16875     // expression, rather than a type), which should be done as part
16876     // of a larger effort to fix checkPointerTypesForAssignment for
16877     // C++ semantics.
16878     if (getLangOpts().CPlusPlus &&
16879         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16880       return false;
16881     if (getLangOpts().CPlusPlus) {
16882       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
16883       isInvalid = true;
16884     } else {
16885       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
16886     }
16887 
16888     break;
16889   case IncompatibleNestedPointerQualifiers:
16890     if (getLangOpts().CPlusPlus) {
16891       isInvalid = true;
16892       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16893     } else {
16894       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16895     }
16896     break;
16897   case IncompatibleNestedPointerAddressSpaceMismatch:
16898     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16899     isInvalid = true;
16900     break;
16901   case IntToBlockPointer:
16902     DiagKind = diag::err_int_to_block_pointer;
16903     isInvalid = true;
16904     break;
16905   case IncompatibleBlockPointer:
16906     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16907     isInvalid = true;
16908     break;
16909   case IncompatibleObjCQualifiedId: {
16910     if (SrcType->isObjCQualifiedIdType()) {
16911       const ObjCObjectPointerType *srcOPT =
16912                 SrcType->castAs<ObjCObjectPointerType>();
16913       for (auto *srcProto : srcOPT->quals()) {
16914         PDecl = srcProto;
16915         break;
16916       }
16917       if (const ObjCInterfaceType *IFaceT =
16918             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16919         IFace = IFaceT->getDecl();
16920     }
16921     else if (DstType->isObjCQualifiedIdType()) {
16922       const ObjCObjectPointerType *dstOPT =
16923         DstType->castAs<ObjCObjectPointerType>();
16924       for (auto *dstProto : dstOPT->quals()) {
16925         PDecl = dstProto;
16926         break;
16927       }
16928       if (const ObjCInterfaceType *IFaceT =
16929             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16930         IFace = IFaceT->getDecl();
16931     }
16932     if (getLangOpts().CPlusPlus) {
16933       DiagKind = diag::err_incompatible_qualified_id;
16934       isInvalid = true;
16935     } else {
16936       DiagKind = diag::warn_incompatible_qualified_id;
16937     }
16938     break;
16939   }
16940   case IncompatibleVectors:
16941     if (getLangOpts().CPlusPlus) {
16942       DiagKind = diag::err_incompatible_vectors;
16943       isInvalid = true;
16944     } else {
16945       DiagKind = diag::warn_incompatible_vectors;
16946     }
16947     break;
16948   case IncompatibleObjCWeakRef:
16949     DiagKind = diag::err_arc_weak_unavailable_assign;
16950     isInvalid = true;
16951     break;
16952   case Incompatible:
16953     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16954       if (Complained)
16955         *Complained = true;
16956       return true;
16957     }
16958 
16959     DiagKind = diag::err_typecheck_convert_incompatible;
16960     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16961     MayHaveConvFixit = true;
16962     isInvalid = true;
16963     MayHaveFunctionDiff = true;
16964     break;
16965   }
16966 
16967   QualType FirstType, SecondType;
16968   switch (Action) {
16969   case AA_Assigning:
16970   case AA_Initializing:
16971     // The destination type comes first.
16972     FirstType = DstType;
16973     SecondType = SrcType;
16974     break;
16975 
16976   case AA_Returning:
16977   case AA_Passing:
16978   case AA_Passing_CFAudited:
16979   case AA_Converting:
16980   case AA_Sending:
16981   case AA_Casting:
16982     // The source type comes first.
16983     FirstType = SrcType;
16984     SecondType = DstType;
16985     break;
16986   }
16987 
16988   PartialDiagnostic FDiag = PDiag(DiagKind);
16989   AssignmentAction ActionForDiag = Action;
16990   if (Action == AA_Passing_CFAudited)
16991     ActionForDiag = AA_Passing;
16992 
16993   FDiag << FirstType << SecondType << ActionForDiag
16994         << SrcExpr->getSourceRange();
16995 
16996   if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16997       DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16998     auto isPlainChar = [](const clang::Type *Type) {
16999       return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17000              Type->isSpecificBuiltinType(BuiltinType::Char_U);
17001     };
17002     FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17003               isPlainChar(SecondType->getPointeeOrArrayElementType()));
17004   }
17005 
17006   // If we can fix the conversion, suggest the FixIts.
17007   if (!ConvHints.isNull()) {
17008     for (FixItHint &H : ConvHints.Hints)
17009       FDiag << H;
17010   }
17011 
17012   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17013 
17014   if (MayHaveFunctionDiff)
17015     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17016 
17017   Diag(Loc, FDiag);
17018   if ((DiagKind == diag::warn_incompatible_qualified_id ||
17019        DiagKind == diag::err_incompatible_qualified_id) &&
17020       PDecl && IFace && !IFace->hasDefinition())
17021     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17022         << IFace << PDecl;
17023 
17024   if (SecondType == Context.OverloadTy)
17025     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
17026                               FirstType, /*TakingAddress=*/true);
17027 
17028   if (CheckInferredResultType)
17029     EmitRelatedResultTypeNote(SrcExpr);
17030 
17031   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17032     EmitRelatedResultTypeNoteForReturn(DstType);
17033 
17034   if (Complained)
17035     *Complained = true;
17036   return isInvalid;
17037 }
17038 
17039 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17040                                                  llvm::APSInt *Result,
17041                                                  AllowFoldKind CanFold) {
17042   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17043   public:
17044     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17045                                              QualType T) override {
17046       return S.Diag(Loc, diag::err_ice_not_integral)
17047              << T << S.LangOpts.CPlusPlus;
17048     }
17049     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17050       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17051     }
17052   } Diagnoser;
17053 
17054   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17055 }
17056 
17057 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17058                                                  llvm::APSInt *Result,
17059                                                  unsigned DiagID,
17060                                                  AllowFoldKind CanFold) {
17061   class IDDiagnoser : public VerifyICEDiagnoser {
17062     unsigned DiagID;
17063 
17064   public:
17065     IDDiagnoser(unsigned DiagID)
17066       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17067 
17068     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17069       return S.Diag(Loc, DiagID);
17070     }
17071   } Diagnoser(DiagID);
17072 
17073   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17074 }
17075 
17076 Sema::SemaDiagnosticBuilder
17077 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17078                                              QualType T) {
17079   return diagnoseNotICE(S, Loc);
17080 }
17081 
17082 Sema::SemaDiagnosticBuilder
17083 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17084   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17085 }
17086 
17087 ExprResult
17088 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17089                                       VerifyICEDiagnoser &Diagnoser,
17090                                       AllowFoldKind CanFold) {
17091   SourceLocation DiagLoc = E->getBeginLoc();
17092 
17093   if (getLangOpts().CPlusPlus11) {
17094     // C++11 [expr.const]p5:
17095     //   If an expression of literal class type is used in a context where an
17096     //   integral constant expression is required, then that class type shall
17097     //   have a single non-explicit conversion function to an integral or
17098     //   unscoped enumeration type
17099     ExprResult Converted;
17100     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17101       VerifyICEDiagnoser &BaseDiagnoser;
17102     public:
17103       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17104           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17105                                 BaseDiagnoser.Suppress, true),
17106             BaseDiagnoser(BaseDiagnoser) {}
17107 
17108       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17109                                            QualType T) override {
17110         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17111       }
17112 
17113       SemaDiagnosticBuilder diagnoseIncomplete(
17114           Sema &S, SourceLocation Loc, QualType T) override {
17115         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17116       }
17117 
17118       SemaDiagnosticBuilder diagnoseExplicitConv(
17119           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17120         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17121       }
17122 
17123       SemaDiagnosticBuilder noteExplicitConv(
17124           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17125         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17126                  << ConvTy->isEnumeralType() << ConvTy;
17127       }
17128 
17129       SemaDiagnosticBuilder diagnoseAmbiguous(
17130           Sema &S, SourceLocation Loc, QualType T) override {
17131         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17132       }
17133 
17134       SemaDiagnosticBuilder noteAmbiguous(
17135           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17136         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17137                  << ConvTy->isEnumeralType() << ConvTy;
17138       }
17139 
17140       SemaDiagnosticBuilder diagnoseConversion(
17141           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17142         llvm_unreachable("conversion functions are permitted");
17143       }
17144     } ConvertDiagnoser(Diagnoser);
17145 
17146     Converted = PerformContextualImplicitConversion(DiagLoc, E,
17147                                                     ConvertDiagnoser);
17148     if (Converted.isInvalid())
17149       return Converted;
17150     E = Converted.get();
17151     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
17152       return ExprError();
17153   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17154     // An ICE must be of integral or unscoped enumeration type.
17155     if (!Diagnoser.Suppress)
17156       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17157           << E->getSourceRange();
17158     return ExprError();
17159   }
17160 
17161   ExprResult RValueExpr = DefaultLvalueConversion(E);
17162   if (RValueExpr.isInvalid())
17163     return ExprError();
17164 
17165   E = RValueExpr.get();
17166 
17167   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17168   // in the non-ICE case.
17169   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
17170     if (Result)
17171       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
17172     if (!isa<ConstantExpr>(E))
17173       E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
17174                  : ConstantExpr::Create(Context, E);
17175     return E;
17176   }
17177 
17178   Expr::EvalResult EvalResult;
17179   SmallVector<PartialDiagnosticAt, 8> Notes;
17180   EvalResult.Diag = &Notes;
17181 
17182   // Try to evaluate the expression, and produce diagnostics explaining why it's
17183   // not a constant expression as a side-effect.
17184   bool Folded =
17185       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17186       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
17187 
17188   if (!isa<ConstantExpr>(E))
17189     E = ConstantExpr::Create(Context, E, EvalResult.Val);
17190 
17191   // In C++11, we can rely on diagnostics being produced for any expression
17192   // which is not a constant expression. If no diagnostics were produced, then
17193   // this is a constant expression.
17194   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17195     if (Result)
17196       *Result = EvalResult.Val.getInt();
17197     return E;
17198   }
17199 
17200   // If our only note is the usual "invalid subexpression" note, just point
17201   // the caret at its location rather than producing an essentially
17202   // redundant note.
17203   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17204         diag::note_invalid_subexpr_in_const_expr) {
17205     DiagLoc = Notes[0].first;
17206     Notes.clear();
17207   }
17208 
17209   if (!Folded || !CanFold) {
17210     if (!Diagnoser.Suppress) {
17211       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17212       for (const PartialDiagnosticAt &Note : Notes)
17213         Diag(Note.first, Note.second);
17214     }
17215 
17216     return ExprError();
17217   }
17218 
17219   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17220   for (const PartialDiagnosticAt &Note : Notes)
17221     Diag(Note.first, Note.second);
17222 
17223   if (Result)
17224     *Result = EvalResult.Val.getInt();
17225   return E;
17226 }
17227 
17228 namespace {
17229   // Handle the case where we conclude a expression which we speculatively
17230   // considered to be unevaluated is actually evaluated.
17231   class TransformToPE : public TreeTransform<TransformToPE> {
17232     typedef TreeTransform<TransformToPE> BaseTransform;
17233 
17234   public:
17235     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17236 
17237     // Make sure we redo semantic analysis
17238     bool AlwaysRebuild() { return true; }
17239     bool ReplacingOriginal() { return true; }
17240 
17241     // We need to special-case DeclRefExprs referring to FieldDecls which
17242     // are not part of a member pointer formation; normal TreeTransforming
17243     // doesn't catch this case because of the way we represent them in the AST.
17244     // FIXME: This is a bit ugly; is it really the best way to handle this
17245     // case?
17246     //
17247     // Error on DeclRefExprs referring to FieldDecls.
17248     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17249       if (isa<FieldDecl>(E->getDecl()) &&
17250           !SemaRef.isUnevaluatedContext())
17251         return SemaRef.Diag(E->getLocation(),
17252                             diag::err_invalid_non_static_member_use)
17253             << E->getDecl() << E->getSourceRange();
17254 
17255       return BaseTransform::TransformDeclRefExpr(E);
17256     }
17257 
17258     // Exception: filter out member pointer formation
17259     ExprResult TransformUnaryOperator(UnaryOperator *E) {
17260       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17261         return E;
17262 
17263       return BaseTransform::TransformUnaryOperator(E);
17264     }
17265 
17266     // The body of a lambda-expression is in a separate expression evaluation
17267     // context so never needs to be transformed.
17268     // FIXME: Ideally we wouldn't transform the closure type either, and would
17269     // just recreate the capture expressions and lambda expression.
17270     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17271       return SkipLambdaBody(E, Body);
17272     }
17273   };
17274 }
17275 
17276 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
17277   assert(isUnevaluatedContext() &&
17278          "Should only transform unevaluated expressions");
17279   ExprEvalContexts.back().Context =
17280       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17281   if (isUnevaluatedContext())
17282     return E;
17283   return TransformToPE(*this).TransformExpr(E);
17284 }
17285 
17286 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
17287   assert(isUnevaluatedContext() &&
17288          "Should only transform unevaluated expressions");
17289   ExprEvalContexts.back().Context =
17290       ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
17291   if (isUnevaluatedContext())
17292     return TInfo;
17293   return TransformToPE(*this).TransformType(TInfo);
17294 }
17295 
17296 void
17297 Sema::PushExpressionEvaluationContext(
17298     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17299     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17300   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17301                                 LambdaContextDecl, ExprContext);
17302 
17303   // Discarded statements and immediate contexts nested in other
17304   // discarded statements or immediate context are themselves
17305   // a discarded statement or an immediate context, respectively.
17306   ExprEvalContexts.back().InDiscardedStatement =
17307       ExprEvalContexts[ExprEvalContexts.size() - 2]
17308           .isDiscardedStatementContext();
17309   ExprEvalContexts.back().InImmediateFunctionContext =
17310       ExprEvalContexts[ExprEvalContexts.size() - 2]
17311           .isImmediateFunctionContext();
17312 
17313   Cleanup.reset();
17314   if (!MaybeODRUseExprs.empty())
17315     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17316 }
17317 
17318 void
17319 Sema::PushExpressionEvaluationContext(
17320     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
17321     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17322   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17323   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17324 }
17325 
17326 namespace {
17327 
17328 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17329   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17330   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17331     if (E->getOpcode() == UO_Deref)
17332       return CheckPossibleDeref(S, E->getSubExpr());
17333   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17334     return CheckPossibleDeref(S, E->getBase());
17335   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17336     return CheckPossibleDeref(S, E->getBase());
17337   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17338     QualType Inner;
17339     QualType Ty = E->getType();
17340     if (const auto *Ptr = Ty->getAs<PointerType>())
17341       Inner = Ptr->getPointeeType();
17342     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17343       Inner = Arr->getElementType();
17344     else
17345       return nullptr;
17346 
17347     if (Inner->hasAttr(attr::NoDeref))
17348       return E;
17349   }
17350   return nullptr;
17351 }
17352 
17353 } // namespace
17354 
17355 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
17356   for (const Expr *E : Rec.PossibleDerefs) {
17357     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17358     if (DeclRef) {
17359       const ValueDecl *Decl = DeclRef->getDecl();
17360       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17361           << Decl->getName() << E->getSourceRange();
17362       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17363     } else {
17364       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17365           << E->getSourceRange();
17366     }
17367   }
17368   Rec.PossibleDerefs.clear();
17369 }
17370 
17371 /// Check whether E, which is either a discarded-value expression or an
17372 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17373 /// and if so, remove it from the list of volatile-qualified assignments that
17374 /// we are going to warn are deprecated.
17375 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
17376   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
17377     return;
17378 
17379   // Note: ignoring parens here is not justified by the standard rules, but
17380   // ignoring parentheses seems like a more reasonable approach, and this only
17381   // drives a deprecation warning so doesn't affect conformance.
17382   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17383     if (BO->getOpcode() == BO_Assign) {
17384       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17385       llvm::erase_value(LHSs, BO->getLHS());
17386     }
17387   }
17388 }
17389 
17390 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
17391   if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17392       !Decl->isConsteval() || isConstantEvaluated() ||
17393       RebuildingImmediateInvocation || isImmediateFunctionContext())
17394     return E;
17395 
17396   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17397   /// It's OK if this fails; we'll also remove this in
17398   /// HandleImmediateInvocations, but catching it here allows us to avoid
17399   /// walking the AST looking for it in simple cases.
17400   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17401     if (auto *DeclRef =
17402             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17403       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17404 
17405   E = MaybeCreateExprWithCleanups(E);
17406 
17407   ConstantExpr *Res = ConstantExpr::Create(
17408       getASTContext(), E.get(),
17409       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17410                                    getASTContext()),
17411       /*IsImmediateInvocation*/ true);
17412   /// Value-dependent constant expressions should not be immediately
17413   /// evaluated until they are instantiated.
17414   if (!Res->isValueDependent())
17415     ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17416   return Res;
17417 }
17418 
17419 static void EvaluateAndDiagnoseImmediateInvocation(
17420     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
17421   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
17422   Expr::EvalResult Eval;
17423   Eval.Diag = &Notes;
17424   ConstantExpr *CE = Candidate.getPointer();
17425   bool Result = CE->EvaluateAsConstantExpr(
17426       Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17427   if (!Result || !Notes.empty()) {
17428     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17429     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17430       InnerExpr = FunctionalCast->getSubExpr();
17431     FunctionDecl *FD = nullptr;
17432     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17433       FD = cast<FunctionDecl>(Call->getCalleeDecl());
17434     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17435       FD = Call->getConstructor();
17436     else
17437       llvm_unreachable("unhandled decl kind");
17438     assert(FD->isConsteval());
17439     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
17440     for (auto &Note : Notes)
17441       SemaRef.Diag(Note.first, Note.second);
17442     return;
17443   }
17444   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
17445 }
17446 
17447 static void RemoveNestedImmediateInvocation(
17448     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
17449     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
17450   struct ComplexRemove : TreeTransform<ComplexRemove> {
17451     using Base = TreeTransform<ComplexRemove>;
17452     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17453     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
17454     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
17455         CurrentII;
17456     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17457                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
17458                   SmallVector<Sema::ImmediateInvocationCandidate,
17459                               4>::reverse_iterator Current)
17460         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17461     void RemoveImmediateInvocation(ConstantExpr* E) {
17462       auto It = std::find_if(CurrentII, IISet.rend(),
17463                              [E](Sema::ImmediateInvocationCandidate Elem) {
17464                                return Elem.getPointer() == E;
17465                              });
17466       assert(It != IISet.rend() &&
17467              "ConstantExpr marked IsImmediateInvocation should "
17468              "be present");
17469       It->setInt(1); // Mark as deleted
17470     }
17471     ExprResult TransformConstantExpr(ConstantExpr *E) {
17472       if (!E->isImmediateInvocation())
17473         return Base::TransformConstantExpr(E);
17474       RemoveImmediateInvocation(E);
17475       return Base::TransformExpr(E->getSubExpr());
17476     }
17477     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17478     /// we need to remove its DeclRefExpr from the DRSet.
17479     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17480       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17481       return Base::TransformCXXOperatorCallExpr(E);
17482     }
17483     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
17484     /// here.
17485     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17486       if (!Init)
17487         return Init;
17488       /// ConstantExpr are the first layer of implicit node to be removed so if
17489       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17490       if (auto *CE = dyn_cast<ConstantExpr>(Init))
17491         if (CE->isImmediateInvocation())
17492           RemoveImmediateInvocation(CE);
17493       return Base::TransformInitializer(Init, NotCopyInit);
17494     }
17495     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17496       DRSet.erase(E);
17497       return E;
17498     }
17499     bool AlwaysRebuild() { return false; }
17500     bool ReplacingOriginal() { return true; }
17501     bool AllowSkippingCXXConstructExpr() {
17502       bool Res = AllowSkippingFirstCXXConstructExpr;
17503       AllowSkippingFirstCXXConstructExpr = true;
17504       return Res;
17505     }
17506     bool AllowSkippingFirstCXXConstructExpr = true;
17507   } Transformer(SemaRef, Rec.ReferenceToConsteval,
17508                 Rec.ImmediateInvocationCandidates, It);
17509 
17510   /// CXXConstructExpr with a single argument are getting skipped by
17511   /// TreeTransform in some situtation because they could be implicit. This
17512   /// can only occur for the top-level CXXConstructExpr because it is used
17513   /// nowhere in the expression being transformed therefore will not be rebuilt.
17514   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17515   /// skipping the first CXXConstructExpr.
17516   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17517     Transformer.AllowSkippingFirstCXXConstructExpr = false;
17518 
17519   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17520   assert(Res.isUsable());
17521   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
17522   It->getPointer()->setSubExpr(Res.get());
17523 }
17524 
17525 static void
17526 HandleImmediateInvocations(Sema &SemaRef,
17527                            Sema::ExpressionEvaluationContextRecord &Rec) {
17528   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17529        Rec.ReferenceToConsteval.size() == 0) ||
17530       SemaRef.RebuildingImmediateInvocation)
17531     return;
17532 
17533   /// When we have more then 1 ImmediateInvocationCandidates we need to check
17534   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
17535   /// need to remove ReferenceToConsteval in the immediate invocation.
17536   if (Rec.ImmediateInvocationCandidates.size() > 1) {
17537 
17538     /// Prevent sema calls during the tree transform from adding pointers that
17539     /// are already in the sets.
17540     llvm::SaveAndRestore<bool> DisableIITracking(
17541         SemaRef.RebuildingImmediateInvocation, true);
17542 
17543     /// Prevent diagnostic during tree transfrom as they are duplicates
17544     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
17545 
17546     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17547          It != Rec.ImmediateInvocationCandidates.rend(); It++)
17548       if (!It->getInt())
17549         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
17550   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17551              Rec.ReferenceToConsteval.size()) {
17552     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17553       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17554       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17555       bool VisitDeclRefExpr(DeclRefExpr *E) {
17556         DRSet.erase(E);
17557         return DRSet.size();
17558       }
17559     } Visitor(Rec.ReferenceToConsteval);
17560     Visitor.TraverseStmt(
17561         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17562   }
17563   for (auto CE : Rec.ImmediateInvocationCandidates)
17564     if (!CE.getInt())
17565       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
17566   for (auto DR : Rec.ReferenceToConsteval) {
17567     auto *FD = cast<FunctionDecl>(DR->getDecl());
17568     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17569         << FD;
17570     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
17571   }
17572 }
17573 
17574 void Sema::PopExpressionEvaluationContext() {
17575   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
17576   unsigned NumTypos = Rec.NumTypos;
17577 
17578   if (!Rec.Lambdas.empty()) {
17579     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
17580     if (!getLangOpts().CPlusPlus20 &&
17581         (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17582          Rec.isUnevaluated() ||
17583          (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
17584       unsigned D;
17585       if (Rec.isUnevaluated()) {
17586         // C++11 [expr.prim.lambda]p2:
17587         //   A lambda-expression shall not appear in an unevaluated operand
17588         //   (Clause 5).
17589         D = diag::err_lambda_unevaluated_operand;
17590       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17591         // C++1y [expr.const]p2:
17592         //   A conditional-expression e is a core constant expression unless the
17593         //   evaluation of e, following the rules of the abstract machine, would
17594         //   evaluate [...] a lambda-expression.
17595         D = diag::err_lambda_in_constant_expression;
17596       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17597         // C++17 [expr.prim.lamda]p2:
17598         // A lambda-expression shall not appear [...] in a template-argument.
17599         D = diag::err_lambda_in_invalid_context;
17600       } else
17601         llvm_unreachable("Couldn't infer lambda error message.");
17602 
17603       for (const auto *L : Rec.Lambdas)
17604         Diag(L->getBeginLoc(), D);
17605     }
17606   }
17607 
17608   WarnOnPendingNoDerefs(Rec);
17609   HandleImmediateInvocations(*this, Rec);
17610 
17611   // Warn on any volatile-qualified simple-assignments that are not discarded-
17612   // value expressions nor unevaluated operands (those cases get removed from
17613   // this list by CheckUnusedVolatileAssignment).
17614   for (auto *BO : Rec.VolatileAssignmentLHSs)
17615     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17616         << BO->getType();
17617 
17618   // When are coming out of an unevaluated context, clear out any
17619   // temporaries that we may have created as part of the evaluation of
17620   // the expression in that context: they aren't relevant because they
17621   // will never be constructed.
17622   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17623     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
17624                              ExprCleanupObjects.end());
17625     Cleanup = Rec.ParentCleanup;
17626     CleanupVarDeclMarking();
17627     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
17628   // Otherwise, merge the contexts together.
17629   } else {
17630     Cleanup.mergeFrom(Rec.ParentCleanup);
17631     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17632                             Rec.SavedMaybeODRUseExprs.end());
17633   }
17634 
17635   // Pop the current expression evaluation context off the stack.
17636   ExprEvalContexts.pop_back();
17637 
17638   // The global expression evaluation context record is never popped.
17639   ExprEvalContexts.back().NumTypos += NumTypos;
17640 }
17641 
17642 void Sema::DiscardCleanupsInEvaluationContext() {
17643   ExprCleanupObjects.erase(
17644          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17645          ExprCleanupObjects.end());
17646   Cleanup.reset();
17647   MaybeODRUseExprs.clear();
17648 }
17649 
17650 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
17651   ExprResult Result = CheckPlaceholderExpr(E);
17652   if (Result.isInvalid())
17653     return ExprError();
17654   E = Result.get();
17655   if (!E->getType()->isVariablyModifiedType())
17656     return E;
17657   return TransformToPotentiallyEvaluated(E);
17658 }
17659 
17660 /// Are we in a context that is potentially constant evaluated per C++20
17661 /// [expr.const]p12?
17662 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
17663   /// C++2a [expr.const]p12:
17664   //   An expression or conversion is potentially constant evaluated if it is
17665   switch (SemaRef.ExprEvalContexts.back().Context) {
17666     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17667     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17668 
17669       // -- a manifestly constant-evaluated expression,
17670     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17671     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17672     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17673       // -- a potentially-evaluated expression,
17674     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17675       // -- an immediate subexpression of a braced-init-list,
17676 
17677       // -- [FIXME] an expression of the form & cast-expression that occurs
17678       //    within a templated entity
17679       // -- a subexpression of one of the above that is not a subexpression of
17680       // a nested unevaluated operand.
17681       return true;
17682 
17683     case Sema::ExpressionEvaluationContext::Unevaluated:
17684     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17685       // Expressions in this context are never evaluated.
17686       return false;
17687   }
17688   llvm_unreachable("Invalid context");
17689 }
17690 
17691 /// Return true if this function has a calling convention that requires mangling
17692 /// in the size of the parameter pack.
17693 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
17694   // These manglings don't do anything on non-Windows or non-x86 platforms, so
17695   // we don't need parameter type sizes.
17696   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17697   if (!TT.isOSWindows() || !TT.isX86())
17698     return false;
17699 
17700   // If this is C++ and this isn't an extern "C" function, parameters do not
17701   // need to be complete. In this case, C++ mangling will apply, which doesn't
17702   // use the size of the parameters.
17703   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17704     return false;
17705 
17706   // Stdcall, fastcall, and vectorcall need this special treatment.
17707   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17708   switch (CC) {
17709   case CC_X86StdCall:
17710   case CC_X86FastCall:
17711   case CC_X86VectorCall:
17712     return true;
17713   default:
17714     break;
17715   }
17716   return false;
17717 }
17718 
17719 /// Require that all of the parameter types of function be complete. Normally,
17720 /// parameter types are only required to be complete when a function is called
17721 /// or defined, but to mangle functions with certain calling conventions, the
17722 /// mangler needs to know the size of the parameter list. In this situation,
17723 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17724 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17725 /// result in a linker error. Clang doesn't implement this behavior, and instead
17726 /// attempts to error at compile time.
17727 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
17728                                                   SourceLocation Loc) {
17729   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17730     FunctionDecl *FD;
17731     ParmVarDecl *Param;
17732 
17733   public:
17734     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17735         : FD(FD), Param(Param) {}
17736 
17737     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17738       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17739       StringRef CCName;
17740       switch (CC) {
17741       case CC_X86StdCall:
17742         CCName = "stdcall";
17743         break;
17744       case CC_X86FastCall:
17745         CCName = "fastcall";
17746         break;
17747       case CC_X86VectorCall:
17748         CCName = "vectorcall";
17749         break;
17750       default:
17751         llvm_unreachable("CC does not need mangling");
17752       }
17753 
17754       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17755           << Param->getDeclName() << FD->getDeclName() << CCName;
17756     }
17757   };
17758 
17759   for (ParmVarDecl *Param : FD->parameters()) {
17760     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17761     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17762   }
17763 }
17764 
17765 namespace {
17766 enum class OdrUseContext {
17767   /// Declarations in this context are not odr-used.
17768   None,
17769   /// Declarations in this context are formally odr-used, but this is a
17770   /// dependent context.
17771   Dependent,
17772   /// Declarations in this context are odr-used but not actually used (yet).
17773   FormallyOdrUsed,
17774   /// Declarations in this context are used.
17775   Used
17776 };
17777 }
17778 
17779 /// Are we within a context in which references to resolved functions or to
17780 /// variables result in odr-use?
17781 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17782   OdrUseContext Result;
17783 
17784   switch (SemaRef.ExprEvalContexts.back().Context) {
17785     case Sema::ExpressionEvaluationContext::Unevaluated:
17786     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17787     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17788       return OdrUseContext::None;
17789 
17790     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17791     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17792     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17793       Result = OdrUseContext::Used;
17794       break;
17795 
17796     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17797       Result = OdrUseContext::FormallyOdrUsed;
17798       break;
17799 
17800     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17801       // A default argument formally results in odr-use, but doesn't actually
17802       // result in a use in any real sense until it itself is used.
17803       Result = OdrUseContext::FormallyOdrUsed;
17804       break;
17805   }
17806 
17807   if (SemaRef.CurContext->isDependentContext())
17808     return OdrUseContext::Dependent;
17809 
17810   return Result;
17811 }
17812 
17813 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17814   if (!Func->isConstexpr())
17815     return false;
17816 
17817   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17818     return true;
17819   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17820   return CCD && CCD->getInheritedConstructor();
17821 }
17822 
17823 /// Mark a function referenced, and check whether it is odr-used
17824 /// (C++ [basic.def.odr]p2, C99 6.9p3)
17825 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17826                                   bool MightBeOdrUse) {
17827   assert(Func && "No function?");
17828 
17829   Func->setReferenced();
17830 
17831   // Recursive functions aren't really used until they're used from some other
17832   // context.
17833   bool IsRecursiveCall = CurContext == Func;
17834 
17835   // C++11 [basic.def.odr]p3:
17836   //   A function whose name appears as a potentially-evaluated expression is
17837   //   odr-used if it is the unique lookup result or the selected member of a
17838   //   set of overloaded functions [...].
17839   //
17840   // We (incorrectly) mark overload resolution as an unevaluated context, so we
17841   // can just check that here.
17842   OdrUseContext OdrUse =
17843       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17844   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17845     OdrUse = OdrUseContext::FormallyOdrUsed;
17846 
17847   // Trivial default constructors and destructors are never actually used.
17848   // FIXME: What about other special members?
17849   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17850       OdrUse == OdrUseContext::Used) {
17851     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17852       if (Constructor->isDefaultConstructor())
17853         OdrUse = OdrUseContext::FormallyOdrUsed;
17854     if (isa<CXXDestructorDecl>(Func))
17855       OdrUse = OdrUseContext::FormallyOdrUsed;
17856   }
17857 
17858   // C++20 [expr.const]p12:
17859   //   A function [...] is needed for constant evaluation if it is [...] a
17860   //   constexpr function that is named by an expression that is potentially
17861   //   constant evaluated
17862   bool NeededForConstantEvaluation =
17863       isPotentiallyConstantEvaluatedContext(*this) &&
17864       isImplicitlyDefinableConstexprFunction(Func);
17865 
17866   // Determine whether we require a function definition to exist, per
17867   // C++11 [temp.inst]p3:
17868   //   Unless a function template specialization has been explicitly
17869   //   instantiated or explicitly specialized, the function template
17870   //   specialization is implicitly instantiated when the specialization is
17871   //   referenced in a context that requires a function definition to exist.
17872   // C++20 [temp.inst]p7:
17873   //   The existence of a definition of a [...] function is considered to
17874   //   affect the semantics of the program if the [...] function is needed for
17875   //   constant evaluation by an expression
17876   // C++20 [basic.def.odr]p10:
17877   //   Every program shall contain exactly one definition of every non-inline
17878   //   function or variable that is odr-used in that program outside of a
17879   //   discarded statement
17880   // C++20 [special]p1:
17881   //   The implementation will implicitly define [defaulted special members]
17882   //   if they are odr-used or needed for constant evaluation.
17883   //
17884   // Note that we skip the implicit instantiation of templates that are only
17885   // used in unused default arguments or by recursive calls to themselves.
17886   // This is formally non-conforming, but seems reasonable in practice.
17887   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
17888                                              NeededForConstantEvaluation);
17889 
17890   // C++14 [temp.expl.spec]p6:
17891   //   If a template [...] is explicitly specialized then that specialization
17892   //   shall be declared before the first use of that specialization that would
17893   //   cause an implicit instantiation to take place, in every translation unit
17894   //   in which such a use occurs
17895   if (NeedDefinition &&
17896       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17897        Func->getMemberSpecializationInfo()))
17898     checkSpecializationVisibility(Loc, Func);
17899 
17900   if (getLangOpts().CUDA)
17901     CheckCUDACall(Loc, Func);
17902 
17903   if (getLangOpts().SYCLIsDevice)
17904     checkSYCLDeviceFunction(Loc, Func);
17905 
17906   // If we need a definition, try to create one.
17907   if (NeedDefinition && !Func->getBody()) {
17908     runWithSufficientStackSpace(Loc, [&] {
17909       if (CXXConstructorDecl *Constructor =
17910               dyn_cast<CXXConstructorDecl>(Func)) {
17911         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17912         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17913           if (Constructor->isDefaultConstructor()) {
17914             if (Constructor->isTrivial() &&
17915                 !Constructor->hasAttr<DLLExportAttr>())
17916               return;
17917             DefineImplicitDefaultConstructor(Loc, Constructor);
17918           } else if (Constructor->isCopyConstructor()) {
17919             DefineImplicitCopyConstructor(Loc, Constructor);
17920           } else if (Constructor->isMoveConstructor()) {
17921             DefineImplicitMoveConstructor(Loc, Constructor);
17922           }
17923         } else if (Constructor->getInheritedConstructor()) {
17924           DefineInheritingConstructor(Loc, Constructor);
17925         }
17926       } else if (CXXDestructorDecl *Destructor =
17927                      dyn_cast<CXXDestructorDecl>(Func)) {
17928         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17929         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17930           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17931             return;
17932           DefineImplicitDestructor(Loc, Destructor);
17933         }
17934         if (Destructor->isVirtual() && getLangOpts().AppleKext)
17935           MarkVTableUsed(Loc, Destructor->getParent());
17936       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17937         if (MethodDecl->isOverloadedOperator() &&
17938             MethodDecl->getOverloadedOperator() == OO_Equal) {
17939           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17940           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17941             if (MethodDecl->isCopyAssignmentOperator())
17942               DefineImplicitCopyAssignment(Loc, MethodDecl);
17943             else if (MethodDecl->isMoveAssignmentOperator())
17944               DefineImplicitMoveAssignment(Loc, MethodDecl);
17945           }
17946         } else if (isa<CXXConversionDecl>(MethodDecl) &&
17947                    MethodDecl->getParent()->isLambda()) {
17948           CXXConversionDecl *Conversion =
17949               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17950           if (Conversion->isLambdaToBlockPointerConversion())
17951             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17952           else
17953             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17954         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17955           MarkVTableUsed(Loc, MethodDecl->getParent());
17956       }
17957 
17958       if (Func->isDefaulted() && !Func->isDeleted()) {
17959         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17960         if (DCK != DefaultedComparisonKind::None)
17961           DefineDefaultedComparison(Loc, Func, DCK);
17962       }
17963 
17964       // Implicit instantiation of function templates and member functions of
17965       // class templates.
17966       if (Func->isImplicitlyInstantiable()) {
17967         TemplateSpecializationKind TSK =
17968             Func->getTemplateSpecializationKindForInstantiation();
17969         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17970         bool FirstInstantiation = PointOfInstantiation.isInvalid();
17971         if (FirstInstantiation) {
17972           PointOfInstantiation = Loc;
17973           if (auto *MSI = Func->getMemberSpecializationInfo())
17974             MSI->setPointOfInstantiation(Loc);
17975             // FIXME: Notify listener.
17976           else
17977             Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17978         } else if (TSK != TSK_ImplicitInstantiation) {
17979           // Use the point of use as the point of instantiation, instead of the
17980           // point of explicit instantiation (which we track as the actual point
17981           // of instantiation). This gives better backtraces in diagnostics.
17982           PointOfInstantiation = Loc;
17983         }
17984 
17985         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17986             Func->isConstexpr()) {
17987           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17988               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17989               CodeSynthesisContexts.size())
17990             PendingLocalImplicitInstantiations.push_back(
17991                 std::make_pair(Func, PointOfInstantiation));
17992           else if (Func->isConstexpr())
17993             // Do not defer instantiations of constexpr functions, to avoid the
17994             // expression evaluator needing to call back into Sema if it sees a
17995             // call to such a function.
17996             InstantiateFunctionDefinition(PointOfInstantiation, Func);
17997           else {
17998             Func->setInstantiationIsPending(true);
17999             PendingInstantiations.push_back(
18000                 std::make_pair(Func, PointOfInstantiation));
18001             // Notify the consumer that a function was implicitly instantiated.
18002             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
18003           }
18004         }
18005       } else {
18006         // Walk redefinitions, as some of them may be instantiable.
18007         for (auto i : Func->redecls()) {
18008           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18009             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18010         }
18011       }
18012     });
18013   }
18014 
18015   // C++14 [except.spec]p17:
18016   //   An exception-specification is considered to be needed when:
18017   //   - the function is odr-used or, if it appears in an unevaluated operand,
18018   //     would be odr-used if the expression were potentially-evaluated;
18019   //
18020   // Note, we do this even if MightBeOdrUse is false. That indicates that the
18021   // function is a pure virtual function we're calling, and in that case the
18022   // function was selected by overload resolution and we need to resolve its
18023   // exception specification for a different reason.
18024   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18025   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
18026     ResolveExceptionSpec(Loc, FPT);
18027 
18028   // If this is the first "real" use, act on that.
18029   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18030     // Keep track of used but undefined functions.
18031     if (!Func->isDefined()) {
18032       if (mightHaveNonExternalLinkage(Func))
18033         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18034       else if (Func->getMostRecentDecl()->isInlined() &&
18035                !LangOpts.GNUInline &&
18036                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18037         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18038       else if (isExternalWithNoLinkageType(Func))
18039         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18040     }
18041 
18042     // Some x86 Windows calling conventions mangle the size of the parameter
18043     // pack into the name. Computing the size of the parameters requires the
18044     // parameter types to be complete. Check that now.
18045     if (funcHasParameterSizeMangling(*this, Func))
18046       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
18047 
18048     // In the MS C++ ABI, the compiler emits destructor variants where they are
18049     // used. If the destructor is used here but defined elsewhere, mark the
18050     // virtual base destructors referenced. If those virtual base destructors
18051     // are inline, this will ensure they are defined when emitting the complete
18052     // destructor variant. This checking may be redundant if the destructor is
18053     // provided later in this TU.
18054     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18055       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18056         CXXRecordDecl *Parent = Dtor->getParent();
18057         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18058           CheckCompleteDestructorVariant(Loc, Dtor);
18059       }
18060     }
18061 
18062     Func->markUsed(Context);
18063   }
18064 }
18065 
18066 /// Directly mark a variable odr-used. Given a choice, prefer to use
18067 /// MarkVariableReferenced since it does additional checks and then
18068 /// calls MarkVarDeclODRUsed.
18069 /// If the variable must be captured:
18070 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18071 ///  - else capture it in the DeclContext that maps to the
18072 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18073 static void
18074 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
18075                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18076   // Keep track of used but undefined variables.
18077   // FIXME: We shouldn't suppress this warning for static data members.
18078   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
18079       (!Var->isExternallyVisible() || Var->isInline() ||
18080        SemaRef.isExternalWithNoLinkageType(Var)) &&
18081       !(Var->isStaticDataMember() && Var->hasInit())) {
18082     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
18083     if (old.isInvalid())
18084       old = Loc;
18085   }
18086   QualType CaptureType, DeclRefType;
18087   if (SemaRef.LangOpts.OpenMP)
18088     SemaRef.tryCaptureOpenMPLambdas(Var);
18089   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
18090     /*EllipsisLoc*/ SourceLocation(),
18091     /*BuildAndDiagnose*/ true,
18092     CaptureType, DeclRefType,
18093     FunctionScopeIndexToStopAt);
18094 
18095   if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18096     auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18097     auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
18098     auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
18099     if (VarTarget == Sema::CVT_Host &&
18100         (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
18101          UserTarget == Sema::CFT_Global)) {
18102       // Diagnose ODR-use of host global variables in device functions.
18103       // Reference of device global variables in host functions is allowed
18104       // through shadow variables therefore it is not diagnosed.
18105       if (SemaRef.LangOpts.CUDAIsDevice) {
18106         SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18107             << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
18108         SemaRef.targetDiag(Var->getLocation(),
18109                            Var->getType().isConstQualified()
18110                                ? diag::note_cuda_const_var_unpromoted
18111                                : diag::note_cuda_host_var);
18112       }
18113     } else if (VarTarget == Sema::CVT_Device &&
18114                (UserTarget == Sema::CFT_Host ||
18115                 UserTarget == Sema::CFT_HostDevice)) {
18116       // Record a CUDA/HIP device side variable if it is ODR-used
18117       // by host code. This is done conservatively, when the variable is
18118       // referenced in any of the following contexts:
18119       //   - a non-function context
18120       //   - a host function
18121       //   - a host device function
18122       // This makes the ODR-use of the device side variable by host code to
18123       // be visible in the device compilation for the compiler to be able to
18124       // emit template variables instantiated by host code only and to
18125       // externalize the static device side variable ODR-used by host code.
18126       if (!Var->hasExternalStorage())
18127         SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
18128       else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
18129         SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
18130     }
18131   }
18132 
18133   Var->markUsed(SemaRef.Context);
18134 }
18135 
18136 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
18137                                              SourceLocation Loc,
18138                                              unsigned CapturingScopeIndex) {
18139   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18140 }
18141 
18142 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
18143                                                ValueDecl *var) {
18144   DeclContext *VarDC = var->getDeclContext();
18145 
18146   //  If the parameter still belongs to the translation unit, then
18147   //  we're actually just using one parameter in the declaration of
18148   //  the next.
18149   if (isa<ParmVarDecl>(var) &&
18150       isa<TranslationUnitDecl>(VarDC))
18151     return;
18152 
18153   // For C code, don't diagnose about capture if we're not actually in code
18154   // right now; it's impossible to write a non-constant expression outside of
18155   // function context, so we'll get other (more useful) diagnostics later.
18156   //
18157   // For C++, things get a bit more nasty... it would be nice to suppress this
18158   // diagnostic for certain cases like using a local variable in an array bound
18159   // for a member of a local class, but the correct predicate is not obvious.
18160   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18161     return;
18162 
18163   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18164   unsigned ContextKind = 3; // unknown
18165   if (isa<CXXMethodDecl>(VarDC) &&
18166       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18167     ContextKind = 2;
18168   } else if (isa<FunctionDecl>(VarDC)) {
18169     ContextKind = 0;
18170   } else if (isa<BlockDecl>(VarDC)) {
18171     ContextKind = 1;
18172   }
18173 
18174   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18175     << var << ValueKind << ContextKind << VarDC;
18176   S.Diag(var->getLocation(), diag::note_entity_declared_at)
18177       << var;
18178 
18179   // FIXME: Add additional diagnostic info about class etc. which prevents
18180   // capture.
18181 }
18182 
18183 
18184 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
18185                                       bool &SubCapturesAreNested,
18186                                       QualType &CaptureType,
18187                                       QualType &DeclRefType) {
18188    // Check whether we've already captured it.
18189   if (CSI->CaptureMap.count(Var)) {
18190     // If we found a capture, any subcaptures are nested.
18191     SubCapturesAreNested = true;
18192 
18193     // Retrieve the capture type for this variable.
18194     CaptureType = CSI->getCapture(Var).getCaptureType();
18195 
18196     // Compute the type of an expression that refers to this variable.
18197     DeclRefType = CaptureType.getNonReferenceType();
18198 
18199     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18200     // are mutable in the sense that user can change their value - they are
18201     // private instances of the captured declarations.
18202     const Capture &Cap = CSI->getCapture(Var);
18203     if (Cap.isCopyCapture() &&
18204         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
18205         !(isa<CapturedRegionScopeInfo>(CSI) &&
18206           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18207       DeclRefType.addConst();
18208     return true;
18209   }
18210   return false;
18211 }
18212 
18213 // Only block literals, captured statements, and lambda expressions can
18214 // capture; other scopes don't work.
18215 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
18216                                  SourceLocation Loc,
18217                                  const bool Diagnose, Sema &S) {
18218   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18219     return getLambdaAwareParentOfDeclContext(DC);
18220   else if (Var->hasLocalStorage()) {
18221     if (Diagnose)
18222        diagnoseUncapturableValueReference(S, Loc, Var);
18223   }
18224   return nullptr;
18225 }
18226 
18227 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18228 // certain types of variables (unnamed, variably modified types etc.)
18229 // so check for eligibility.
18230 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
18231                                  SourceLocation Loc,
18232                                  const bool Diagnose, Sema &S) {
18233 
18234   bool IsBlock = isa<BlockScopeInfo>(CSI);
18235   bool IsLambda = isa<LambdaScopeInfo>(CSI);
18236 
18237   // Lambdas are not allowed to capture unnamed variables
18238   // (e.g. anonymous unions).
18239   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18240   // assuming that's the intent.
18241   if (IsLambda && !Var->getDeclName()) {
18242     if (Diagnose) {
18243       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18244       S.Diag(Var->getLocation(), diag::note_declared_at);
18245     }
18246     return false;
18247   }
18248 
18249   // Prohibit variably-modified types in blocks; they're difficult to deal with.
18250   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18251     if (Diagnose) {
18252       S.Diag(Loc, diag::err_ref_vm_type);
18253       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18254     }
18255     return false;
18256   }
18257   // Prohibit structs with flexible array members too.
18258   // We cannot capture what is in the tail end of the struct.
18259   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18260     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18261       if (Diagnose) {
18262         if (IsBlock)
18263           S.Diag(Loc, diag::err_ref_flexarray_type);
18264         else
18265           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18266         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18267       }
18268       return false;
18269     }
18270   }
18271   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18272   // Lambdas and captured statements are not allowed to capture __block
18273   // variables; they don't support the expected semantics.
18274   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18275     if (Diagnose) {
18276       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18277       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18278     }
18279     return false;
18280   }
18281   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18282   if (S.getLangOpts().OpenCL && IsBlock &&
18283       Var->getType()->isBlockPointerType()) {
18284     if (Diagnose)
18285       S.Diag(Loc, diag::err_opencl_block_ref_block);
18286     return false;
18287   }
18288 
18289   return true;
18290 }
18291 
18292 // Returns true if the capture by block was successful.
18293 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
18294                                  SourceLocation Loc,
18295                                  const bool BuildAndDiagnose,
18296                                  QualType &CaptureType,
18297                                  QualType &DeclRefType,
18298                                  const bool Nested,
18299                                  Sema &S, bool Invalid) {
18300   bool ByRef = false;
18301 
18302   // Blocks are not allowed to capture arrays, excepting OpenCL.
18303   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18304   // (decayed to pointers).
18305   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18306     if (BuildAndDiagnose) {
18307       S.Diag(Loc, diag::err_ref_array_type);
18308       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18309       Invalid = true;
18310     } else {
18311       return false;
18312     }
18313   }
18314 
18315   // Forbid the block-capture of autoreleasing variables.
18316   if (!Invalid &&
18317       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18318     if (BuildAndDiagnose) {
18319       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18320         << /*block*/ 0;
18321       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18322       Invalid = true;
18323     } else {
18324       return false;
18325     }
18326   }
18327 
18328   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18329   if (const auto *PT = CaptureType->getAs<PointerType>()) {
18330     QualType PointeeTy = PT->getPointeeType();
18331 
18332     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18333         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
18334         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18335       if (BuildAndDiagnose) {
18336         SourceLocation VarLoc = Var->getLocation();
18337         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18338         S.Diag(VarLoc, diag::note_declare_parameter_strong);
18339       }
18340     }
18341   }
18342 
18343   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18344   if (HasBlocksAttr || CaptureType->isReferenceType() ||
18345       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
18346     // Block capture by reference does not change the capture or
18347     // declaration reference types.
18348     ByRef = true;
18349   } else {
18350     // Block capture by copy introduces 'const'.
18351     CaptureType = CaptureType.getNonReferenceType().withConst();
18352     DeclRefType = CaptureType;
18353   }
18354 
18355   // Actually capture the variable.
18356   if (BuildAndDiagnose)
18357     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18358                     CaptureType, Invalid);
18359 
18360   return !Invalid;
18361 }
18362 
18363 
18364 /// Capture the given variable in the captured region.
18365 static bool captureInCapturedRegion(
18366     CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
18367     const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18368     const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18369     bool IsTopScope, Sema &S, bool Invalid) {
18370   // By default, capture variables by reference.
18371   bool ByRef = true;
18372   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18373     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18374   } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18375     // Using an LValue reference type is consistent with Lambdas (see below).
18376     if (S.isOpenMPCapturedDecl(Var)) {
18377       bool HasConst = DeclRefType.isConstQualified();
18378       DeclRefType = DeclRefType.getUnqualifiedType();
18379       // Don't lose diagnostics about assignments to const.
18380       if (HasConst)
18381         DeclRefType.addConst();
18382     }
18383     // Do not capture firstprivates in tasks.
18384     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
18385         OMPC_unknown)
18386       return true;
18387     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18388                                     RSI->OpenMPCaptureLevel);
18389   }
18390 
18391   if (ByRef)
18392     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18393   else
18394     CaptureType = DeclRefType;
18395 
18396   // Actually capture the variable.
18397   if (BuildAndDiagnose)
18398     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18399                     Loc, SourceLocation(), CaptureType, Invalid);
18400 
18401   return !Invalid;
18402 }
18403 
18404 /// Capture the given variable in the lambda.
18405 static bool captureInLambda(LambdaScopeInfo *LSI,
18406                             VarDecl *Var,
18407                             SourceLocation Loc,
18408                             const bool BuildAndDiagnose,
18409                             QualType &CaptureType,
18410                             QualType &DeclRefType,
18411                             const bool RefersToCapturedVariable,
18412                             const Sema::TryCaptureKind Kind,
18413                             SourceLocation EllipsisLoc,
18414                             const bool IsTopScope,
18415                             Sema &S, bool Invalid) {
18416   // Determine whether we are capturing by reference or by value.
18417   bool ByRef = false;
18418   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18419     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18420   } else {
18421     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18422   }
18423 
18424   // Compute the type of the field that will capture this variable.
18425   if (ByRef) {
18426     // C++11 [expr.prim.lambda]p15:
18427     //   An entity is captured by reference if it is implicitly or
18428     //   explicitly captured but not captured by copy. It is
18429     //   unspecified whether additional unnamed non-static data
18430     //   members are declared in the closure type for entities
18431     //   captured by reference.
18432     //
18433     // FIXME: It is not clear whether we want to build an lvalue reference
18434     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18435     // to do the former, while EDG does the latter. Core issue 1249 will
18436     // clarify, but for now we follow GCC because it's a more permissive and
18437     // easily defensible position.
18438     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18439   } else {
18440     // C++11 [expr.prim.lambda]p14:
18441     //   For each entity captured by copy, an unnamed non-static
18442     //   data member is declared in the closure type. The
18443     //   declaration order of these members is unspecified. The type
18444     //   of such a data member is the type of the corresponding
18445     //   captured entity if the entity is not a reference to an
18446     //   object, or the referenced type otherwise. [Note: If the
18447     //   captured entity is a reference to a function, the
18448     //   corresponding data member is also a reference to a
18449     //   function. - end note ]
18450     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18451       if (!RefType->getPointeeType()->isFunctionType())
18452         CaptureType = RefType->getPointeeType();
18453     }
18454 
18455     // Forbid the lambda copy-capture of autoreleasing variables.
18456     if (!Invalid &&
18457         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18458       if (BuildAndDiagnose) {
18459         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18460         S.Diag(Var->getLocation(), diag::note_previous_decl)
18461           << Var->getDeclName();
18462         Invalid = true;
18463       } else {
18464         return false;
18465       }
18466     }
18467 
18468     // Make sure that by-copy captures are of a complete and non-abstract type.
18469     if (!Invalid && BuildAndDiagnose) {
18470       if (!CaptureType->isDependentType() &&
18471           S.RequireCompleteSizedType(
18472               Loc, CaptureType,
18473               diag::err_capture_of_incomplete_or_sizeless_type,
18474               Var->getDeclName()))
18475         Invalid = true;
18476       else if (S.RequireNonAbstractType(Loc, CaptureType,
18477                                         diag::err_capture_of_abstract_type))
18478         Invalid = true;
18479     }
18480   }
18481 
18482   // Compute the type of a reference to this captured variable.
18483   if (ByRef)
18484     DeclRefType = CaptureType.getNonReferenceType();
18485   else {
18486     // C++ [expr.prim.lambda]p5:
18487     //   The closure type for a lambda-expression has a public inline
18488     //   function call operator [...]. This function call operator is
18489     //   declared const (9.3.1) if and only if the lambda-expression's
18490     //   parameter-declaration-clause is not followed by mutable.
18491     DeclRefType = CaptureType.getNonReferenceType();
18492     if (!LSI->Mutable && !CaptureType->isReferenceType())
18493       DeclRefType.addConst();
18494   }
18495 
18496   // Add the capture.
18497   if (BuildAndDiagnose)
18498     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18499                     Loc, EllipsisLoc, CaptureType, Invalid);
18500 
18501   return !Invalid;
18502 }
18503 
18504 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
18505   // Offer a Copy fix even if the type is dependent.
18506   if (Var->getType()->isDependentType())
18507     return true;
18508   QualType T = Var->getType().getNonReferenceType();
18509   if (T.isTriviallyCopyableType(Context))
18510     return true;
18511   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18512 
18513     if (!(RD = RD->getDefinition()))
18514       return false;
18515     if (RD->hasSimpleCopyConstructor())
18516       return true;
18517     if (RD->hasUserDeclaredCopyConstructor())
18518       for (CXXConstructorDecl *Ctor : RD->ctors())
18519         if (Ctor->isCopyConstructor())
18520           return !Ctor->isDeleted();
18521   }
18522   return false;
18523 }
18524 
18525 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18526 /// default capture. Fixes may be omitted if they aren't allowed by the
18527 /// standard, for example we can't emit a default copy capture fix-it if we
18528 /// already explicitly copy capture capture another variable.
18529 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
18530                                     VarDecl *Var) {
18531   assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
18532   // Don't offer Capture by copy of default capture by copy fixes if Var is
18533   // known not to be copy constructible.
18534   bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18535 
18536   SmallString<32> FixBuffer;
18537   StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18538   if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18539     SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18540     if (ShouldOfferCopyFix) {
18541       // Offer fixes to insert an explicit capture for the variable.
18542       // [] -> [VarName]
18543       // [OtherCapture] -> [OtherCapture, VarName]
18544       FixBuffer.assign({Separator, Var->getName()});
18545       Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18546           << Var << /*value*/ 0
18547           << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18548     }
18549     // As above but capture by reference.
18550     FixBuffer.assign({Separator, "&", Var->getName()});
18551     Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18552         << Var << /*reference*/ 1
18553         << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18554   }
18555 
18556   // Only try to offer default capture if there are no captures excluding this
18557   // and init captures.
18558   // [this]: OK.
18559   // [X = Y]: OK.
18560   // [&A, &B]: Don't offer.
18561   // [A, B]: Don't offer.
18562   if (llvm::any_of(LSI->Captures, [](Capture &C) {
18563         return !C.isThisCapture() && !C.isInitCapture();
18564       }))
18565     return;
18566 
18567   // The default capture specifiers, '=' or '&', must appear first in the
18568   // capture body.
18569   SourceLocation DefaultInsertLoc =
18570       LSI->IntroducerRange.getBegin().getLocWithOffset(1);
18571 
18572   if (ShouldOfferCopyFix) {
18573     bool CanDefaultCopyCapture = true;
18574     // [=, *this] OK since c++17
18575     // [=, this] OK since c++20
18576     if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18577       CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18578                                   ? LSI->getCXXThisCapture().isCopyCapture()
18579                                   : false;
18580     // We can't use default capture by copy if any captures already specified
18581     // capture by copy.
18582     if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18583           return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18584         })) {
18585       FixBuffer.assign({"=", Separator});
18586       Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18587           << /*value*/ 0
18588           << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18589     }
18590   }
18591 
18592   // We can't use default capture by reference if any captures already specified
18593   // capture by reference.
18594   if (llvm::none_of(LSI->Captures, [](Capture &C) {
18595         return !C.isInitCapture() && C.isReferenceCapture() &&
18596                !C.isThisCapture();
18597       })) {
18598     FixBuffer.assign({"&", Separator});
18599     Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18600         << /*reference*/ 1
18601         << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18602   }
18603 }
18604 
18605 bool Sema::tryCaptureVariable(
18606     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18607     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18608     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18609   // An init-capture is notionally from the context surrounding its
18610   // declaration, but its parent DC is the lambda class.
18611   DeclContext *VarDC = Var->getDeclContext();
18612   if (Var->isInitCapture())
18613     VarDC = VarDC->getParent();
18614 
18615   DeclContext *DC = CurContext;
18616   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18617       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18618   // We need to sync up the Declaration Context with the
18619   // FunctionScopeIndexToStopAt
18620   if (FunctionScopeIndexToStopAt) {
18621     unsigned FSIndex = FunctionScopes.size() - 1;
18622     while (FSIndex != MaxFunctionScopesIndex) {
18623       DC = getLambdaAwareParentOfDeclContext(DC);
18624       --FSIndex;
18625     }
18626   }
18627 
18628 
18629   // If the variable is declared in the current context, there is no need to
18630   // capture it.
18631   if (VarDC == DC) return true;
18632 
18633   // Capture global variables if it is required to use private copy of this
18634   // variable.
18635   bool IsGlobal = !Var->hasLocalStorage();
18636   if (IsGlobal &&
18637       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18638                                                 MaxFunctionScopesIndex)))
18639     return true;
18640   Var = Var->getCanonicalDecl();
18641 
18642   // Walk up the stack to determine whether we can capture the variable,
18643   // performing the "simple" checks that don't depend on type. We stop when
18644   // we've either hit the declared scope of the variable or find an existing
18645   // capture of that variable.  We start from the innermost capturing-entity
18646   // (the DC) and ensure that all intervening capturing-entities
18647   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18648   // declcontext can either capture the variable or have already captured
18649   // the variable.
18650   CaptureType = Var->getType();
18651   DeclRefType = CaptureType.getNonReferenceType();
18652   bool Nested = false;
18653   bool Explicit = (Kind != TryCapture_Implicit);
18654   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18655   do {
18656     // Only block literals, captured statements, and lambda expressions can
18657     // capture; other scopes don't work.
18658     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
18659                                                               ExprLoc,
18660                                                               BuildAndDiagnose,
18661                                                               *this);
18662     // We need to check for the parent *first* because, if we *have*
18663     // private-captured a global variable, we need to recursively capture it in
18664     // intermediate blocks, lambdas, etc.
18665     if (!ParentDC) {
18666       if (IsGlobal) {
18667         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18668         break;
18669       }
18670       return true;
18671     }
18672 
18673     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
18674     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18675 
18676 
18677     // Check whether we've already captured it.
18678     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18679                                              DeclRefType)) {
18680       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18681       break;
18682     }
18683     // If we are instantiating a generic lambda call operator body,
18684     // we do not want to capture new variables.  What was captured
18685     // during either a lambdas transformation or initial parsing
18686     // should be used.
18687     if (isGenericLambdaCallOperatorSpecialization(DC)) {
18688       if (BuildAndDiagnose) {
18689         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18690         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
18691           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18692           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18693           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18694           buildLambdaCaptureFixit(*this, LSI, Var);
18695         } else
18696           diagnoseUncapturableValueReference(*this, ExprLoc, Var);
18697       }
18698       return true;
18699     }
18700 
18701     // Try to capture variable-length arrays types.
18702     if (Var->getType()->isVariablyModifiedType()) {
18703       // We're going to walk down into the type and look for VLA
18704       // expressions.
18705       QualType QTy = Var->getType();
18706       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18707         QTy = PVD->getOriginalType();
18708       captureVariablyModifiedType(Context, QTy, CSI);
18709     }
18710 
18711     if (getLangOpts().OpenMP) {
18712       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18713         // OpenMP private variables should not be captured in outer scope, so
18714         // just break here. Similarly, global variables that are captured in a
18715         // target region should not be captured outside the scope of the region.
18716         if (RSI->CapRegionKind == CR_OpenMP) {
18717           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
18718               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18719           // If the variable is private (i.e. not captured) and has variably
18720           // modified type, we still need to capture the type for correct
18721           // codegen in all regions, associated with the construct. Currently,
18722           // it is captured in the innermost captured region only.
18723           if (IsOpenMPPrivateDecl != OMPC_unknown &&
18724               Var->getType()->isVariablyModifiedType()) {
18725             QualType QTy = Var->getType();
18726             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18727               QTy = PVD->getOriginalType();
18728             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
18729                  I < E; ++I) {
18730               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18731                   FunctionScopes[FunctionScopesIndex - I]);
18732               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
18733                      "Wrong number of captured regions associated with the "
18734                      "OpenMP construct.");
18735               captureVariablyModifiedType(Context, QTy, OuterRSI);
18736             }
18737           }
18738           bool IsTargetCap =
18739               IsOpenMPPrivateDecl != OMPC_private &&
18740               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
18741                                          RSI->OpenMPCaptureLevel);
18742           // Do not capture global if it is not privatized in outer regions.
18743           bool IsGlobalCap =
18744               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
18745                                                      RSI->OpenMPCaptureLevel);
18746 
18747           // When we detect target captures we are looking from inside the
18748           // target region, therefore we need to propagate the capture from the
18749           // enclosing region. Therefore, the capture is not initially nested.
18750           if (IsTargetCap)
18751             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
18752 
18753           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18754               (IsGlobal && !IsGlobalCap)) {
18755             Nested = !IsTargetCap;
18756             bool HasConst = DeclRefType.isConstQualified();
18757             DeclRefType = DeclRefType.getUnqualifiedType();
18758             // Don't lose diagnostics about assignments to const.
18759             if (HasConst)
18760               DeclRefType.addConst();
18761             CaptureType = Context.getLValueReferenceType(DeclRefType);
18762             break;
18763           }
18764         }
18765       }
18766     }
18767     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18768       // No capture-default, and this is not an explicit capture
18769       // so cannot capture this variable.
18770       if (BuildAndDiagnose) {
18771         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18772         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18773         auto *LSI = cast<LambdaScopeInfo>(CSI);
18774         if (LSI->Lambda) {
18775           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18776           buildLambdaCaptureFixit(*this, LSI, Var);
18777         }
18778         // FIXME: If we error out because an outer lambda can not implicitly
18779         // capture a variable that an inner lambda explicitly captures, we
18780         // should have the inner lambda do the explicit capture - because
18781         // it makes for cleaner diagnostics later.  This would purely be done
18782         // so that the diagnostic does not misleadingly claim that a variable
18783         // can not be captured by a lambda implicitly even though it is captured
18784         // explicitly.  Suggestion:
18785         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18786         //    at the function head
18787         //  - cache the StartingDeclContext - this must be a lambda
18788         //  - captureInLambda in the innermost lambda the variable.
18789       }
18790       return true;
18791     }
18792 
18793     FunctionScopesIndex--;
18794     DC = ParentDC;
18795     Explicit = false;
18796   } while (!VarDC->Equals(DC));
18797 
18798   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18799   // computing the type of the capture at each step, checking type-specific
18800   // requirements, and adding captures if requested.
18801   // If the variable had already been captured previously, we start capturing
18802   // at the lambda nested within that one.
18803   bool Invalid = false;
18804   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18805        ++I) {
18806     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18807 
18808     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18809     // certain types of variables (unnamed, variably modified types etc.)
18810     // so check for eligibility.
18811     if (!Invalid)
18812       Invalid =
18813           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18814 
18815     // After encountering an error, if we're actually supposed to capture, keep
18816     // capturing in nested contexts to suppress any follow-on diagnostics.
18817     if (Invalid && !BuildAndDiagnose)
18818       return true;
18819 
18820     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18821       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18822                                DeclRefType, Nested, *this, Invalid);
18823       Nested = true;
18824     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18825       Invalid = !captureInCapturedRegion(
18826           RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18827           Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18828       Nested = true;
18829     } else {
18830       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18831       Invalid =
18832           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18833                            DeclRefType, Nested, Kind, EllipsisLoc,
18834                            /*IsTopScope*/ I == N - 1, *this, Invalid);
18835       Nested = true;
18836     }
18837 
18838     if (Invalid && !BuildAndDiagnose)
18839       return true;
18840   }
18841   return Invalid;
18842 }
18843 
18844 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
18845                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18846   QualType CaptureType;
18847   QualType DeclRefType;
18848   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18849                             /*BuildAndDiagnose=*/true, CaptureType,
18850                             DeclRefType, nullptr);
18851 }
18852 
18853 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
18854   QualType CaptureType;
18855   QualType DeclRefType;
18856   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18857                              /*BuildAndDiagnose=*/false, CaptureType,
18858                              DeclRefType, nullptr);
18859 }
18860 
18861 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
18862   QualType CaptureType;
18863   QualType DeclRefType;
18864 
18865   // Determine whether we can capture this variable.
18866   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18867                          /*BuildAndDiagnose=*/false, CaptureType,
18868                          DeclRefType, nullptr))
18869     return QualType();
18870 
18871   return DeclRefType;
18872 }
18873 
18874 namespace {
18875 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
18876 // The produced TemplateArgumentListInfo* points to data stored within this
18877 // object, so should only be used in contexts where the pointer will not be
18878 // used after the CopiedTemplateArgs object is destroyed.
18879 class CopiedTemplateArgs {
18880   bool HasArgs;
18881   TemplateArgumentListInfo TemplateArgStorage;
18882 public:
18883   template<typename RefExpr>
18884   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
18885     if (HasArgs)
18886       E->copyTemplateArgumentsInto(TemplateArgStorage);
18887   }
18888   operator TemplateArgumentListInfo*()
18889 #ifdef __has_cpp_attribute
18890 #if __has_cpp_attribute(clang::lifetimebound)
18891   [[clang::lifetimebound]]
18892 #endif
18893 #endif
18894   {
18895     return HasArgs ? &TemplateArgStorage : nullptr;
18896   }
18897 };
18898 }
18899 
18900 /// Walk the set of potential results of an expression and mark them all as
18901 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
18902 ///
18903 /// \return A new expression if we found any potential results, ExprEmpty() if
18904 ///         not, and ExprError() if we diagnosed an error.
18905 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
18906                                                       NonOdrUseReason NOUR) {
18907   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
18908   // an object that satisfies the requirements for appearing in a
18909   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
18910   // is immediately applied."  This function handles the lvalue-to-rvalue
18911   // conversion part.
18912   //
18913   // If we encounter a node that claims to be an odr-use but shouldn't be, we
18914   // transform it into the relevant kind of non-odr-use node and rebuild the
18915   // tree of nodes leading to it.
18916   //
18917   // This is a mini-TreeTransform that only transforms a restricted subset of
18918   // nodes (and only certain operands of them).
18919 
18920   // Rebuild a subexpression.
18921   auto Rebuild = [&](Expr *Sub) {
18922     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
18923   };
18924 
18925   // Check whether a potential result satisfies the requirements of NOUR.
18926   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
18927     // Any entity other than a VarDecl is always odr-used whenever it's named
18928     // in a potentially-evaluated expression.
18929     auto *VD = dyn_cast<VarDecl>(D);
18930     if (!VD)
18931       return true;
18932 
18933     // C++2a [basic.def.odr]p4:
18934     //   A variable x whose name appears as a potentially-evalauted expression
18935     //   e is odr-used by e unless
18936     //   -- x is a reference that is usable in constant expressions, or
18937     //   -- x is a variable of non-reference type that is usable in constant
18938     //      expressions and has no mutable subobjects, and e is an element of
18939     //      the set of potential results of an expression of
18940     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18941     //      conversion is applied, or
18942     //   -- x is a variable of non-reference type, and e is an element of the
18943     //      set of potential results of a discarded-value expression to which
18944     //      the lvalue-to-rvalue conversion is not applied
18945     //
18946     // We check the first bullet and the "potentially-evaluated" condition in
18947     // BuildDeclRefExpr. We check the type requirements in the second bullet
18948     // in CheckLValueToRValueConversionOperand below.
18949     switch (NOUR) {
18950     case NOUR_None:
18951     case NOUR_Unevaluated:
18952       llvm_unreachable("unexpected non-odr-use-reason");
18953 
18954     case NOUR_Constant:
18955       // Constant references were handled when they were built.
18956       if (VD->getType()->isReferenceType())
18957         return true;
18958       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
18959         if (RD->hasMutableFields())
18960           return true;
18961       if (!VD->isUsableInConstantExpressions(S.Context))
18962         return true;
18963       break;
18964 
18965     case NOUR_Discarded:
18966       if (VD->getType()->isReferenceType())
18967         return true;
18968       break;
18969     }
18970     return false;
18971   };
18972 
18973   // Mark that this expression does not constitute an odr-use.
18974   auto MarkNotOdrUsed = [&] {
18975     S.MaybeODRUseExprs.remove(E);
18976     if (LambdaScopeInfo *LSI = S.getCurLambda())
18977       LSI->markVariableExprAsNonODRUsed(E);
18978   };
18979 
18980   // C++2a [basic.def.odr]p2:
18981   //   The set of potential results of an expression e is defined as follows:
18982   switch (E->getStmtClass()) {
18983   //   -- If e is an id-expression, ...
18984   case Expr::DeclRefExprClass: {
18985     auto *DRE = cast<DeclRefExpr>(E);
18986     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
18987       break;
18988 
18989     // Rebuild as a non-odr-use DeclRefExpr.
18990     MarkNotOdrUsed();
18991     return DeclRefExpr::Create(
18992         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
18993         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
18994         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
18995         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
18996   }
18997 
18998   case Expr::FunctionParmPackExprClass: {
18999     auto *FPPE = cast<FunctionParmPackExpr>(E);
19000     // If any of the declarations in the pack is odr-used, then the expression
19001     // as a whole constitutes an odr-use.
19002     for (VarDecl *D : *FPPE)
19003       if (IsPotentialResultOdrUsed(D))
19004         return ExprEmpty();
19005 
19006     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19007     // nothing cares about whether we marked this as an odr-use, but it might
19008     // be useful for non-compiler tools.
19009     MarkNotOdrUsed();
19010     break;
19011   }
19012 
19013   //   -- If e is a subscripting operation with an array operand...
19014   case Expr::ArraySubscriptExprClass: {
19015     auto *ASE = cast<ArraySubscriptExpr>(E);
19016     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19017     if (!OldBase->getType()->isArrayType())
19018       break;
19019     ExprResult Base = Rebuild(OldBase);
19020     if (!Base.isUsable())
19021       return Base;
19022     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19023     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19024     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19025     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19026                                      ASE->getRBracketLoc());
19027   }
19028 
19029   case Expr::MemberExprClass: {
19030     auto *ME = cast<MemberExpr>(E);
19031     // -- If e is a class member access expression [...] naming a non-static
19032     //    data member...
19033     if (isa<FieldDecl>(ME->getMemberDecl())) {
19034       ExprResult Base = Rebuild(ME->getBase());
19035       if (!Base.isUsable())
19036         return Base;
19037       return MemberExpr::Create(
19038           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19039           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19040           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19041           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19042           ME->getObjectKind(), ME->isNonOdrUse());
19043     }
19044 
19045     if (ME->getMemberDecl()->isCXXInstanceMember())
19046       break;
19047 
19048     // -- If e is a class member access expression naming a static data member,
19049     //    ...
19050     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19051       break;
19052 
19053     // Rebuild as a non-odr-use MemberExpr.
19054     MarkNotOdrUsed();
19055     return MemberExpr::Create(
19056         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19057         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19058         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19059         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19060   }
19061 
19062   case Expr::BinaryOperatorClass: {
19063     auto *BO = cast<BinaryOperator>(E);
19064     Expr *LHS = BO->getLHS();
19065     Expr *RHS = BO->getRHS();
19066     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19067     if (BO->getOpcode() == BO_PtrMemD) {
19068       ExprResult Sub = Rebuild(LHS);
19069       if (!Sub.isUsable())
19070         return Sub;
19071       LHS = Sub.get();
19072     //   -- If e is a comma expression, ...
19073     } else if (BO->getOpcode() == BO_Comma) {
19074       ExprResult Sub = Rebuild(RHS);
19075       if (!Sub.isUsable())
19076         return Sub;
19077       RHS = Sub.get();
19078     } else {
19079       break;
19080     }
19081     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
19082                         LHS, RHS);
19083   }
19084 
19085   //   -- If e has the form (e1)...
19086   case Expr::ParenExprClass: {
19087     auto *PE = cast<ParenExpr>(E);
19088     ExprResult Sub = Rebuild(PE->getSubExpr());
19089     if (!Sub.isUsable())
19090       return Sub;
19091     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19092   }
19093 
19094   //   -- If e is a glvalue conditional expression, ...
19095   // We don't apply this to a binary conditional operator. FIXME: Should we?
19096   case Expr::ConditionalOperatorClass: {
19097     auto *CO = cast<ConditionalOperator>(E);
19098     ExprResult LHS = Rebuild(CO->getLHS());
19099     if (LHS.isInvalid())
19100       return ExprError();
19101     ExprResult RHS = Rebuild(CO->getRHS());
19102     if (RHS.isInvalid())
19103       return ExprError();
19104     if (!LHS.isUsable() && !RHS.isUsable())
19105       return ExprEmpty();
19106     if (!LHS.isUsable())
19107       LHS = CO->getLHS();
19108     if (!RHS.isUsable())
19109       RHS = CO->getRHS();
19110     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19111                                 CO->getCond(), LHS.get(), RHS.get());
19112   }
19113 
19114   // [Clang extension]
19115   //   -- If e has the form __extension__ e1...
19116   case Expr::UnaryOperatorClass: {
19117     auto *UO = cast<UnaryOperator>(E);
19118     if (UO->getOpcode() != UO_Extension)
19119       break;
19120     ExprResult Sub = Rebuild(UO->getSubExpr());
19121     if (!Sub.isUsable())
19122       return Sub;
19123     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19124                           Sub.get());
19125   }
19126 
19127   // [Clang extension]
19128   //   -- If e has the form _Generic(...), the set of potential results is the
19129   //      union of the sets of potential results of the associated expressions.
19130   case Expr::GenericSelectionExprClass: {
19131     auto *GSE = cast<GenericSelectionExpr>(E);
19132 
19133     SmallVector<Expr *, 4> AssocExprs;
19134     bool AnyChanged = false;
19135     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19136       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19137       if (AssocExpr.isInvalid())
19138         return ExprError();
19139       if (AssocExpr.isUsable()) {
19140         AssocExprs.push_back(AssocExpr.get());
19141         AnyChanged = true;
19142       } else {
19143         AssocExprs.push_back(OrigAssocExpr);
19144       }
19145     }
19146 
19147     return AnyChanged ? S.CreateGenericSelectionExpr(
19148                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
19149                             GSE->getRParenLoc(), GSE->getControllingExpr(),
19150                             GSE->getAssocTypeSourceInfos(), AssocExprs)
19151                       : ExprEmpty();
19152   }
19153 
19154   // [Clang extension]
19155   //   -- If e has the form __builtin_choose_expr(...), the set of potential
19156   //      results is the union of the sets of potential results of the
19157   //      second and third subexpressions.
19158   case Expr::ChooseExprClass: {
19159     auto *CE = cast<ChooseExpr>(E);
19160 
19161     ExprResult LHS = Rebuild(CE->getLHS());
19162     if (LHS.isInvalid())
19163       return ExprError();
19164 
19165     ExprResult RHS = Rebuild(CE->getLHS());
19166     if (RHS.isInvalid())
19167       return ExprError();
19168 
19169     if (!LHS.get() && !RHS.get())
19170       return ExprEmpty();
19171     if (!LHS.isUsable())
19172       LHS = CE->getLHS();
19173     if (!RHS.isUsable())
19174       RHS = CE->getRHS();
19175 
19176     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19177                              RHS.get(), CE->getRParenLoc());
19178   }
19179 
19180   // Step through non-syntactic nodes.
19181   case Expr::ConstantExprClass: {
19182     auto *CE = cast<ConstantExpr>(E);
19183     ExprResult Sub = Rebuild(CE->getSubExpr());
19184     if (!Sub.isUsable())
19185       return Sub;
19186     return ConstantExpr::Create(S.Context, Sub.get());
19187   }
19188 
19189   // We could mostly rely on the recursive rebuilding to rebuild implicit
19190   // casts, but not at the top level, so rebuild them here.
19191   case Expr::ImplicitCastExprClass: {
19192     auto *ICE = cast<ImplicitCastExpr>(E);
19193     // Only step through the narrow set of cast kinds we expect to encounter.
19194     // Anything else suggests we've left the region in which potential results
19195     // can be found.
19196     switch (ICE->getCastKind()) {
19197     case CK_NoOp:
19198     case CK_DerivedToBase:
19199     case CK_UncheckedDerivedToBase: {
19200       ExprResult Sub = Rebuild(ICE->getSubExpr());
19201       if (!Sub.isUsable())
19202         return Sub;
19203       CXXCastPath Path(ICE->path());
19204       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19205                                  ICE->getValueKind(), &Path);
19206     }
19207 
19208     default:
19209       break;
19210     }
19211     break;
19212   }
19213 
19214   default:
19215     break;
19216   }
19217 
19218   // Can't traverse through this node. Nothing to do.
19219   return ExprEmpty();
19220 }
19221 
19222 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
19223   // Check whether the operand is or contains an object of non-trivial C union
19224   // type.
19225   if (E->getType().isVolatileQualified() &&
19226       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
19227        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
19228     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
19229                           Sema::NTCUC_LValueToRValueVolatile,
19230                           NTCUK_Destruct|NTCUK_Copy);
19231 
19232   // C++2a [basic.def.odr]p4:
19233   //   [...] an expression of non-volatile-qualified non-class type to which
19234   //   the lvalue-to-rvalue conversion is applied [...]
19235   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
19236     return E;
19237 
19238   ExprResult Result =
19239       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
19240   if (Result.isInvalid())
19241     return ExprError();
19242   return Result.get() ? Result : E;
19243 }
19244 
19245 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
19246   Res = CorrectDelayedTyposInExpr(Res);
19247 
19248   if (!Res.isUsable())
19249     return Res;
19250 
19251   // If a constant-expression is a reference to a variable where we delay
19252   // deciding whether it is an odr-use, just assume we will apply the
19253   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
19254   // (a non-type template argument), we have special handling anyway.
19255   return CheckLValueToRValueConversionOperand(Res.get());
19256 }
19257 
19258 void Sema::CleanupVarDeclMarking() {
19259   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19260   // call.
19261   MaybeODRUseExprSet LocalMaybeODRUseExprs;
19262   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19263 
19264   for (Expr *E : LocalMaybeODRUseExprs) {
19265     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19266       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19267                          DRE->getLocation(), *this);
19268     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19269       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19270                          *this);
19271     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19272       for (VarDecl *VD : *FP)
19273         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19274     } else {
19275       llvm_unreachable("Unexpected expression");
19276     }
19277   }
19278 
19279   assert(MaybeODRUseExprs.empty() &&
19280          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19281 }
19282 
19283 static void DoMarkVarDeclReferenced(
19284     Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
19285     llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19286   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19287           isa<FunctionParmPackExpr>(E)) &&
19288          "Invalid Expr argument to DoMarkVarDeclReferenced");
19289   Var->setReferenced();
19290 
19291   if (Var->isInvalidDecl())
19292     return;
19293 
19294   auto *MSI = Var->getMemberSpecializationInfo();
19295   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
19296                                        : Var->getTemplateSpecializationKind();
19297 
19298   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19299   bool UsableInConstantExpr =
19300       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
19301 
19302   if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19303     RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19304   }
19305 
19306   // C++20 [expr.const]p12:
19307   //   A variable [...] is needed for constant evaluation if it is [...] a
19308   //   variable whose name appears as a potentially constant evaluated
19309   //   expression that is either a contexpr variable or is of non-volatile
19310   //   const-qualified integral type or of reference type
19311   bool NeededForConstantEvaluation =
19312       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19313 
19314   bool NeedDefinition =
19315       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19316 
19317   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19318          "Can't instantiate a partial template specialization.");
19319 
19320   // If this might be a member specialization of a static data member, check
19321   // the specialization is visible. We already did the checks for variable
19322   // template specializations when we created them.
19323   if (NeedDefinition && TSK != TSK_Undeclared &&
19324       !isa<VarTemplateSpecializationDecl>(Var))
19325     SemaRef.checkSpecializationVisibility(Loc, Var);
19326 
19327   // Perform implicit instantiation of static data members, static data member
19328   // templates of class templates, and variable template specializations. Delay
19329   // instantiations of variable templates, except for those that could be used
19330   // in a constant expression.
19331   if (NeedDefinition && isTemplateInstantiation(TSK)) {
19332     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19333     // instantiation declaration if a variable is usable in a constant
19334     // expression (among other cases).
19335     bool TryInstantiating =
19336         TSK == TSK_ImplicitInstantiation ||
19337         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19338 
19339     if (TryInstantiating) {
19340       SourceLocation PointOfInstantiation =
19341           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19342       bool FirstInstantiation = PointOfInstantiation.isInvalid();
19343       if (FirstInstantiation) {
19344         PointOfInstantiation = Loc;
19345         if (MSI)
19346           MSI->setPointOfInstantiation(PointOfInstantiation);
19347           // FIXME: Notify listener.
19348         else
19349           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19350       }
19351 
19352       if (UsableInConstantExpr) {
19353         // Do not defer instantiations of variables that could be used in a
19354         // constant expression.
19355         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19356           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19357         });
19358 
19359         // Re-set the member to trigger a recomputation of the dependence bits
19360         // for the expression.
19361         if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19362           DRE->setDecl(DRE->getDecl());
19363         else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19364           ME->setMemberDecl(ME->getMemberDecl());
19365       } else if (FirstInstantiation ||
19366                  isa<VarTemplateSpecializationDecl>(Var)) {
19367         // FIXME: For a specialization of a variable template, we don't
19368         // distinguish between "declaration and type implicitly instantiated"
19369         // and "implicit instantiation of definition requested", so we have
19370         // no direct way to avoid enqueueing the pending instantiation
19371         // multiple times.
19372         SemaRef.PendingInstantiations
19373             .push_back(std::make_pair(Var, PointOfInstantiation));
19374       }
19375     }
19376   }
19377 
19378   // C++2a [basic.def.odr]p4:
19379   //   A variable x whose name appears as a potentially-evaluated expression e
19380   //   is odr-used by e unless
19381   //   -- x is a reference that is usable in constant expressions
19382   //   -- x is a variable of non-reference type that is usable in constant
19383   //      expressions and has no mutable subobjects [FIXME], and e is an
19384   //      element of the set of potential results of an expression of
19385   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
19386   //      conversion is applied
19387   //   -- x is a variable of non-reference type, and e is an element of the set
19388   //      of potential results of a discarded-value expression to which the
19389   //      lvalue-to-rvalue conversion is not applied [FIXME]
19390   //
19391   // We check the first part of the second bullet here, and
19392   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19393   // FIXME: To get the third bullet right, we need to delay this even for
19394   // variables that are not usable in constant expressions.
19395 
19396   // If we already know this isn't an odr-use, there's nothing more to do.
19397   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19398     if (DRE->isNonOdrUse())
19399       return;
19400   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19401     if (ME->isNonOdrUse())
19402       return;
19403 
19404   switch (OdrUse) {
19405   case OdrUseContext::None:
19406     assert((!E || isa<FunctionParmPackExpr>(E)) &&
19407            "missing non-odr-use marking for unevaluated decl ref");
19408     break;
19409 
19410   case OdrUseContext::FormallyOdrUsed:
19411     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19412     // behavior.
19413     break;
19414 
19415   case OdrUseContext::Used:
19416     // If we might later find that this expression isn't actually an odr-use,
19417     // delay the marking.
19418     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
19419       SemaRef.MaybeODRUseExprs.insert(E);
19420     else
19421       MarkVarDeclODRUsed(Var, Loc, SemaRef);
19422     break;
19423 
19424   case OdrUseContext::Dependent:
19425     // If this is a dependent context, we don't need to mark variables as
19426     // odr-used, but we may still need to track them for lambda capture.
19427     // FIXME: Do we also need to do this inside dependent typeid expressions
19428     // (which are modeled as unevaluated at this point)?
19429     const bool RefersToEnclosingScope =
19430         (SemaRef.CurContext != Var->getDeclContext() &&
19431          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
19432     if (RefersToEnclosingScope) {
19433       LambdaScopeInfo *const LSI =
19434           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19435       if (LSI && (!LSI->CallOperator ||
19436                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19437         // If a variable could potentially be odr-used, defer marking it so
19438         // until we finish analyzing the full expression for any
19439         // lvalue-to-rvalue
19440         // or discarded value conversions that would obviate odr-use.
19441         // Add it to the list of potential captures that will be analyzed
19442         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19443         // unless the variable is a reference that was initialized by a constant
19444         // expression (this will never need to be captured or odr-used).
19445         //
19446         // FIXME: We can simplify this a lot after implementing P0588R1.
19447         assert(E && "Capture variable should be used in an expression.");
19448         if (!Var->getType()->isReferenceType() ||
19449             !Var->isUsableInConstantExpressions(SemaRef.Context))
19450           LSI->addPotentialCapture(E->IgnoreParens());
19451       }
19452     }
19453     break;
19454   }
19455 }
19456 
19457 /// Mark a variable referenced, and check whether it is odr-used
19458 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
19459 /// used directly for normal expressions referring to VarDecl.
19460 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
19461   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19462 }
19463 
19464 static void
19465 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
19466                    bool MightBeOdrUse,
19467                    llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19468   if (SemaRef.isInOpenMPDeclareTargetContext())
19469     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
19470 
19471   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19472     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
19473     return;
19474   }
19475 
19476   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19477 
19478   // If this is a call to a method via a cast, also mark the method in the
19479   // derived class used in case codegen can devirtualize the call.
19480   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19481   if (!ME)
19482     return;
19483   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19484   if (!MD)
19485     return;
19486   // Only attempt to devirtualize if this is truly a virtual call.
19487   bool IsVirtualCall = MD->isVirtual() &&
19488                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
19489   if (!IsVirtualCall)
19490     return;
19491 
19492   // If it's possible to devirtualize the call, mark the called function
19493   // referenced.
19494   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
19495       ME->getBase(), SemaRef.getLangOpts().AppleKext);
19496   if (DM)
19497     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
19498 }
19499 
19500 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
19501 ///
19502 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
19503 /// handled with care if the DeclRefExpr is not newly-created.
19504 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
19505   // TODO: update this with DR# once a defect report is filed.
19506   // C++11 defect. The address of a pure member should not be an ODR use, even
19507   // if it's a qualified reference.
19508   bool OdrUse = true;
19509   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
19510     if (Method->isVirtual() &&
19511         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
19512       OdrUse = false;
19513 
19514   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
19515     if (!isUnevaluatedContext() && !isConstantEvaluated() &&
19516         FD->isConsteval() && !RebuildingImmediateInvocation)
19517       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
19518   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
19519                      RefsMinusAssignments);
19520 }
19521 
19522 /// Perform reference-marking and odr-use handling for a MemberExpr.
19523 void Sema::MarkMemberReferenced(MemberExpr *E) {
19524   // C++11 [basic.def.odr]p2:
19525   //   A non-overloaded function whose name appears as a potentially-evaluated
19526   //   expression or a member of a set of candidate functions, if selected by
19527   //   overload resolution when referred to from a potentially-evaluated
19528   //   expression, is odr-used, unless it is a pure virtual function and its
19529   //   name is not explicitly qualified.
19530   bool MightBeOdrUse = true;
19531   if (E->performsVirtualDispatch(getLangOpts())) {
19532     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
19533       if (Method->isPure())
19534         MightBeOdrUse = false;
19535   }
19536   SourceLocation Loc =
19537       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
19538   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
19539                      RefsMinusAssignments);
19540 }
19541 
19542 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
19543 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
19544   for (VarDecl *VD : *E)
19545     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
19546                        RefsMinusAssignments);
19547 }
19548 
19549 /// Perform marking for a reference to an arbitrary declaration.  It
19550 /// marks the declaration referenced, and performs odr-use checking for
19551 /// functions and variables. This method should not be used when building a
19552 /// normal expression which refers to a variable.
19553 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
19554                                  bool MightBeOdrUse) {
19555   if (MightBeOdrUse) {
19556     if (auto *VD = dyn_cast<VarDecl>(D)) {
19557       MarkVariableReferenced(Loc, VD);
19558       return;
19559     }
19560   }
19561   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19562     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
19563     return;
19564   }
19565   D->setReferenced();
19566 }
19567 
19568 namespace {
19569   // Mark all of the declarations used by a type as referenced.
19570   // FIXME: Not fully implemented yet! We need to have a better understanding
19571   // of when we're entering a context we should not recurse into.
19572   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
19573   // TreeTransforms rebuilding the type in a new context. Rather than
19574   // duplicating the TreeTransform logic, we should consider reusing it here.
19575   // Currently that causes problems when rebuilding LambdaExprs.
19576   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
19577     Sema &S;
19578     SourceLocation Loc;
19579 
19580   public:
19581     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
19582 
19583     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
19584 
19585     bool TraverseTemplateArgument(const TemplateArgument &Arg);
19586   };
19587 }
19588 
19589 bool MarkReferencedDecls::TraverseTemplateArgument(
19590     const TemplateArgument &Arg) {
19591   {
19592     // A non-type template argument is a constant-evaluated context.
19593     EnterExpressionEvaluationContext Evaluated(
19594         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
19595     if (Arg.getKind() == TemplateArgument::Declaration) {
19596       if (Decl *D = Arg.getAsDecl())
19597         S.MarkAnyDeclReferenced(Loc, D, true);
19598     } else if (Arg.getKind() == TemplateArgument::Expression) {
19599       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
19600     }
19601   }
19602 
19603   return Inherited::TraverseTemplateArgument(Arg);
19604 }
19605 
19606 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
19607   MarkReferencedDecls Marker(*this, Loc);
19608   Marker.TraverseType(T);
19609 }
19610 
19611 namespace {
19612 /// Helper class that marks all of the declarations referenced by
19613 /// potentially-evaluated subexpressions as "referenced".
19614 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
19615 public:
19616   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
19617   bool SkipLocalVariables;
19618   ArrayRef<const Expr *> StopAt;
19619 
19620   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
19621                       ArrayRef<const Expr *> StopAt)
19622       : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
19623 
19624   void visitUsedDecl(SourceLocation Loc, Decl *D) {
19625     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
19626   }
19627 
19628   void Visit(Expr *E) {
19629     if (llvm::is_contained(StopAt, E))
19630       return;
19631     Inherited::Visit(E);
19632   }
19633 
19634   void VisitConstantExpr(ConstantExpr *E) {
19635     // Don't mark declarations within a ConstantExpression, as this expression
19636     // will be evaluated and folded to a value.
19637     return;
19638   }
19639 
19640   void VisitDeclRefExpr(DeclRefExpr *E) {
19641     // If we were asked not to visit local variables, don't.
19642     if (SkipLocalVariables) {
19643       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
19644         if (VD->hasLocalStorage())
19645           return;
19646     }
19647 
19648     // FIXME: This can trigger the instantiation of the initializer of a
19649     // variable, which can cause the expression to become value-dependent
19650     // or error-dependent. Do we need to propagate the new dependence bits?
19651     S.MarkDeclRefReferenced(E);
19652   }
19653 
19654   void VisitMemberExpr(MemberExpr *E) {
19655     S.MarkMemberReferenced(E);
19656     Visit(E->getBase());
19657   }
19658 };
19659 } // namespace
19660 
19661 /// Mark any declarations that appear within this expression or any
19662 /// potentially-evaluated subexpressions as "referenced".
19663 ///
19664 /// \param SkipLocalVariables If true, don't mark local variables as
19665 /// 'referenced'.
19666 /// \param StopAt Subexpressions that we shouldn't recurse into.
19667 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
19668                                             bool SkipLocalVariables,
19669                                             ArrayRef<const Expr*> StopAt) {
19670   EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
19671 }
19672 
19673 /// Emit a diagnostic when statements are reachable.
19674 /// FIXME: check for reachability even in expressions for which we don't build a
19675 ///        CFG (eg, in the initializer of a global or in a constant expression).
19676 ///        For example,
19677 ///        namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
19678 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
19679                            const PartialDiagnostic &PD) {
19680   if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
19681     if (!FunctionScopes.empty())
19682       FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
19683           sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
19684     return true;
19685   }
19686 
19687   // The initializer of a constexpr variable or of the first declaration of a
19688   // static data member is not syntactically a constant evaluated constant,
19689   // but nonetheless is always required to be a constant expression, so we
19690   // can skip diagnosing.
19691   // FIXME: Using the mangling context here is a hack.
19692   if (auto *VD = dyn_cast_or_null<VarDecl>(
19693           ExprEvalContexts.back().ManglingContextDecl)) {
19694     if (VD->isConstexpr() ||
19695         (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
19696       return false;
19697     // FIXME: For any other kind of variable, we should build a CFG for its
19698     // initializer and check whether the context in question is reachable.
19699   }
19700 
19701   Diag(Loc, PD);
19702   return true;
19703 }
19704 
19705 /// Emit a diagnostic that describes an effect on the run-time behavior
19706 /// of the program being compiled.
19707 ///
19708 /// This routine emits the given diagnostic when the code currently being
19709 /// type-checked is "potentially evaluated", meaning that there is a
19710 /// possibility that the code will actually be executable. Code in sizeof()
19711 /// expressions, code used only during overload resolution, etc., are not
19712 /// potentially evaluated. This routine will suppress such diagnostics or,
19713 /// in the absolutely nutty case of potentially potentially evaluated
19714 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
19715 /// later.
19716 ///
19717 /// This routine should be used for all diagnostics that describe the run-time
19718 /// behavior of a program, such as passing a non-POD value through an ellipsis.
19719 /// Failure to do so will likely result in spurious diagnostics or failures
19720 /// during overload resolution or within sizeof/alignof/typeof/typeid.
19721 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
19722                                const PartialDiagnostic &PD) {
19723 
19724   if (ExprEvalContexts.back().isDiscardedStatementContext())
19725     return false;
19726 
19727   switch (ExprEvalContexts.back().Context) {
19728   case ExpressionEvaluationContext::Unevaluated:
19729   case ExpressionEvaluationContext::UnevaluatedList:
19730   case ExpressionEvaluationContext::UnevaluatedAbstract:
19731   case ExpressionEvaluationContext::DiscardedStatement:
19732     // The argument will never be evaluated, so don't complain.
19733     break;
19734 
19735   case ExpressionEvaluationContext::ConstantEvaluated:
19736   case ExpressionEvaluationContext::ImmediateFunctionContext:
19737     // Relevant diagnostics should be produced by constant evaluation.
19738     break;
19739 
19740   case ExpressionEvaluationContext::PotentiallyEvaluated:
19741   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19742     return DiagIfReachable(Loc, Stmts, PD);
19743   }
19744 
19745   return false;
19746 }
19747 
19748 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
19749                                const PartialDiagnostic &PD) {
19750   return DiagRuntimeBehavior(
19751       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
19752 }
19753 
19754 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
19755                                CallExpr *CE, FunctionDecl *FD) {
19756   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
19757     return false;
19758 
19759   // If we're inside a decltype's expression, don't check for a valid return
19760   // type or construct temporaries until we know whether this is the last call.
19761   if (ExprEvalContexts.back().ExprContext ==
19762       ExpressionEvaluationContextRecord::EK_Decltype) {
19763     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
19764     return false;
19765   }
19766 
19767   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
19768     FunctionDecl *FD;
19769     CallExpr *CE;
19770 
19771   public:
19772     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
19773       : FD(FD), CE(CE) { }
19774 
19775     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19776       if (!FD) {
19777         S.Diag(Loc, diag::err_call_incomplete_return)
19778           << T << CE->getSourceRange();
19779         return;
19780       }
19781 
19782       S.Diag(Loc, diag::err_call_function_incomplete_return)
19783           << CE->getSourceRange() << FD << T;
19784       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
19785           << FD->getDeclName();
19786     }
19787   } Diagnoser(FD, CE);
19788 
19789   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
19790     return true;
19791 
19792   return false;
19793 }
19794 
19795 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
19796 // will prevent this condition from triggering, which is what we want.
19797 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
19798   SourceLocation Loc;
19799 
19800   unsigned diagnostic = diag::warn_condition_is_assignment;
19801   bool IsOrAssign = false;
19802 
19803   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
19804     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
19805       return;
19806 
19807     IsOrAssign = Op->getOpcode() == BO_OrAssign;
19808 
19809     // Greylist some idioms by putting them into a warning subcategory.
19810     if (ObjCMessageExpr *ME
19811           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
19812       Selector Sel = ME->getSelector();
19813 
19814       // self = [<foo> init...]
19815       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
19816         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19817 
19818       // <foo> = [<bar> nextObject]
19819       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
19820         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19821     }
19822 
19823     Loc = Op->getOperatorLoc();
19824   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
19825     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
19826       return;
19827 
19828     IsOrAssign = Op->getOperator() == OO_PipeEqual;
19829     Loc = Op->getOperatorLoc();
19830   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
19831     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
19832   else {
19833     // Not an assignment.
19834     return;
19835   }
19836 
19837   Diag(Loc, diagnostic) << E->getSourceRange();
19838 
19839   SourceLocation Open = E->getBeginLoc();
19840   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
19841   Diag(Loc, diag::note_condition_assign_silence)
19842         << FixItHint::CreateInsertion(Open, "(")
19843         << FixItHint::CreateInsertion(Close, ")");
19844 
19845   if (IsOrAssign)
19846     Diag(Loc, diag::note_condition_or_assign_to_comparison)
19847       << FixItHint::CreateReplacement(Loc, "!=");
19848   else
19849     Diag(Loc, diag::note_condition_assign_to_comparison)
19850       << FixItHint::CreateReplacement(Loc, "==");
19851 }
19852 
19853 /// Redundant parentheses over an equality comparison can indicate
19854 /// that the user intended an assignment used as condition.
19855 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
19856   // Don't warn if the parens came from a macro.
19857   SourceLocation parenLoc = ParenE->getBeginLoc();
19858   if (parenLoc.isInvalid() || parenLoc.isMacroID())
19859     return;
19860   // Don't warn for dependent expressions.
19861   if (ParenE->isTypeDependent())
19862     return;
19863 
19864   Expr *E = ParenE->IgnoreParens();
19865 
19866   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
19867     if (opE->getOpcode() == BO_EQ &&
19868         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
19869                                                            == Expr::MLV_Valid) {
19870       SourceLocation Loc = opE->getOperatorLoc();
19871 
19872       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
19873       SourceRange ParenERange = ParenE->getSourceRange();
19874       Diag(Loc, diag::note_equality_comparison_silence)
19875         << FixItHint::CreateRemoval(ParenERange.getBegin())
19876         << FixItHint::CreateRemoval(ParenERange.getEnd());
19877       Diag(Loc, diag::note_equality_comparison_to_assign)
19878         << FixItHint::CreateReplacement(Loc, "=");
19879     }
19880 }
19881 
19882 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
19883                                        bool IsConstexpr) {
19884   DiagnoseAssignmentAsCondition(E);
19885   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
19886     DiagnoseEqualityWithExtraParens(parenE);
19887 
19888   ExprResult result = CheckPlaceholderExpr(E);
19889   if (result.isInvalid()) return ExprError();
19890   E = result.get();
19891 
19892   if (!E->isTypeDependent()) {
19893     if (getLangOpts().CPlusPlus)
19894       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
19895 
19896     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
19897     if (ERes.isInvalid())
19898       return ExprError();
19899     E = ERes.get();
19900 
19901     QualType T = E->getType();
19902     if (!T->isScalarType()) { // C99 6.8.4.1p1
19903       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
19904         << T << E->getSourceRange();
19905       return ExprError();
19906     }
19907     CheckBoolLikeConversion(E, Loc);
19908   }
19909 
19910   return E;
19911 }
19912 
19913 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
19914                                            Expr *SubExpr, ConditionKind CK,
19915                                            bool MissingOK) {
19916   // MissingOK indicates whether having no condition expression is valid
19917   // (for loop) or invalid (e.g. while loop).
19918   if (!SubExpr)
19919     return MissingOK ? ConditionResult() : ConditionError();
19920 
19921   ExprResult Cond;
19922   switch (CK) {
19923   case ConditionKind::Boolean:
19924     Cond = CheckBooleanCondition(Loc, SubExpr);
19925     break;
19926 
19927   case ConditionKind::ConstexprIf:
19928     Cond = CheckBooleanCondition(Loc, SubExpr, true);
19929     break;
19930 
19931   case ConditionKind::Switch:
19932     Cond = CheckSwitchCondition(Loc, SubExpr);
19933     break;
19934   }
19935   if (Cond.isInvalid()) {
19936     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
19937                               {SubExpr}, PreferredConditionType(CK));
19938     if (!Cond.get())
19939       return ConditionError();
19940   }
19941   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
19942   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
19943   if (!FullExpr.get())
19944     return ConditionError();
19945 
19946   return ConditionResult(*this, nullptr, FullExpr,
19947                          CK == ConditionKind::ConstexprIf);
19948 }
19949 
19950 namespace {
19951   /// A visitor for rebuilding a call to an __unknown_any expression
19952   /// to have an appropriate type.
19953   struct RebuildUnknownAnyFunction
19954     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
19955 
19956     Sema &S;
19957 
19958     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
19959 
19960     ExprResult VisitStmt(Stmt *S) {
19961       llvm_unreachable("unexpected statement!");
19962     }
19963 
19964     ExprResult VisitExpr(Expr *E) {
19965       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
19966         << E->getSourceRange();
19967       return ExprError();
19968     }
19969 
19970     /// Rebuild an expression which simply semantically wraps another
19971     /// expression which it shares the type and value kind of.
19972     template <class T> ExprResult rebuildSugarExpr(T *E) {
19973       ExprResult SubResult = Visit(E->getSubExpr());
19974       if (SubResult.isInvalid()) return ExprError();
19975 
19976       Expr *SubExpr = SubResult.get();
19977       E->setSubExpr(SubExpr);
19978       E->setType(SubExpr->getType());
19979       E->setValueKind(SubExpr->getValueKind());
19980       assert(E->getObjectKind() == OK_Ordinary);
19981       return E;
19982     }
19983 
19984     ExprResult VisitParenExpr(ParenExpr *E) {
19985       return rebuildSugarExpr(E);
19986     }
19987 
19988     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19989       return rebuildSugarExpr(E);
19990     }
19991 
19992     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19993       ExprResult SubResult = Visit(E->getSubExpr());
19994       if (SubResult.isInvalid()) return ExprError();
19995 
19996       Expr *SubExpr = SubResult.get();
19997       E->setSubExpr(SubExpr);
19998       E->setType(S.Context.getPointerType(SubExpr->getType()));
19999       assert(E->isPRValue());
20000       assert(E->getObjectKind() == OK_Ordinary);
20001       return E;
20002     }
20003 
20004     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20005       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20006 
20007       E->setType(VD->getType());
20008 
20009       assert(E->isPRValue());
20010       if (S.getLangOpts().CPlusPlus &&
20011           !(isa<CXXMethodDecl>(VD) &&
20012             cast<CXXMethodDecl>(VD)->isInstance()))
20013         E->setValueKind(VK_LValue);
20014 
20015       return E;
20016     }
20017 
20018     ExprResult VisitMemberExpr(MemberExpr *E) {
20019       return resolveDecl(E, E->getMemberDecl());
20020     }
20021 
20022     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20023       return resolveDecl(E, E->getDecl());
20024     }
20025   };
20026 }
20027 
20028 /// Given a function expression of unknown-any type, try to rebuild it
20029 /// to have a function type.
20030 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
20031   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20032   if (Result.isInvalid()) return ExprError();
20033   return S.DefaultFunctionArrayConversion(Result.get());
20034 }
20035 
20036 namespace {
20037   /// A visitor for rebuilding an expression of type __unknown_anytype
20038   /// into one which resolves the type directly on the referring
20039   /// expression.  Strict preservation of the original source
20040   /// structure is not a goal.
20041   struct RebuildUnknownAnyExpr
20042     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20043 
20044     Sema &S;
20045 
20046     /// The current destination type.
20047     QualType DestType;
20048 
20049     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20050       : S(S), DestType(CastType) {}
20051 
20052     ExprResult VisitStmt(Stmt *S) {
20053       llvm_unreachable("unexpected statement!");
20054     }
20055 
20056     ExprResult VisitExpr(Expr *E) {
20057       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20058         << E->getSourceRange();
20059       return ExprError();
20060     }
20061 
20062     ExprResult VisitCallExpr(CallExpr *E);
20063     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20064 
20065     /// Rebuild an expression which simply semantically wraps another
20066     /// expression which it shares the type and value kind of.
20067     template <class T> ExprResult rebuildSugarExpr(T *E) {
20068       ExprResult SubResult = Visit(E->getSubExpr());
20069       if (SubResult.isInvalid()) return ExprError();
20070       Expr *SubExpr = SubResult.get();
20071       E->setSubExpr(SubExpr);
20072       E->setType(SubExpr->getType());
20073       E->setValueKind(SubExpr->getValueKind());
20074       assert(E->getObjectKind() == OK_Ordinary);
20075       return E;
20076     }
20077 
20078     ExprResult VisitParenExpr(ParenExpr *E) {
20079       return rebuildSugarExpr(E);
20080     }
20081 
20082     ExprResult VisitUnaryExtension(UnaryOperator *E) {
20083       return rebuildSugarExpr(E);
20084     }
20085 
20086     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20087       const PointerType *Ptr = DestType->getAs<PointerType>();
20088       if (!Ptr) {
20089         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20090           << E->getSourceRange();
20091         return ExprError();
20092       }
20093 
20094       if (isa<CallExpr>(E->getSubExpr())) {
20095         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20096           << E->getSourceRange();
20097         return ExprError();
20098       }
20099 
20100       assert(E->isPRValue());
20101       assert(E->getObjectKind() == OK_Ordinary);
20102       E->setType(DestType);
20103 
20104       // Build the sub-expression as if it were an object of the pointee type.
20105       DestType = Ptr->getPointeeType();
20106       ExprResult SubResult = Visit(E->getSubExpr());
20107       if (SubResult.isInvalid()) return ExprError();
20108       E->setSubExpr(SubResult.get());
20109       return E;
20110     }
20111 
20112     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20113 
20114     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20115 
20116     ExprResult VisitMemberExpr(MemberExpr *E) {
20117       return resolveDecl(E, E->getMemberDecl());
20118     }
20119 
20120     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20121       return resolveDecl(E, E->getDecl());
20122     }
20123   };
20124 }
20125 
20126 /// Rebuilds a call expression which yielded __unknown_anytype.
20127 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20128   Expr *CalleeExpr = E->getCallee();
20129 
20130   enum FnKind {
20131     FK_MemberFunction,
20132     FK_FunctionPointer,
20133     FK_BlockPointer
20134   };
20135 
20136   FnKind Kind;
20137   QualType CalleeType = CalleeExpr->getType();
20138   if (CalleeType == S.Context.BoundMemberTy) {
20139     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20140     Kind = FK_MemberFunction;
20141     CalleeType = Expr::findBoundMemberType(CalleeExpr);
20142   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20143     CalleeType = Ptr->getPointeeType();
20144     Kind = FK_FunctionPointer;
20145   } else {
20146     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20147     Kind = FK_BlockPointer;
20148   }
20149   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20150 
20151   // Verify that this is a legal result type of a function.
20152   if (DestType->isArrayType() || DestType->isFunctionType()) {
20153     unsigned diagID = diag::err_func_returning_array_function;
20154     if (Kind == FK_BlockPointer)
20155       diagID = diag::err_block_returning_array_function;
20156 
20157     S.Diag(E->getExprLoc(), diagID)
20158       << DestType->isFunctionType() << DestType;
20159     return ExprError();
20160   }
20161 
20162   // Otherwise, go ahead and set DestType as the call's result.
20163   E->setType(DestType.getNonLValueExprType(S.Context));
20164   E->setValueKind(Expr::getValueKindForType(DestType));
20165   assert(E->getObjectKind() == OK_Ordinary);
20166 
20167   // Rebuild the function type, replacing the result type with DestType.
20168   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20169   if (Proto) {
20170     // __unknown_anytype(...) is a special case used by the debugger when
20171     // it has no idea what a function's signature is.
20172     //
20173     // We want to build this call essentially under the K&R
20174     // unprototyped rules, but making a FunctionNoProtoType in C++
20175     // would foul up all sorts of assumptions.  However, we cannot
20176     // simply pass all arguments as variadic arguments, nor can we
20177     // portably just call the function under a non-variadic type; see
20178     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20179     // However, it turns out that in practice it is generally safe to
20180     // call a function declared as "A foo(B,C,D);" under the prototype
20181     // "A foo(B,C,D,...);".  The only known exception is with the
20182     // Windows ABI, where any variadic function is implicitly cdecl
20183     // regardless of its normal CC.  Therefore we change the parameter
20184     // types to match the types of the arguments.
20185     //
20186     // This is a hack, but it is far superior to moving the
20187     // corresponding target-specific code from IR-gen to Sema/AST.
20188 
20189     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20190     SmallVector<QualType, 8> ArgTypes;
20191     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20192       ArgTypes.reserve(E->getNumArgs());
20193       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20194         ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20195       }
20196       ParamTypes = ArgTypes;
20197     }
20198     DestType = S.Context.getFunctionType(DestType, ParamTypes,
20199                                          Proto->getExtProtoInfo());
20200   } else {
20201     DestType = S.Context.getFunctionNoProtoType(DestType,
20202                                                 FnType->getExtInfo());
20203   }
20204 
20205   // Rebuild the appropriate pointer-to-function type.
20206   switch (Kind) {
20207   case FK_MemberFunction:
20208     // Nothing to do.
20209     break;
20210 
20211   case FK_FunctionPointer:
20212     DestType = S.Context.getPointerType(DestType);
20213     break;
20214 
20215   case FK_BlockPointer:
20216     DestType = S.Context.getBlockPointerType(DestType);
20217     break;
20218   }
20219 
20220   // Finally, we can recurse.
20221   ExprResult CalleeResult = Visit(CalleeExpr);
20222   if (!CalleeResult.isUsable()) return ExprError();
20223   E->setCallee(CalleeResult.get());
20224 
20225   // Bind a temporary if necessary.
20226   return S.MaybeBindToTemporary(E);
20227 }
20228 
20229 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20230   // Verify that this is a legal result type of a call.
20231   if (DestType->isArrayType() || DestType->isFunctionType()) {
20232     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20233       << DestType->isFunctionType() << DestType;
20234     return ExprError();
20235   }
20236 
20237   // Rewrite the method result type if available.
20238   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20239     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20240     Method->setReturnType(DestType);
20241   }
20242 
20243   // Change the type of the message.
20244   E->setType(DestType.getNonReferenceType());
20245   E->setValueKind(Expr::getValueKindForType(DestType));
20246 
20247   return S.MaybeBindToTemporary(E);
20248 }
20249 
20250 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20251   // The only case we should ever see here is a function-to-pointer decay.
20252   if (E->getCastKind() == CK_FunctionToPointerDecay) {
20253     assert(E->isPRValue());
20254     assert(E->getObjectKind() == OK_Ordinary);
20255 
20256     E->setType(DestType);
20257 
20258     // Rebuild the sub-expression as the pointee (function) type.
20259     DestType = DestType->castAs<PointerType>()->getPointeeType();
20260 
20261     ExprResult Result = Visit(E->getSubExpr());
20262     if (!Result.isUsable()) return ExprError();
20263 
20264     E->setSubExpr(Result.get());
20265     return E;
20266   } else if (E->getCastKind() == CK_LValueToRValue) {
20267     assert(E->isPRValue());
20268     assert(E->getObjectKind() == OK_Ordinary);
20269 
20270     assert(isa<BlockPointerType>(E->getType()));
20271 
20272     E->setType(DestType);
20273 
20274     // The sub-expression has to be a lvalue reference, so rebuild it as such.
20275     DestType = S.Context.getLValueReferenceType(DestType);
20276 
20277     ExprResult Result = Visit(E->getSubExpr());
20278     if (!Result.isUsable()) return ExprError();
20279 
20280     E->setSubExpr(Result.get());
20281     return E;
20282   } else {
20283     llvm_unreachable("Unhandled cast type!");
20284   }
20285 }
20286 
20287 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20288   ExprValueKind ValueKind = VK_LValue;
20289   QualType Type = DestType;
20290 
20291   // We know how to make this work for certain kinds of decls:
20292 
20293   //  - functions
20294   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20295     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20296       DestType = Ptr->getPointeeType();
20297       ExprResult Result = resolveDecl(E, VD);
20298       if (Result.isInvalid()) return ExprError();
20299       return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20300                                  VK_PRValue);
20301     }
20302 
20303     if (!Type->isFunctionType()) {
20304       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20305         << VD << E->getSourceRange();
20306       return ExprError();
20307     }
20308     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20309       // We must match the FunctionDecl's type to the hack introduced in
20310       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20311       // type. See the lengthy commentary in that routine.
20312       QualType FDT = FD->getType();
20313       const FunctionType *FnType = FDT->castAs<FunctionType>();
20314       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20315       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20316       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20317         SourceLocation Loc = FD->getLocation();
20318         FunctionDecl *NewFD = FunctionDecl::Create(
20319             S.Context, FD->getDeclContext(), Loc, Loc,
20320             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20321             SC_None, S.getCurFPFeatures().isFPConstrained(),
20322             false /*isInlineSpecified*/, FD->hasPrototype(),
20323             /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20324 
20325         if (FD->getQualifier())
20326           NewFD->setQualifierInfo(FD->getQualifierLoc());
20327 
20328         SmallVector<ParmVarDecl*, 16> Params;
20329         for (const auto &AI : FT->param_types()) {
20330           ParmVarDecl *Param =
20331             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
20332           Param->setScopeInfo(0, Params.size());
20333           Params.push_back(Param);
20334         }
20335         NewFD->setParams(Params);
20336         DRE->setDecl(NewFD);
20337         VD = DRE->getDecl();
20338       }
20339     }
20340 
20341     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20342       if (MD->isInstance()) {
20343         ValueKind = VK_PRValue;
20344         Type = S.Context.BoundMemberTy;
20345       }
20346 
20347     // Function references aren't l-values in C.
20348     if (!S.getLangOpts().CPlusPlus)
20349       ValueKind = VK_PRValue;
20350 
20351   //  - variables
20352   } else if (isa<VarDecl>(VD)) {
20353     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20354       Type = RefTy->getPointeeType();
20355     } else if (Type->isFunctionType()) {
20356       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20357         << VD << E->getSourceRange();
20358       return ExprError();
20359     }
20360 
20361   //  - nothing else
20362   } else {
20363     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20364       << VD << E->getSourceRange();
20365     return ExprError();
20366   }
20367 
20368   // Modifying the declaration like this is friendly to IR-gen but
20369   // also really dangerous.
20370   VD->setType(DestType);
20371   E->setType(Type);
20372   E->setValueKind(ValueKind);
20373   return E;
20374 }
20375 
20376 /// Check a cast of an unknown-any type.  We intentionally only
20377 /// trigger this for C-style casts.
20378 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
20379                                      Expr *CastExpr, CastKind &CastKind,
20380                                      ExprValueKind &VK, CXXCastPath &Path) {
20381   // The type we're casting to must be either void or complete.
20382   if (!CastType->isVoidType() &&
20383       RequireCompleteType(TypeRange.getBegin(), CastType,
20384                           diag::err_typecheck_cast_to_incomplete))
20385     return ExprError();
20386 
20387   // Rewrite the casted expression from scratch.
20388   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20389   if (!result.isUsable()) return ExprError();
20390 
20391   CastExpr = result.get();
20392   VK = CastExpr->getValueKind();
20393   CastKind = CK_NoOp;
20394 
20395   return CastExpr;
20396 }
20397 
20398 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
20399   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20400 }
20401 
20402 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
20403                                     Expr *arg, QualType &paramType) {
20404   // If the syntactic form of the argument is not an explicit cast of
20405   // any sort, just do default argument promotion.
20406   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20407   if (!castArg) {
20408     ExprResult result = DefaultArgumentPromotion(arg);
20409     if (result.isInvalid()) return ExprError();
20410     paramType = result.get()->getType();
20411     return result;
20412   }
20413 
20414   // Otherwise, use the type that was written in the explicit cast.
20415   assert(!arg->hasPlaceholderType());
20416   paramType = castArg->getTypeAsWritten();
20417 
20418   // Copy-initialize a parameter of that type.
20419   InitializedEntity entity =
20420     InitializedEntity::InitializeParameter(Context, paramType,
20421                                            /*consumed*/ false);
20422   return PerformCopyInitialization(entity, callLoc, arg);
20423 }
20424 
20425 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
20426   Expr *orig = E;
20427   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20428   while (true) {
20429     E = E->IgnoreParenImpCasts();
20430     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20431       E = call->getCallee();
20432       diagID = diag::err_uncasted_call_of_unknown_any;
20433     } else {
20434       break;
20435     }
20436   }
20437 
20438   SourceLocation loc;
20439   NamedDecl *d;
20440   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20441     loc = ref->getLocation();
20442     d = ref->getDecl();
20443   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20444     loc = mem->getMemberLoc();
20445     d = mem->getMemberDecl();
20446   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20447     diagID = diag::err_uncasted_call_of_unknown_any;
20448     loc = msg->getSelectorStartLoc();
20449     d = msg->getMethodDecl();
20450     if (!d) {
20451       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20452         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20453         << orig->getSourceRange();
20454       return ExprError();
20455     }
20456   } else {
20457     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20458       << E->getSourceRange();
20459     return ExprError();
20460   }
20461 
20462   S.Diag(loc, diagID) << d << orig->getSourceRange();
20463 
20464   // Never recoverable.
20465   return ExprError();
20466 }
20467 
20468 /// Check for operands with placeholder types and complain if found.
20469 /// Returns ExprError() if there was an error and no recovery was possible.
20470 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
20471   if (!Context.isDependenceAllowed()) {
20472     // C cannot handle TypoExpr nodes on either side of a binop because it
20473     // doesn't handle dependent types properly, so make sure any TypoExprs have
20474     // been dealt with before checking the operands.
20475     ExprResult Result = CorrectDelayedTyposInExpr(E);
20476     if (!Result.isUsable()) return ExprError();
20477     E = Result.get();
20478   }
20479 
20480   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20481   if (!placeholderType) return E;
20482 
20483   switch (placeholderType->getKind()) {
20484 
20485   // Overloaded expressions.
20486   case BuiltinType::Overload: {
20487     // Try to resolve a single function template specialization.
20488     // This is obligatory.
20489     ExprResult Result = E;
20490     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
20491       return Result;
20492 
20493     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20494     // leaves Result unchanged on failure.
20495     Result = E;
20496     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
20497       return Result;
20498 
20499     // If that failed, try to recover with a call.
20500     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
20501                          /*complain*/ true);
20502     return Result;
20503   }
20504 
20505   // Bound member functions.
20506   case BuiltinType::BoundMember: {
20507     ExprResult result = E;
20508     const Expr *BME = E->IgnoreParens();
20509     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
20510     // Try to give a nicer diagnostic if it is a bound member that we recognize.
20511     if (isa<CXXPseudoDestructorExpr>(BME)) {
20512       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
20513     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
20514       if (ME->getMemberNameInfo().getName().getNameKind() ==
20515           DeclarationName::CXXDestructorName)
20516         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
20517     }
20518     tryToRecoverWithCall(result, PD,
20519                          /*complain*/ true);
20520     return result;
20521   }
20522 
20523   // ARC unbridged casts.
20524   case BuiltinType::ARCUnbridgedCast: {
20525     Expr *realCast = stripARCUnbridgedCast(E);
20526     diagnoseARCUnbridgedCast(realCast);
20527     return realCast;
20528   }
20529 
20530   // Expressions of unknown type.
20531   case BuiltinType::UnknownAny:
20532     return diagnoseUnknownAnyExpr(*this, E);
20533 
20534   // Pseudo-objects.
20535   case BuiltinType::PseudoObject:
20536     return checkPseudoObjectRValue(E);
20537 
20538   case BuiltinType::BuiltinFn: {
20539     // Accept __noop without parens by implicitly converting it to a call expr.
20540     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
20541     if (DRE) {
20542       auto *FD = cast<FunctionDecl>(DRE->getDecl());
20543       unsigned BuiltinID = FD->getBuiltinID();
20544       if (BuiltinID == Builtin::BI__noop) {
20545         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
20546                               CK_BuiltinFnToFnPtr)
20547                 .get();
20548         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
20549                                 VK_PRValue, SourceLocation(),
20550                                 FPOptionsOverride());
20551       }
20552 
20553       if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
20554         // Any use of these other than a direct call is ill-formed as of C++20,
20555         // because they are not addressable functions. In earlier language
20556         // modes, warn and force an instantiation of the real body.
20557         Diag(E->getBeginLoc(),
20558              getLangOpts().CPlusPlus20
20559                  ? diag::err_use_of_unaddressable_function
20560                  : diag::warn_cxx20_compat_use_of_unaddressable_function);
20561         if (FD->isImplicitlyInstantiable()) {
20562           // Require a definition here because a normal attempt at
20563           // instantiation for a builtin will be ignored, and we won't try
20564           // again later. We assume that the definition of the template
20565           // precedes this use.
20566           InstantiateFunctionDefinition(E->getBeginLoc(), FD,
20567                                         /*Recursive=*/false,
20568                                         /*DefinitionRequired=*/true,
20569                                         /*AtEndOfTU=*/false);
20570         }
20571         // Produce a properly-typed reference to the function.
20572         CXXScopeSpec SS;
20573         SS.Adopt(DRE->getQualifierLoc());
20574         TemplateArgumentListInfo TemplateArgs;
20575         DRE->copyTemplateArgumentsInto(TemplateArgs);
20576         return BuildDeclRefExpr(
20577             FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
20578             DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
20579             DRE->getTemplateKeywordLoc(),
20580             DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
20581       }
20582     }
20583 
20584     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
20585     return ExprError();
20586   }
20587 
20588   case BuiltinType::IncompleteMatrixIdx:
20589     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
20590              ->getRowIdx()
20591              ->getBeginLoc(),
20592          diag::err_matrix_incomplete_index);
20593     return ExprError();
20594 
20595   // Expressions of unknown type.
20596   case BuiltinType::OMPArraySection:
20597     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
20598     return ExprError();
20599 
20600   // Expressions of unknown type.
20601   case BuiltinType::OMPArrayShaping:
20602     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
20603 
20604   case BuiltinType::OMPIterator:
20605     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
20606 
20607   // Everything else should be impossible.
20608 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
20609   case BuiltinType::Id:
20610 #include "clang/Basic/OpenCLImageTypes.def"
20611 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
20612   case BuiltinType::Id:
20613 #include "clang/Basic/OpenCLExtensionTypes.def"
20614 #define SVE_TYPE(Name, Id, SingletonId) \
20615   case BuiltinType::Id:
20616 #include "clang/Basic/AArch64SVEACLETypes.def"
20617 #define PPC_VECTOR_TYPE(Name, Id, Size) \
20618   case BuiltinType::Id:
20619 #include "clang/Basic/PPCTypes.def"
20620 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20621 #include "clang/Basic/RISCVVTypes.def"
20622 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
20623 #define PLACEHOLDER_TYPE(Id, SingletonId)
20624 #include "clang/AST/BuiltinTypes.def"
20625     break;
20626   }
20627 
20628   llvm_unreachable("invalid placeholder type!");
20629 }
20630 
20631 bool Sema::CheckCaseExpression(Expr *E) {
20632   if (E->isTypeDependent())
20633     return true;
20634   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
20635     return E->getType()->isIntegralOrEnumerationType();
20636   return false;
20637 }
20638 
20639 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
20640 ExprResult
20641 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
20642   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
20643          "Unknown Objective-C Boolean value!");
20644   QualType BoolT = Context.ObjCBuiltinBoolTy;
20645   if (!Context.getBOOLDecl()) {
20646     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
20647                         Sema::LookupOrdinaryName);
20648     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
20649       NamedDecl *ND = Result.getFoundDecl();
20650       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
20651         Context.setBOOLDecl(TD);
20652     }
20653   }
20654   if (Context.getBOOLDecl())
20655     BoolT = Context.getBOOLType();
20656   return new (Context)
20657       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
20658 }
20659 
20660 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
20661     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
20662     SourceLocation RParen) {
20663   auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
20664     auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20665       return Spec.getPlatform() == Platform;
20666     });
20667     // Transcribe the "ios" availability check to "maccatalyst" when compiling
20668     // for "maccatalyst" if "maccatalyst" is not specified.
20669     if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
20670       Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20671         return Spec.getPlatform() == "ios";
20672       });
20673     }
20674     if (Spec == AvailSpecs.end())
20675       return None;
20676     return Spec->getVersion();
20677   };
20678 
20679   VersionTuple Version;
20680   if (auto MaybeVersion =
20681           FindSpecVersion(Context.getTargetInfo().getPlatformName()))
20682     Version = *MaybeVersion;
20683 
20684   // The use of `@available` in the enclosing context should be analyzed to
20685   // warn when it's used inappropriately (i.e. not if(@available)).
20686   if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
20687     Context->HasPotentialAvailabilityViolations = true;
20688 
20689   return new (Context)
20690       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
20691 }
20692 
20693 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
20694                                     ArrayRef<Expr *> SubExprs, QualType T) {
20695   if (!Context.getLangOpts().RecoveryAST)
20696     return ExprError();
20697 
20698   if (isSFINAEContext())
20699     return ExprError();
20700 
20701   if (T.isNull() || T->isUndeducedType() ||
20702       !Context.getLangOpts().RecoveryASTType)
20703     // We don't know the concrete type, fallback to dependent type.
20704     T = Context.DependentTy;
20705 
20706   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
20707 }
20708