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::Ordinary;
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::Ordinary,
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 =
3838           StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3839                                 StringLiteral::Ordinary,
3840                                 /*Pascal*/ false, StrTy, &TokLoc, 1);
3841       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3842     }
3843 
3844     case LOLR_Template: {
3845       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3846       // template), L is treated as a call fo the form
3847       //   operator "" X <'c1', 'c2', ... 'ck'>()
3848       // where n is the source character sequence c1 c2 ... ck.
3849       TemplateArgumentListInfo ExplicitArgs;
3850       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3851       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3852       llvm::APSInt Value(CharBits, CharIsUnsigned);
3853       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3854         Value = TokSpelling[I];
3855         TemplateArgument Arg(Context, Value, Context.CharTy);
3856         TemplateArgumentLocInfo ArgInfo;
3857         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3858       }
3859       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3860                                       &ExplicitArgs);
3861     }
3862     case LOLR_StringTemplatePack:
3863       llvm_unreachable("unexpected literal operator lookup result");
3864     }
3865   }
3866 
3867   Expr *Res;
3868 
3869   if (Literal.isFixedPointLiteral()) {
3870     QualType Ty;
3871 
3872     if (Literal.isAccum) {
3873       if (Literal.isHalf) {
3874         Ty = Context.ShortAccumTy;
3875       } else if (Literal.isLong) {
3876         Ty = Context.LongAccumTy;
3877       } else {
3878         Ty = Context.AccumTy;
3879       }
3880     } else if (Literal.isFract) {
3881       if (Literal.isHalf) {
3882         Ty = Context.ShortFractTy;
3883       } else if (Literal.isLong) {
3884         Ty = Context.LongFractTy;
3885       } else {
3886         Ty = Context.FractTy;
3887       }
3888     }
3889 
3890     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3891 
3892     bool isSigned = !Literal.isUnsigned;
3893     unsigned scale = Context.getFixedPointScale(Ty);
3894     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3895 
3896     llvm::APInt Val(bit_width, 0, isSigned);
3897     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3898     bool ValIsZero = Val.isZero() && !Overflowed;
3899 
3900     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3901     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3902       // Clause 6.4.4 - The value of a constant shall be in the range of
3903       // representable values for its type, with exception for constants of a
3904       // fract type with a value of exactly 1; such a constant shall denote
3905       // the maximal value for the type.
3906       --Val;
3907     else if (Val.ugt(MaxVal) || Overflowed)
3908       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3909 
3910     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3911                                               Tok.getLocation(), scale);
3912   } else if (Literal.isFloatingLiteral()) {
3913     QualType Ty;
3914     if (Literal.isHalf){
3915       if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3916         Ty = Context.HalfTy;
3917       else {
3918         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3919         return ExprError();
3920       }
3921     } else if (Literal.isFloat)
3922       Ty = Context.FloatTy;
3923     else if (Literal.isLong)
3924       Ty = Context.LongDoubleTy;
3925     else if (Literal.isFloat16)
3926       Ty = Context.Float16Ty;
3927     else if (Literal.isFloat128)
3928       Ty = Context.Float128Ty;
3929     else
3930       Ty = Context.DoubleTy;
3931 
3932     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3933 
3934     if (Ty == Context.DoubleTy) {
3935       if (getLangOpts().SinglePrecisionConstants) {
3936         if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3937           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3938         }
3939       } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3940                                              "cl_khr_fp64", getLangOpts())) {
3941         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3942         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3943             << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3944         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3945       }
3946     }
3947   } else if (!Literal.isIntegerLiteral()) {
3948     return ExprError();
3949   } else {
3950     QualType Ty;
3951 
3952     // 'long long' is a C99 or C++11 feature.
3953     if (!getLangOpts().C99 && Literal.isLongLong) {
3954       if (getLangOpts().CPlusPlus)
3955         Diag(Tok.getLocation(),
3956              getLangOpts().CPlusPlus11 ?
3957              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3958       else
3959         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3960     }
3961 
3962     // 'z/uz' literals are a C++2b feature.
3963     if (Literal.isSizeT)
3964       Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3965                                   ? getLangOpts().CPlusPlus2b
3966                                         ? diag::warn_cxx20_compat_size_t_suffix
3967                                         : diag::ext_cxx2b_size_t_suffix
3968                                   : diag::err_cxx2b_size_t_suffix);
3969 
3970     // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3971     // but we do not currently support the suffix in C++ mode because it's not
3972     // entirely clear whether WG21 will prefer this suffix to return a library
3973     // type such as std::bit_int instead of returning a _BitInt.
3974     if (Literal.isBitInt && !getLangOpts().CPlusPlus)
3975       PP.Diag(Tok.getLocation(), getLangOpts().C2x
3976                                      ? diag::warn_c2x_compat_bitint_suffix
3977                                      : diag::ext_c2x_bitint_suffix);
3978 
3979     // Get the value in the widest-possible width. What is "widest" depends on
3980     // whether the literal is a bit-precise integer or not. For a bit-precise
3981     // integer type, try to scan the source to determine how many bits are
3982     // needed to represent the value. This may seem a bit expensive, but trying
3983     // to get the integer value from an overly-wide APInt is *extremely*
3984     // expensive, so the naive approach of assuming
3985     // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3986     unsigned BitsNeeded =
3987         Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3988                                Literal.getLiteralDigits(), Literal.getRadix())
3989                          : Context.getTargetInfo().getIntMaxTWidth();
3990     llvm::APInt ResultVal(BitsNeeded, 0);
3991 
3992     if (Literal.GetIntegerValue(ResultVal)) {
3993       // If this value didn't fit into uintmax_t, error and force to ull.
3994       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3995           << /* Unsigned */ 1;
3996       Ty = Context.UnsignedLongLongTy;
3997       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3998              "long long is not intmax_t?");
3999     } else {
4000       // If this value fits into a ULL, try to figure out what else it fits into
4001       // according to the rules of C99 6.4.4.1p5.
4002 
4003       // Octal, Hexadecimal, and integers with a U suffix are allowed to
4004       // be an unsigned int.
4005       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4006 
4007       // Check from smallest to largest, picking the smallest type we can.
4008       unsigned Width = 0;
4009 
4010       // Microsoft specific integer suffixes are explicitly sized.
4011       if (Literal.MicrosoftInteger) {
4012         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4013           Width = 8;
4014           Ty = Context.CharTy;
4015         } else {
4016           Width = Literal.MicrosoftInteger;
4017           Ty = Context.getIntTypeForBitwidth(Width,
4018                                              /*Signed=*/!Literal.isUnsigned);
4019         }
4020       }
4021 
4022       // Bit-precise integer literals are automagically-sized based on the
4023       // width required by the literal.
4024       if (Literal.isBitInt) {
4025         // The signed version has one more bit for the sign value. There are no
4026         // zero-width bit-precise integers, even if the literal value is 0.
4027         Width = std::max(ResultVal.getActiveBits(), 1u) +
4028                 (Literal.isUnsigned ? 0u : 1u);
4029 
4030         // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4031         // and reset the type to the largest supported width.
4032         unsigned int MaxBitIntWidth =
4033             Context.getTargetInfo().getMaxBitIntWidth();
4034         if (Width > MaxBitIntWidth) {
4035           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4036               << Literal.isUnsigned;
4037           Width = MaxBitIntWidth;
4038         }
4039 
4040         // Reset the result value to the smaller APInt and select the correct
4041         // type to be used. Note, we zext even for signed values because the
4042         // literal itself is always an unsigned value (a preceeding - is a
4043         // unary operator, not part of the literal).
4044         ResultVal = ResultVal.zextOrTrunc(Width);
4045         Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4046       }
4047 
4048       // Check C++2b size_t literals.
4049       if (Literal.isSizeT) {
4050         assert(!Literal.MicrosoftInteger &&
4051                "size_t literals can't be Microsoft literals");
4052         unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4053             Context.getTargetInfo().getSizeType());
4054 
4055         // Does it fit in size_t?
4056         if (ResultVal.isIntN(SizeTSize)) {
4057           // Does it fit in ssize_t?
4058           if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4059             Ty = Context.getSignedSizeType();
4060           else if (AllowUnsigned)
4061             Ty = Context.getSizeType();
4062           Width = SizeTSize;
4063         }
4064       }
4065 
4066       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4067           !Literal.isSizeT) {
4068         // Are int/unsigned possibilities?
4069         unsigned IntSize = Context.getTargetInfo().getIntWidth();
4070 
4071         // Does it fit in a unsigned int?
4072         if (ResultVal.isIntN(IntSize)) {
4073           // Does it fit in a signed int?
4074           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4075             Ty = Context.IntTy;
4076           else if (AllowUnsigned)
4077             Ty = Context.UnsignedIntTy;
4078           Width = IntSize;
4079         }
4080       }
4081 
4082       // Are long/unsigned long possibilities?
4083       if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4084         unsigned LongSize = Context.getTargetInfo().getLongWidth();
4085 
4086         // Does it fit in a unsigned long?
4087         if (ResultVal.isIntN(LongSize)) {
4088           // Does it fit in a signed long?
4089           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4090             Ty = Context.LongTy;
4091           else if (AllowUnsigned)
4092             Ty = Context.UnsignedLongTy;
4093           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4094           // is compatible.
4095           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4096             const unsigned LongLongSize =
4097                 Context.getTargetInfo().getLongLongWidth();
4098             Diag(Tok.getLocation(),
4099                  getLangOpts().CPlusPlus
4100                      ? Literal.isLong
4101                            ? diag::warn_old_implicitly_unsigned_long_cxx
4102                            : /*C++98 UB*/ diag::
4103                                  ext_old_implicitly_unsigned_long_cxx
4104                      : diag::warn_old_implicitly_unsigned_long)
4105                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4106                                             : /*will be ill-formed*/ 1);
4107             Ty = Context.UnsignedLongTy;
4108           }
4109           Width = LongSize;
4110         }
4111       }
4112 
4113       // Check long long if needed.
4114       if (Ty.isNull() && !Literal.isSizeT) {
4115         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4116 
4117         // Does it fit in a unsigned long long?
4118         if (ResultVal.isIntN(LongLongSize)) {
4119           // Does it fit in a signed long long?
4120           // To be compatible with MSVC, hex integer literals ending with the
4121           // LL or i64 suffix are always signed in Microsoft mode.
4122           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4123               (getLangOpts().MSVCCompat && Literal.isLongLong)))
4124             Ty = Context.LongLongTy;
4125           else if (AllowUnsigned)
4126             Ty = Context.UnsignedLongLongTy;
4127           Width = LongLongSize;
4128         }
4129       }
4130 
4131       // If we still couldn't decide a type, we either have 'size_t' literal
4132       // that is out of range, or a decimal literal that does not fit in a
4133       // signed long long and has no U suffix.
4134       if (Ty.isNull()) {
4135         if (Literal.isSizeT)
4136           Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4137               << Literal.isUnsigned;
4138         else
4139           Diag(Tok.getLocation(),
4140                diag::ext_integer_literal_too_large_for_signed);
4141         Ty = Context.UnsignedLongLongTy;
4142         Width = Context.getTargetInfo().getLongLongWidth();
4143       }
4144 
4145       if (ResultVal.getBitWidth() != Width)
4146         ResultVal = ResultVal.trunc(Width);
4147     }
4148     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4149   }
4150 
4151   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4152   if (Literal.isImaginary) {
4153     Res = new (Context) ImaginaryLiteral(Res,
4154                                         Context.getComplexType(Res->getType()));
4155 
4156     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4157   }
4158   return Res;
4159 }
4160 
4161 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4162   assert(E && "ActOnParenExpr() missing expr");
4163   QualType ExprTy = E->getType();
4164   if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4165       !E->isLValue() && ExprTy->hasFloatingRepresentation())
4166     return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4167   return new (Context) ParenExpr(L, R, E);
4168 }
4169 
4170 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4171                                          SourceLocation Loc,
4172                                          SourceRange ArgRange) {
4173   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4174   // scalar or vector data type argument..."
4175   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4176   // type (C99 6.2.5p18) or void.
4177   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4178     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4179       << T << ArgRange;
4180     return true;
4181   }
4182 
4183   assert((T->isVoidType() || !T->isIncompleteType()) &&
4184          "Scalar types should always be complete");
4185   return false;
4186 }
4187 
4188 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4189                                            SourceLocation Loc,
4190                                            SourceRange ArgRange,
4191                                            UnaryExprOrTypeTrait TraitKind) {
4192   // Invalid types must be hard errors for SFINAE in C++.
4193   if (S.LangOpts.CPlusPlus)
4194     return true;
4195 
4196   // C99 6.5.3.4p1:
4197   if (T->isFunctionType() &&
4198       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4199        TraitKind == UETT_PreferredAlignOf)) {
4200     // sizeof(function)/alignof(function) is allowed as an extension.
4201     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4202         << getTraitSpelling(TraitKind) << ArgRange;
4203     return false;
4204   }
4205 
4206   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4207   // this is an error (OpenCL v1.1 s6.3.k)
4208   if (T->isVoidType()) {
4209     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4210                                         : diag::ext_sizeof_alignof_void_type;
4211     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4212     return false;
4213   }
4214 
4215   return true;
4216 }
4217 
4218 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4219                                              SourceLocation Loc,
4220                                              SourceRange ArgRange,
4221                                              UnaryExprOrTypeTrait TraitKind) {
4222   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4223   // runtime doesn't allow it.
4224   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4225     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4226       << T << (TraitKind == UETT_SizeOf)
4227       << ArgRange;
4228     return true;
4229   }
4230 
4231   return false;
4232 }
4233 
4234 /// Check whether E is a pointer from a decayed array type (the decayed
4235 /// pointer type is equal to T) and emit a warning if it is.
4236 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4237                                      Expr *E) {
4238   // Don't warn if the operation changed the type.
4239   if (T != E->getType())
4240     return;
4241 
4242   // Now look for array decays.
4243   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4244   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4245     return;
4246 
4247   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4248                                              << ICE->getType()
4249                                              << ICE->getSubExpr()->getType();
4250 }
4251 
4252 /// Check the constraints on expression operands to unary type expression
4253 /// and type traits.
4254 ///
4255 /// Completes any types necessary and validates the constraints on the operand
4256 /// expression. The logic mostly mirrors the type-based overload, but may modify
4257 /// the expression as it completes the type for that expression through template
4258 /// instantiation, etc.
4259 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4260                                             UnaryExprOrTypeTrait ExprKind) {
4261   QualType ExprTy = E->getType();
4262   assert(!ExprTy->isReferenceType());
4263 
4264   bool IsUnevaluatedOperand =
4265       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4266        ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4267   if (IsUnevaluatedOperand) {
4268     ExprResult Result = CheckUnevaluatedOperand(E);
4269     if (Result.isInvalid())
4270       return true;
4271     E = Result.get();
4272   }
4273 
4274   // The operand for sizeof and alignof is in an unevaluated expression context,
4275   // so side effects could result in unintended consequences.
4276   // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4277   // used to build SFINAE gadgets.
4278   // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4279   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4280       !E->isInstantiationDependent() &&
4281       !E->getType()->isVariableArrayType() &&
4282       E->HasSideEffects(Context, false))
4283     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4284 
4285   if (ExprKind == UETT_VecStep)
4286     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4287                                         E->getSourceRange());
4288 
4289   // Explicitly list some types as extensions.
4290   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4291                                       E->getSourceRange(), ExprKind))
4292     return false;
4293 
4294   // 'alignof' applied to an expression only requires the base element type of
4295   // the expression to be complete. 'sizeof' requires the expression's type to
4296   // be complete (and will attempt to complete it if it's an array of unknown
4297   // bound).
4298   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4299     if (RequireCompleteSizedType(
4300             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4301             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4302             getTraitSpelling(ExprKind), E->getSourceRange()))
4303       return true;
4304   } else {
4305     if (RequireCompleteSizedExprType(
4306             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4307             getTraitSpelling(ExprKind), E->getSourceRange()))
4308       return true;
4309   }
4310 
4311   // Completing the expression's type may have changed it.
4312   ExprTy = E->getType();
4313   assert(!ExprTy->isReferenceType());
4314 
4315   if (ExprTy->isFunctionType()) {
4316     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4317         << getTraitSpelling(ExprKind) << E->getSourceRange();
4318     return true;
4319   }
4320 
4321   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4322                                        E->getSourceRange(), ExprKind))
4323     return true;
4324 
4325   if (ExprKind == UETT_SizeOf) {
4326     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4327       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4328         QualType OType = PVD->getOriginalType();
4329         QualType Type = PVD->getType();
4330         if (Type->isPointerType() && OType->isArrayType()) {
4331           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4332             << Type << OType;
4333           Diag(PVD->getLocation(), diag::note_declared_at);
4334         }
4335       }
4336     }
4337 
4338     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4339     // decays into a pointer and returns an unintended result. This is most
4340     // likely a typo for "sizeof(array) op x".
4341     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4342       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4343                                BO->getLHS());
4344       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4345                                BO->getRHS());
4346     }
4347   }
4348 
4349   return false;
4350 }
4351 
4352 /// Check the constraints on operands to unary expression and type
4353 /// traits.
4354 ///
4355 /// This will complete any types necessary, and validate the various constraints
4356 /// on those operands.
4357 ///
4358 /// The UsualUnaryConversions() function is *not* called by this routine.
4359 /// C99 6.3.2.1p[2-4] all state:
4360 ///   Except when it is the operand of the sizeof operator ...
4361 ///
4362 /// C++ [expr.sizeof]p4
4363 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4364 ///   standard conversions are not applied to the operand of sizeof.
4365 ///
4366 /// This policy is followed for all of the unary trait expressions.
4367 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4368                                             SourceLocation OpLoc,
4369                                             SourceRange ExprRange,
4370                                             UnaryExprOrTypeTrait ExprKind) {
4371   if (ExprType->isDependentType())
4372     return false;
4373 
4374   // C++ [expr.sizeof]p2:
4375   //     When applied to a reference or a reference type, the result
4376   //     is the size of the referenced type.
4377   // C++11 [expr.alignof]p3:
4378   //     When alignof is applied to a reference type, the result
4379   //     shall be the alignment of the referenced type.
4380   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4381     ExprType = Ref->getPointeeType();
4382 
4383   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4384   //   When alignof or _Alignof is applied to an array type, the result
4385   //   is the alignment of the element type.
4386   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4387       ExprKind == UETT_OpenMPRequiredSimdAlign)
4388     ExprType = Context.getBaseElementType(ExprType);
4389 
4390   if (ExprKind == UETT_VecStep)
4391     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4392 
4393   // Explicitly list some types as extensions.
4394   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4395                                       ExprKind))
4396     return false;
4397 
4398   if (RequireCompleteSizedType(
4399           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4400           getTraitSpelling(ExprKind), ExprRange))
4401     return true;
4402 
4403   if (ExprType->isFunctionType()) {
4404     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4405         << getTraitSpelling(ExprKind) << ExprRange;
4406     return true;
4407   }
4408 
4409   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4410                                        ExprKind))
4411     return true;
4412 
4413   return false;
4414 }
4415 
4416 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4417   // Cannot know anything else if the expression is dependent.
4418   if (E->isTypeDependent())
4419     return false;
4420 
4421   if (E->getObjectKind() == OK_BitField) {
4422     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4423        << 1 << E->getSourceRange();
4424     return true;
4425   }
4426 
4427   ValueDecl *D = nullptr;
4428   Expr *Inner = E->IgnoreParens();
4429   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4430     D = DRE->getDecl();
4431   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4432     D = ME->getMemberDecl();
4433   }
4434 
4435   // If it's a field, require the containing struct to have a
4436   // complete definition so that we can compute the layout.
4437   //
4438   // This can happen in C++11 onwards, either by naming the member
4439   // in a way that is not transformed into a member access expression
4440   // (in an unevaluated operand, for instance), or by naming the member
4441   // in a trailing-return-type.
4442   //
4443   // For the record, since __alignof__ on expressions is a GCC
4444   // extension, GCC seems to permit this but always gives the
4445   // nonsensical answer 0.
4446   //
4447   // We don't really need the layout here --- we could instead just
4448   // directly check for all the appropriate alignment-lowing
4449   // attributes --- but that would require duplicating a lot of
4450   // logic that just isn't worth duplicating for such a marginal
4451   // use-case.
4452   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4453     // Fast path this check, since we at least know the record has a
4454     // definition if we can find a member of it.
4455     if (!FD->getParent()->isCompleteDefinition()) {
4456       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4457         << E->getSourceRange();
4458       return true;
4459     }
4460 
4461     // Otherwise, if it's a field, and the field doesn't have
4462     // reference type, then it must have a complete type (or be a
4463     // flexible array member, which we explicitly want to
4464     // white-list anyway), which makes the following checks trivial.
4465     if (!FD->getType()->isReferenceType())
4466       return false;
4467   }
4468 
4469   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4470 }
4471 
4472 bool Sema::CheckVecStepExpr(Expr *E) {
4473   E = E->IgnoreParens();
4474 
4475   // Cannot know anything else if the expression is dependent.
4476   if (E->isTypeDependent())
4477     return false;
4478 
4479   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4480 }
4481 
4482 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4483                                         CapturingScopeInfo *CSI) {
4484   assert(T->isVariablyModifiedType());
4485   assert(CSI != nullptr);
4486 
4487   // We're going to walk down into the type and look for VLA expressions.
4488   do {
4489     const Type *Ty = T.getTypePtr();
4490     switch (Ty->getTypeClass()) {
4491 #define TYPE(Class, Base)
4492 #define ABSTRACT_TYPE(Class, Base)
4493 #define NON_CANONICAL_TYPE(Class, Base)
4494 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4495 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4496 #include "clang/AST/TypeNodes.inc"
4497       T = QualType();
4498       break;
4499     // These types are never variably-modified.
4500     case Type::Builtin:
4501     case Type::Complex:
4502     case Type::Vector:
4503     case Type::ExtVector:
4504     case Type::ConstantMatrix:
4505     case Type::Record:
4506     case Type::Enum:
4507     case Type::Elaborated:
4508     case Type::TemplateSpecialization:
4509     case Type::ObjCObject:
4510     case Type::ObjCInterface:
4511     case Type::ObjCObjectPointer:
4512     case Type::ObjCTypeParam:
4513     case Type::Pipe:
4514     case Type::BitInt:
4515       llvm_unreachable("type class is never variably-modified!");
4516     case Type::Adjusted:
4517       T = cast<AdjustedType>(Ty)->getOriginalType();
4518       break;
4519     case Type::Decayed:
4520       T = cast<DecayedType>(Ty)->getPointeeType();
4521       break;
4522     case Type::Pointer:
4523       T = cast<PointerType>(Ty)->getPointeeType();
4524       break;
4525     case Type::BlockPointer:
4526       T = cast<BlockPointerType>(Ty)->getPointeeType();
4527       break;
4528     case Type::LValueReference:
4529     case Type::RValueReference:
4530       T = cast<ReferenceType>(Ty)->getPointeeType();
4531       break;
4532     case Type::MemberPointer:
4533       T = cast<MemberPointerType>(Ty)->getPointeeType();
4534       break;
4535     case Type::ConstantArray:
4536     case Type::IncompleteArray:
4537       // Losing element qualification here is fine.
4538       T = cast<ArrayType>(Ty)->getElementType();
4539       break;
4540     case Type::VariableArray: {
4541       // Losing element qualification here is fine.
4542       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4543 
4544       // Unknown size indication requires no size computation.
4545       // Otherwise, evaluate and record it.
4546       auto Size = VAT->getSizeExpr();
4547       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4548           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4549         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4550 
4551       T = VAT->getElementType();
4552       break;
4553     }
4554     case Type::FunctionProto:
4555     case Type::FunctionNoProto:
4556       T = cast<FunctionType>(Ty)->getReturnType();
4557       break;
4558     case Type::Paren:
4559     case Type::TypeOf:
4560     case Type::UnaryTransform:
4561     case Type::Attributed:
4562     case Type::BTFTagAttributed:
4563     case Type::SubstTemplateTypeParm:
4564     case Type::MacroQualified:
4565       // Keep walking after single level desugaring.
4566       T = T.getSingleStepDesugaredType(Context);
4567       break;
4568     case Type::Typedef:
4569       T = cast<TypedefType>(Ty)->desugar();
4570       break;
4571     case Type::Decltype:
4572       T = cast<DecltypeType>(Ty)->desugar();
4573       break;
4574     case Type::Using:
4575       T = cast<UsingType>(Ty)->desugar();
4576       break;
4577     case Type::Auto:
4578     case Type::DeducedTemplateSpecialization:
4579       T = cast<DeducedType>(Ty)->getDeducedType();
4580       break;
4581     case Type::TypeOfExpr:
4582       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4583       break;
4584     case Type::Atomic:
4585       T = cast<AtomicType>(Ty)->getValueType();
4586       break;
4587     }
4588   } while (!T.isNull() && T->isVariablyModifiedType());
4589 }
4590 
4591 /// Build a sizeof or alignof expression given a type operand.
4592 ExprResult
4593 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4594                                      SourceLocation OpLoc,
4595                                      UnaryExprOrTypeTrait ExprKind,
4596                                      SourceRange R) {
4597   if (!TInfo)
4598     return ExprError();
4599 
4600   QualType T = TInfo->getType();
4601 
4602   if (!T->isDependentType() &&
4603       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4604     return ExprError();
4605 
4606   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4607     if (auto *TT = T->getAs<TypedefType>()) {
4608       for (auto I = FunctionScopes.rbegin(),
4609                 E = std::prev(FunctionScopes.rend());
4610            I != E; ++I) {
4611         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4612         if (CSI == nullptr)
4613           break;
4614         DeclContext *DC = nullptr;
4615         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4616           DC = LSI->CallOperator;
4617         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4618           DC = CRSI->TheCapturedDecl;
4619         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4620           DC = BSI->TheDecl;
4621         if (DC) {
4622           if (DC->containsDecl(TT->getDecl()))
4623             break;
4624           captureVariablyModifiedType(Context, T, CSI);
4625         }
4626       }
4627     }
4628   }
4629 
4630   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4631   if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4632       TInfo->getType()->isVariablyModifiedType())
4633     TInfo = TransformToPotentiallyEvaluated(TInfo);
4634 
4635   return new (Context) UnaryExprOrTypeTraitExpr(
4636       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4637 }
4638 
4639 /// Build a sizeof or alignof expression given an expression
4640 /// operand.
4641 ExprResult
4642 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4643                                      UnaryExprOrTypeTrait ExprKind) {
4644   ExprResult PE = CheckPlaceholderExpr(E);
4645   if (PE.isInvalid())
4646     return ExprError();
4647 
4648   E = PE.get();
4649 
4650   // Verify that the operand is valid.
4651   bool isInvalid = false;
4652   if (E->isTypeDependent()) {
4653     // Delay type-checking for type-dependent expressions.
4654   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4655     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4656   } else if (ExprKind == UETT_VecStep) {
4657     isInvalid = CheckVecStepExpr(E);
4658   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4659       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4660       isInvalid = true;
4661   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4662     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4663     isInvalid = true;
4664   } else {
4665     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4666   }
4667 
4668   if (isInvalid)
4669     return ExprError();
4670 
4671   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4672     PE = TransformToPotentiallyEvaluated(E);
4673     if (PE.isInvalid()) return ExprError();
4674     E = PE.get();
4675   }
4676 
4677   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4678   return new (Context) UnaryExprOrTypeTraitExpr(
4679       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4680 }
4681 
4682 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4683 /// expr and the same for @c alignof and @c __alignof
4684 /// Note that the ArgRange is invalid if isType is false.
4685 ExprResult
4686 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4687                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4688                                     void *TyOrEx, SourceRange ArgRange) {
4689   // If error parsing type, ignore.
4690   if (!TyOrEx) return ExprError();
4691 
4692   if (IsType) {
4693     TypeSourceInfo *TInfo;
4694     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4695     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4696   }
4697 
4698   Expr *ArgEx = (Expr *)TyOrEx;
4699   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4700   return Result;
4701 }
4702 
4703 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4704                                      bool IsReal) {
4705   if (V.get()->isTypeDependent())
4706     return S.Context.DependentTy;
4707 
4708   // _Real and _Imag are only l-values for normal l-values.
4709   if (V.get()->getObjectKind() != OK_Ordinary) {
4710     V = S.DefaultLvalueConversion(V.get());
4711     if (V.isInvalid())
4712       return QualType();
4713   }
4714 
4715   // These operators return the element type of a complex type.
4716   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4717     return CT->getElementType();
4718 
4719   // Otherwise they pass through real integer and floating point types here.
4720   if (V.get()->getType()->isArithmeticType())
4721     return V.get()->getType();
4722 
4723   // Test for placeholders.
4724   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4725   if (PR.isInvalid()) return QualType();
4726   if (PR.get() != V.get()) {
4727     V = PR;
4728     return CheckRealImagOperand(S, V, Loc, IsReal);
4729   }
4730 
4731   // Reject anything else.
4732   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4733     << (IsReal ? "__real" : "__imag");
4734   return QualType();
4735 }
4736 
4737 
4738 
4739 ExprResult
4740 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4741                           tok::TokenKind Kind, Expr *Input) {
4742   UnaryOperatorKind Opc;
4743   switch (Kind) {
4744   default: llvm_unreachable("Unknown unary op!");
4745   case tok::plusplus:   Opc = UO_PostInc; break;
4746   case tok::minusminus: Opc = UO_PostDec; break;
4747   }
4748 
4749   // Since this might is a postfix expression, get rid of ParenListExprs.
4750   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4751   if (Result.isInvalid()) return ExprError();
4752   Input = Result.get();
4753 
4754   return BuildUnaryOp(S, OpLoc, Opc, Input);
4755 }
4756 
4757 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4758 ///
4759 /// \return true on error
4760 static bool checkArithmeticOnObjCPointer(Sema &S,
4761                                          SourceLocation opLoc,
4762                                          Expr *op) {
4763   assert(op->getType()->isObjCObjectPointerType());
4764   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4765       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4766     return false;
4767 
4768   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4769     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4770     << op->getSourceRange();
4771   return true;
4772 }
4773 
4774 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4775   auto *BaseNoParens = Base->IgnoreParens();
4776   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4777     return MSProp->getPropertyDecl()->getType()->isArrayType();
4778   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4779 }
4780 
4781 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4782 // Typically this is DependentTy, but can sometimes be more precise.
4783 //
4784 // There are cases when we could determine a non-dependent type:
4785 //  - LHS and RHS may have non-dependent types despite being type-dependent
4786 //    (e.g. unbounded array static members of the current instantiation)
4787 //  - one may be a dependent-sized array with known element type
4788 //  - one may be a dependent-typed valid index (enum in current instantiation)
4789 //
4790 // We *always* return a dependent type, in such cases it is DependentTy.
4791 // This avoids creating type-dependent expressions with non-dependent types.
4792 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4793 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4794                                                const ASTContext &Ctx) {
4795   assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4796   QualType LTy = LHS->getType(), RTy = RHS->getType();
4797   QualType Result = Ctx.DependentTy;
4798   if (RTy->isIntegralOrUnscopedEnumerationType()) {
4799     if (const PointerType *PT = LTy->getAs<PointerType>())
4800       Result = PT->getPointeeType();
4801     else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4802       Result = AT->getElementType();
4803   } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4804     if (const PointerType *PT = RTy->getAs<PointerType>())
4805       Result = PT->getPointeeType();
4806     else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4807       Result = AT->getElementType();
4808   }
4809   // Ensure we return a dependent type.
4810   return Result->isDependentType() ? Result : Ctx.DependentTy;
4811 }
4812 
4813 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4814 
4815 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4816                                          SourceLocation lbLoc,
4817                                          MultiExprArg ArgExprs,
4818                                          SourceLocation rbLoc) {
4819 
4820   if (base && !base->getType().isNull() &&
4821       base->hasPlaceholderType(BuiltinType::OMPArraySection))
4822     return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4823                                     SourceLocation(), /*Length*/ nullptr,
4824                                     /*Stride=*/nullptr, rbLoc);
4825 
4826   // Since this might be a postfix expression, get rid of ParenListExprs.
4827   if (isa<ParenListExpr>(base)) {
4828     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4829     if (result.isInvalid())
4830       return ExprError();
4831     base = result.get();
4832   }
4833 
4834   // Check if base and idx form a MatrixSubscriptExpr.
4835   //
4836   // Helper to check for comma expressions, which are not allowed as indices for
4837   // matrix subscript expressions.
4838   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4839     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4840       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4841           << SourceRange(base->getBeginLoc(), rbLoc);
4842       return true;
4843     }
4844     return false;
4845   };
4846   // The matrix subscript operator ([][])is considered a single operator.
4847   // Separating the index expressions by parenthesis is not allowed.
4848   if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4849       !isa<MatrixSubscriptExpr>(base)) {
4850     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4851         << SourceRange(base->getBeginLoc(), rbLoc);
4852     return ExprError();
4853   }
4854   // If the base is a MatrixSubscriptExpr, try to create a new
4855   // MatrixSubscriptExpr.
4856   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4857   if (matSubscriptE) {
4858     assert(ArgExprs.size() == 1);
4859     if (CheckAndReportCommaError(ArgExprs.front()))
4860       return ExprError();
4861 
4862     assert(matSubscriptE->isIncomplete() &&
4863            "base has to be an incomplete matrix subscript");
4864     return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4865                                             matSubscriptE->getRowIdx(),
4866                                             ArgExprs.front(), rbLoc);
4867   }
4868 
4869   // Handle any non-overload placeholder types in the base and index
4870   // expressions.  We can't handle overloads here because the other
4871   // operand might be an overloadable type, in which case the overload
4872   // resolution for the operator overload should get the first crack
4873   // at the overload.
4874   bool IsMSPropertySubscript = false;
4875   if (base->getType()->isNonOverloadPlaceholderType()) {
4876     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4877     if (!IsMSPropertySubscript) {
4878       ExprResult result = CheckPlaceholderExpr(base);
4879       if (result.isInvalid())
4880         return ExprError();
4881       base = result.get();
4882     }
4883   }
4884 
4885   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4886   if (base->getType()->isMatrixType()) {
4887     assert(ArgExprs.size() == 1);
4888     if (CheckAndReportCommaError(ArgExprs.front()))
4889       return ExprError();
4890 
4891     return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4892                                             rbLoc);
4893   }
4894 
4895   if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4896     Expr *idx = ArgExprs[0];
4897     if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4898         (isa<CXXOperatorCallExpr>(idx) &&
4899          cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4900       Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4901           << SourceRange(base->getBeginLoc(), rbLoc);
4902     }
4903   }
4904 
4905   if (ArgExprs.size() == 1 &&
4906       ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4907     ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4908     if (result.isInvalid())
4909       return ExprError();
4910     ArgExprs[0] = result.get();
4911   } else {
4912     if (checkArgsForPlaceholders(*this, ArgExprs))
4913       return ExprError();
4914   }
4915 
4916   // Build an unanalyzed expression if either operand is type-dependent.
4917   if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4918       (base->isTypeDependent() ||
4919        Expr::hasAnyTypeDependentArguments(ArgExprs))) {
4920     return new (Context) ArraySubscriptExpr(
4921         base, ArgExprs.front(),
4922         getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4923         VK_LValue, OK_Ordinary, rbLoc);
4924   }
4925 
4926   // MSDN, property (C++)
4927   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4928   // This attribute can also be used in the declaration of an empty array in a
4929   // class or structure definition. For example:
4930   // __declspec(property(get=GetX, put=PutX)) int x[];
4931   // The above statement indicates that x[] can be used with one or more array
4932   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4933   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4934   if (IsMSPropertySubscript) {
4935     assert(ArgExprs.size() == 1);
4936     // Build MS property subscript expression if base is MS property reference
4937     // or MS property subscript.
4938     return new (Context)
4939         MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4940                                 VK_LValue, OK_Ordinary, rbLoc);
4941   }
4942 
4943   // Use C++ overloaded-operator rules if either operand has record
4944   // type.  The spec says to do this if either type is *overloadable*,
4945   // but enum types can't declare subscript operators or conversion
4946   // operators, so there's nothing interesting for overload resolution
4947   // to do if there aren't any record types involved.
4948   //
4949   // ObjC pointers have their own subscripting logic that is not tied
4950   // to overload resolution and so should not take this path.
4951   if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4952       ((base->getType()->isRecordType() ||
4953         (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) {
4954     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4955   }
4956 
4957   ExprResult Res =
4958       CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4959 
4960   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4961     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4962 
4963   return Res;
4964 }
4965 
4966 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4967   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4968   InitializationKind Kind =
4969       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4970   InitializationSequence InitSeq(*this, Entity, Kind, E);
4971   return InitSeq.Perform(*this, Entity, Kind, E);
4972 }
4973 
4974 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4975                                                   Expr *ColumnIdx,
4976                                                   SourceLocation RBLoc) {
4977   ExprResult BaseR = CheckPlaceholderExpr(Base);
4978   if (BaseR.isInvalid())
4979     return BaseR;
4980   Base = BaseR.get();
4981 
4982   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4983   if (RowR.isInvalid())
4984     return RowR;
4985   RowIdx = RowR.get();
4986 
4987   if (!ColumnIdx)
4988     return new (Context) MatrixSubscriptExpr(
4989         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4990 
4991   // Build an unanalyzed expression if any of the operands is type-dependent.
4992   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4993       ColumnIdx->isTypeDependent())
4994     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4995                                              Context.DependentTy, RBLoc);
4996 
4997   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4998   if (ColumnR.isInvalid())
4999     return ColumnR;
5000   ColumnIdx = ColumnR.get();
5001 
5002   // Check that IndexExpr is an integer expression. If it is a constant
5003   // expression, check that it is less than Dim (= the number of elements in the
5004   // corresponding dimension).
5005   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5006                           bool IsColumnIdx) -> Expr * {
5007     if (!IndexExpr->getType()->isIntegerType() &&
5008         !IndexExpr->isTypeDependent()) {
5009       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5010           << IsColumnIdx;
5011       return nullptr;
5012     }
5013 
5014     if (Optional<llvm::APSInt> Idx =
5015             IndexExpr->getIntegerConstantExpr(Context)) {
5016       if ((*Idx < 0 || *Idx >= Dim)) {
5017         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5018             << IsColumnIdx << Dim;
5019         return nullptr;
5020       }
5021     }
5022 
5023     ExprResult ConvExpr =
5024         tryConvertExprToType(IndexExpr, Context.getSizeType());
5025     assert(!ConvExpr.isInvalid() &&
5026            "should be able to convert any integer type to size type");
5027     return ConvExpr.get();
5028   };
5029 
5030   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5031   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5032   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5033   if (!RowIdx || !ColumnIdx)
5034     return ExprError();
5035 
5036   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5037                                            MTy->getElementType(), RBLoc);
5038 }
5039 
5040 void Sema::CheckAddressOfNoDeref(const Expr *E) {
5041   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5042   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5043 
5044   // For expressions like `&(*s).b`, the base is recorded and what should be
5045   // checked.
5046   const MemberExpr *Member = nullptr;
5047   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5048     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5049 
5050   LastRecord.PossibleDerefs.erase(StrippedExpr);
5051 }
5052 
5053 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5054   if (isUnevaluatedContext())
5055     return;
5056 
5057   QualType ResultTy = E->getType();
5058   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5059 
5060   // Bail if the element is an array since it is not memory access.
5061   if (isa<ArrayType>(ResultTy))
5062     return;
5063 
5064   if (ResultTy->hasAttr(attr::NoDeref)) {
5065     LastRecord.PossibleDerefs.insert(E);
5066     return;
5067   }
5068 
5069   // Check if the base type is a pointer to a member access of a struct
5070   // marked with noderef.
5071   const Expr *Base = E->getBase();
5072   QualType BaseTy = Base->getType();
5073   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5074     // Not a pointer access
5075     return;
5076 
5077   const MemberExpr *Member = nullptr;
5078   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5079          Member->isArrow())
5080     Base = Member->getBase();
5081 
5082   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5083     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5084       LastRecord.PossibleDerefs.insert(E);
5085   }
5086 }
5087 
5088 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5089                                           Expr *LowerBound,
5090                                           SourceLocation ColonLocFirst,
5091                                           SourceLocation ColonLocSecond,
5092                                           Expr *Length, Expr *Stride,
5093                                           SourceLocation RBLoc) {
5094   if (Base->hasPlaceholderType() &&
5095       !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5096     ExprResult Result = CheckPlaceholderExpr(Base);
5097     if (Result.isInvalid())
5098       return ExprError();
5099     Base = Result.get();
5100   }
5101   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5102     ExprResult Result = CheckPlaceholderExpr(LowerBound);
5103     if (Result.isInvalid())
5104       return ExprError();
5105     Result = DefaultLvalueConversion(Result.get());
5106     if (Result.isInvalid())
5107       return ExprError();
5108     LowerBound = Result.get();
5109   }
5110   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5111     ExprResult Result = CheckPlaceholderExpr(Length);
5112     if (Result.isInvalid())
5113       return ExprError();
5114     Result = DefaultLvalueConversion(Result.get());
5115     if (Result.isInvalid())
5116       return ExprError();
5117     Length = Result.get();
5118   }
5119   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5120     ExprResult Result = CheckPlaceholderExpr(Stride);
5121     if (Result.isInvalid())
5122       return ExprError();
5123     Result = DefaultLvalueConversion(Result.get());
5124     if (Result.isInvalid())
5125       return ExprError();
5126     Stride = Result.get();
5127   }
5128 
5129   // Build an unanalyzed expression if either operand is type-dependent.
5130   if (Base->isTypeDependent() ||
5131       (LowerBound &&
5132        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5133       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5134       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5135     return new (Context) OMPArraySectionExpr(
5136         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5137         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5138   }
5139 
5140   // Perform default conversions.
5141   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5142   QualType ResultTy;
5143   if (OriginalTy->isAnyPointerType()) {
5144     ResultTy = OriginalTy->getPointeeType();
5145   } else if (OriginalTy->isArrayType()) {
5146     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5147   } else {
5148     return ExprError(
5149         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5150         << Base->getSourceRange());
5151   }
5152   // C99 6.5.2.1p1
5153   if (LowerBound) {
5154     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5155                                                       LowerBound);
5156     if (Res.isInvalid())
5157       return ExprError(Diag(LowerBound->getExprLoc(),
5158                             diag::err_omp_typecheck_section_not_integer)
5159                        << 0 << LowerBound->getSourceRange());
5160     LowerBound = Res.get();
5161 
5162     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5163         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5164       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5165           << 0 << LowerBound->getSourceRange();
5166   }
5167   if (Length) {
5168     auto Res =
5169         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5170     if (Res.isInvalid())
5171       return ExprError(Diag(Length->getExprLoc(),
5172                             diag::err_omp_typecheck_section_not_integer)
5173                        << 1 << Length->getSourceRange());
5174     Length = Res.get();
5175 
5176     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5177         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5178       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5179           << 1 << Length->getSourceRange();
5180   }
5181   if (Stride) {
5182     ExprResult Res =
5183         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5184     if (Res.isInvalid())
5185       return ExprError(Diag(Stride->getExprLoc(),
5186                             diag::err_omp_typecheck_section_not_integer)
5187                        << 1 << Stride->getSourceRange());
5188     Stride = Res.get();
5189 
5190     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5191         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5192       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5193           << 1 << Stride->getSourceRange();
5194   }
5195 
5196   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5197   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5198   // type. Note that functions are not objects, and that (in C99 parlance)
5199   // incomplete types are not object types.
5200   if (ResultTy->isFunctionType()) {
5201     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5202         << ResultTy << Base->getSourceRange();
5203     return ExprError();
5204   }
5205 
5206   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5207                           diag::err_omp_section_incomplete_type, Base))
5208     return ExprError();
5209 
5210   if (LowerBound && !OriginalTy->isAnyPointerType()) {
5211     Expr::EvalResult Result;
5212     if (LowerBound->EvaluateAsInt(Result, Context)) {
5213       // OpenMP 5.0, [2.1.5 Array Sections]
5214       // The array section must be a subset of the original array.
5215       llvm::APSInt LowerBoundValue = Result.Val.getInt();
5216       if (LowerBoundValue.isNegative()) {
5217         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5218             << LowerBound->getSourceRange();
5219         return ExprError();
5220       }
5221     }
5222   }
5223 
5224   if (Length) {
5225     Expr::EvalResult Result;
5226     if (Length->EvaluateAsInt(Result, Context)) {
5227       // OpenMP 5.0, [2.1.5 Array Sections]
5228       // The length must evaluate to non-negative integers.
5229       llvm::APSInt LengthValue = Result.Val.getInt();
5230       if (LengthValue.isNegative()) {
5231         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5232             << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5233             << Length->getSourceRange();
5234         return ExprError();
5235       }
5236     }
5237   } else if (ColonLocFirst.isValid() &&
5238              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5239                                       !OriginalTy->isVariableArrayType()))) {
5240     // OpenMP 5.0, [2.1.5 Array Sections]
5241     // When the size of the array dimension is not known, the length must be
5242     // specified explicitly.
5243     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5244         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5245     return ExprError();
5246   }
5247 
5248   if (Stride) {
5249     Expr::EvalResult Result;
5250     if (Stride->EvaluateAsInt(Result, Context)) {
5251       // OpenMP 5.0, [2.1.5 Array Sections]
5252       // The stride must evaluate to a positive integer.
5253       llvm::APSInt StrideValue = Result.Val.getInt();
5254       if (!StrideValue.isStrictlyPositive()) {
5255         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5256             << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5257             << Stride->getSourceRange();
5258         return ExprError();
5259       }
5260     }
5261   }
5262 
5263   if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5264     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5265     if (Result.isInvalid())
5266       return ExprError();
5267     Base = Result.get();
5268   }
5269   return new (Context) OMPArraySectionExpr(
5270       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5271       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5272 }
5273 
5274 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5275                                           SourceLocation RParenLoc,
5276                                           ArrayRef<Expr *> Dims,
5277                                           ArrayRef<SourceRange> Brackets) {
5278   if (Base->hasPlaceholderType()) {
5279     ExprResult Result = CheckPlaceholderExpr(Base);
5280     if (Result.isInvalid())
5281       return ExprError();
5282     Result = DefaultLvalueConversion(Result.get());
5283     if (Result.isInvalid())
5284       return ExprError();
5285     Base = Result.get();
5286   }
5287   QualType BaseTy = Base->getType();
5288   // Delay analysis of the types/expressions if instantiation/specialization is
5289   // required.
5290   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5291     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5292                                        LParenLoc, RParenLoc, Dims, Brackets);
5293   if (!BaseTy->isPointerType() ||
5294       (!Base->isTypeDependent() &&
5295        BaseTy->getPointeeType()->isIncompleteType()))
5296     return ExprError(Diag(Base->getExprLoc(),
5297                           diag::err_omp_non_pointer_type_array_shaping_base)
5298                      << Base->getSourceRange());
5299 
5300   SmallVector<Expr *, 4> NewDims;
5301   bool ErrorFound = false;
5302   for (Expr *Dim : Dims) {
5303     if (Dim->hasPlaceholderType()) {
5304       ExprResult Result = CheckPlaceholderExpr(Dim);
5305       if (Result.isInvalid()) {
5306         ErrorFound = true;
5307         continue;
5308       }
5309       Result = DefaultLvalueConversion(Result.get());
5310       if (Result.isInvalid()) {
5311         ErrorFound = true;
5312         continue;
5313       }
5314       Dim = Result.get();
5315     }
5316     if (!Dim->isTypeDependent()) {
5317       ExprResult Result =
5318           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5319       if (Result.isInvalid()) {
5320         ErrorFound = true;
5321         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5322             << Dim->getSourceRange();
5323         continue;
5324       }
5325       Dim = Result.get();
5326       Expr::EvalResult EvResult;
5327       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5328         // OpenMP 5.0, [2.1.4 Array Shaping]
5329         // Each si is an integral type expression that must evaluate to a
5330         // positive integer.
5331         llvm::APSInt Value = EvResult.Val.getInt();
5332         if (!Value.isStrictlyPositive()) {
5333           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5334               << toString(Value, /*Radix=*/10, /*Signed=*/true)
5335               << Dim->getSourceRange();
5336           ErrorFound = true;
5337           continue;
5338         }
5339       }
5340     }
5341     NewDims.push_back(Dim);
5342   }
5343   if (ErrorFound)
5344     return ExprError();
5345   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5346                                      LParenLoc, RParenLoc, NewDims, Brackets);
5347 }
5348 
5349 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5350                                       SourceLocation LLoc, SourceLocation RLoc,
5351                                       ArrayRef<OMPIteratorData> Data) {
5352   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5353   bool IsCorrect = true;
5354   for (const OMPIteratorData &D : Data) {
5355     TypeSourceInfo *TInfo = nullptr;
5356     SourceLocation StartLoc;
5357     QualType DeclTy;
5358     if (!D.Type.getAsOpaquePtr()) {
5359       // OpenMP 5.0, 2.1.6 Iterators
5360       // In an iterator-specifier, if the iterator-type is not specified then
5361       // the type of that iterator is of int type.
5362       DeclTy = Context.IntTy;
5363       StartLoc = D.DeclIdentLoc;
5364     } else {
5365       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5366       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5367     }
5368 
5369     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5370                              DeclTy->containsUnexpandedParameterPack() ||
5371                              DeclTy->isInstantiationDependentType();
5372     if (!IsDeclTyDependent) {
5373       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5374         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5375         // The iterator-type must be an integral or pointer type.
5376         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5377             << DeclTy;
5378         IsCorrect = false;
5379         continue;
5380       }
5381       if (DeclTy.isConstant(Context)) {
5382         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5383         // The iterator-type must not be const qualified.
5384         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5385             << DeclTy;
5386         IsCorrect = false;
5387         continue;
5388       }
5389     }
5390 
5391     // Iterator declaration.
5392     assert(D.DeclIdent && "Identifier expected.");
5393     // Always try to create iterator declarator to avoid extra error messages
5394     // about unknown declarations use.
5395     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5396                                D.DeclIdent, DeclTy, TInfo, SC_None);
5397     VD->setImplicit();
5398     if (S) {
5399       // Check for conflicting previous declaration.
5400       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5401       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5402                             ForVisibleRedeclaration);
5403       Previous.suppressDiagnostics();
5404       LookupName(Previous, S);
5405 
5406       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5407                            /*AllowInlineNamespace=*/false);
5408       if (!Previous.empty()) {
5409         NamedDecl *Old = Previous.getRepresentativeDecl();
5410         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5411         Diag(Old->getLocation(), diag::note_previous_definition);
5412       } else {
5413         PushOnScopeChains(VD, S);
5414       }
5415     } else {
5416       CurContext->addDecl(VD);
5417     }
5418     Expr *Begin = D.Range.Begin;
5419     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5420       ExprResult BeginRes =
5421           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5422       Begin = BeginRes.get();
5423     }
5424     Expr *End = D.Range.End;
5425     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5426       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5427       End = EndRes.get();
5428     }
5429     Expr *Step = D.Range.Step;
5430     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5431       if (!Step->getType()->isIntegralType(Context)) {
5432         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5433             << Step << Step->getSourceRange();
5434         IsCorrect = false;
5435         continue;
5436       }
5437       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5438       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5439       // If the step expression of a range-specification equals zero, the
5440       // behavior is unspecified.
5441       if (Result && Result->isZero()) {
5442         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5443             << Step << Step->getSourceRange();
5444         IsCorrect = false;
5445         continue;
5446       }
5447     }
5448     if (!Begin || !End || !IsCorrect) {
5449       IsCorrect = false;
5450       continue;
5451     }
5452     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5453     IDElem.IteratorDecl = VD;
5454     IDElem.AssignmentLoc = D.AssignLoc;
5455     IDElem.Range.Begin = Begin;
5456     IDElem.Range.End = End;
5457     IDElem.Range.Step = Step;
5458     IDElem.ColonLoc = D.ColonLoc;
5459     IDElem.SecondColonLoc = D.SecColonLoc;
5460   }
5461   if (!IsCorrect) {
5462     // Invalidate all created iterator declarations if error is found.
5463     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5464       if (Decl *ID = D.IteratorDecl)
5465         ID->setInvalidDecl();
5466     }
5467     return ExprError();
5468   }
5469   SmallVector<OMPIteratorHelperData, 4> Helpers;
5470   if (!CurContext->isDependentContext()) {
5471     // Build number of ityeration for each iteration range.
5472     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5473     // ((Begini-Stepi-1-Endi) / -Stepi);
5474     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5475       // (Endi - Begini)
5476       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5477                                           D.Range.Begin);
5478       if(!Res.isUsable()) {
5479         IsCorrect = false;
5480         continue;
5481       }
5482       ExprResult St, St1;
5483       if (D.Range.Step) {
5484         St = D.Range.Step;
5485         // (Endi - Begini) + Stepi
5486         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5487         if (!Res.isUsable()) {
5488           IsCorrect = false;
5489           continue;
5490         }
5491         // (Endi - Begini) + Stepi - 1
5492         Res =
5493             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5494                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5495         if (!Res.isUsable()) {
5496           IsCorrect = false;
5497           continue;
5498         }
5499         // ((Endi - Begini) + Stepi - 1) / Stepi
5500         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5501         if (!Res.isUsable()) {
5502           IsCorrect = false;
5503           continue;
5504         }
5505         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5506         // (Begini - Endi)
5507         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5508                                              D.Range.Begin, D.Range.End);
5509         if (!Res1.isUsable()) {
5510           IsCorrect = false;
5511           continue;
5512         }
5513         // (Begini - Endi) - Stepi
5514         Res1 =
5515             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5516         if (!Res1.isUsable()) {
5517           IsCorrect = false;
5518           continue;
5519         }
5520         // (Begini - Endi) - Stepi - 1
5521         Res1 =
5522             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5523                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5524         if (!Res1.isUsable()) {
5525           IsCorrect = false;
5526           continue;
5527         }
5528         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5529         Res1 =
5530             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5531         if (!Res1.isUsable()) {
5532           IsCorrect = false;
5533           continue;
5534         }
5535         // Stepi > 0.
5536         ExprResult CmpRes =
5537             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5538                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5539         if (!CmpRes.isUsable()) {
5540           IsCorrect = false;
5541           continue;
5542         }
5543         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5544                                  Res.get(), Res1.get());
5545         if (!Res.isUsable()) {
5546           IsCorrect = false;
5547           continue;
5548         }
5549       }
5550       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5551       if (!Res.isUsable()) {
5552         IsCorrect = false;
5553         continue;
5554       }
5555 
5556       // Build counter update.
5557       // Build counter.
5558       auto *CounterVD =
5559           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5560                           D.IteratorDecl->getBeginLoc(), nullptr,
5561                           Res.get()->getType(), nullptr, SC_None);
5562       CounterVD->setImplicit();
5563       ExprResult RefRes =
5564           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5565                            D.IteratorDecl->getBeginLoc());
5566       // Build counter update.
5567       // I = Begini + counter * Stepi;
5568       ExprResult UpdateRes;
5569       if (D.Range.Step) {
5570         UpdateRes = CreateBuiltinBinOp(
5571             D.AssignmentLoc, BO_Mul,
5572             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5573       } else {
5574         UpdateRes = DefaultLvalueConversion(RefRes.get());
5575       }
5576       if (!UpdateRes.isUsable()) {
5577         IsCorrect = false;
5578         continue;
5579       }
5580       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5581                                      UpdateRes.get());
5582       if (!UpdateRes.isUsable()) {
5583         IsCorrect = false;
5584         continue;
5585       }
5586       ExprResult VDRes =
5587           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5588                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5589                            D.IteratorDecl->getBeginLoc());
5590       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5591                                      UpdateRes.get());
5592       if (!UpdateRes.isUsable()) {
5593         IsCorrect = false;
5594         continue;
5595       }
5596       UpdateRes =
5597           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5598       if (!UpdateRes.isUsable()) {
5599         IsCorrect = false;
5600         continue;
5601       }
5602       ExprResult CounterUpdateRes =
5603           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5604       if (!CounterUpdateRes.isUsable()) {
5605         IsCorrect = false;
5606         continue;
5607       }
5608       CounterUpdateRes =
5609           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5610       if (!CounterUpdateRes.isUsable()) {
5611         IsCorrect = false;
5612         continue;
5613       }
5614       OMPIteratorHelperData &HD = Helpers.emplace_back();
5615       HD.CounterVD = CounterVD;
5616       HD.Upper = Res.get();
5617       HD.Update = UpdateRes.get();
5618       HD.CounterUpdate = CounterUpdateRes.get();
5619     }
5620   } else {
5621     Helpers.assign(ID.size(), {});
5622   }
5623   if (!IsCorrect) {
5624     // Invalidate all created iterator declarations if error is found.
5625     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5626       if (Decl *ID = D.IteratorDecl)
5627         ID->setInvalidDecl();
5628     }
5629     return ExprError();
5630   }
5631   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5632                                  LLoc, RLoc, ID, Helpers);
5633 }
5634 
5635 ExprResult
5636 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5637                                       Expr *Idx, SourceLocation RLoc) {
5638   Expr *LHSExp = Base;
5639   Expr *RHSExp = Idx;
5640 
5641   ExprValueKind VK = VK_LValue;
5642   ExprObjectKind OK = OK_Ordinary;
5643 
5644   // Per C++ core issue 1213, the result is an xvalue if either operand is
5645   // a non-lvalue array, and an lvalue otherwise.
5646   if (getLangOpts().CPlusPlus11) {
5647     for (auto *Op : {LHSExp, RHSExp}) {
5648       Op = Op->IgnoreImplicit();
5649       if (Op->getType()->isArrayType() && !Op->isLValue())
5650         VK = VK_XValue;
5651     }
5652   }
5653 
5654   // Perform default conversions.
5655   if (!LHSExp->getType()->getAs<VectorType>()) {
5656     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5657     if (Result.isInvalid())
5658       return ExprError();
5659     LHSExp = Result.get();
5660   }
5661   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5662   if (Result.isInvalid())
5663     return ExprError();
5664   RHSExp = Result.get();
5665 
5666   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5667 
5668   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5669   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5670   // in the subscript position. As a result, we need to derive the array base
5671   // and index from the expression types.
5672   Expr *BaseExpr, *IndexExpr;
5673   QualType ResultType;
5674   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5675     BaseExpr = LHSExp;
5676     IndexExpr = RHSExp;
5677     ResultType =
5678         getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5679   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5680     BaseExpr = LHSExp;
5681     IndexExpr = RHSExp;
5682     ResultType = PTy->getPointeeType();
5683   } else if (const ObjCObjectPointerType *PTy =
5684                LHSTy->getAs<ObjCObjectPointerType>()) {
5685     BaseExpr = LHSExp;
5686     IndexExpr = RHSExp;
5687 
5688     // Use custom logic if this should be the pseudo-object subscript
5689     // expression.
5690     if (!LangOpts.isSubscriptPointerArithmetic())
5691       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5692                                           nullptr);
5693 
5694     ResultType = PTy->getPointeeType();
5695   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5696      // Handle the uncommon case of "123[Ptr]".
5697     BaseExpr = RHSExp;
5698     IndexExpr = LHSExp;
5699     ResultType = PTy->getPointeeType();
5700   } else if (const ObjCObjectPointerType *PTy =
5701                RHSTy->getAs<ObjCObjectPointerType>()) {
5702      // Handle the uncommon case of "123[Ptr]".
5703     BaseExpr = RHSExp;
5704     IndexExpr = LHSExp;
5705     ResultType = PTy->getPointeeType();
5706     if (!LangOpts.isSubscriptPointerArithmetic()) {
5707       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5708         << ResultType << BaseExpr->getSourceRange();
5709       return ExprError();
5710     }
5711   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5712     BaseExpr = LHSExp;    // vectors: V[123]
5713     IndexExpr = RHSExp;
5714     // We apply C++ DR1213 to vector subscripting too.
5715     if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5716       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5717       if (Materialized.isInvalid())
5718         return ExprError();
5719       LHSExp = Materialized.get();
5720     }
5721     VK = LHSExp->getValueKind();
5722     if (VK != VK_PRValue)
5723       OK = OK_VectorComponent;
5724 
5725     ResultType = VTy->getElementType();
5726     QualType BaseType = BaseExpr->getType();
5727     Qualifiers BaseQuals = BaseType.getQualifiers();
5728     Qualifiers MemberQuals = ResultType.getQualifiers();
5729     Qualifiers Combined = BaseQuals + MemberQuals;
5730     if (Combined != MemberQuals)
5731       ResultType = Context.getQualifiedType(ResultType, Combined);
5732   } else if (LHSTy->isBuiltinType() &&
5733              LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) {
5734     const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5735     if (BTy->isSVEBool())
5736       return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5737                        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5738 
5739     BaseExpr = LHSExp;
5740     IndexExpr = RHSExp;
5741     if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5742       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5743       if (Materialized.isInvalid())
5744         return ExprError();
5745       LHSExp = Materialized.get();
5746     }
5747     VK = LHSExp->getValueKind();
5748     if (VK != VK_PRValue)
5749       OK = OK_VectorComponent;
5750 
5751     ResultType = BTy->getSveEltType(Context);
5752 
5753     QualType BaseType = BaseExpr->getType();
5754     Qualifiers BaseQuals = BaseType.getQualifiers();
5755     Qualifiers MemberQuals = ResultType.getQualifiers();
5756     Qualifiers Combined = BaseQuals + MemberQuals;
5757     if (Combined != MemberQuals)
5758       ResultType = Context.getQualifiedType(ResultType, Combined);
5759   } else if (LHSTy->isArrayType()) {
5760     // If we see an array that wasn't promoted by
5761     // DefaultFunctionArrayLvalueConversion, it must be an array that
5762     // wasn't promoted because of the C90 rule that doesn't
5763     // allow promoting non-lvalue arrays.  Warn, then
5764     // force the promotion here.
5765     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5766         << LHSExp->getSourceRange();
5767     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5768                                CK_ArrayToPointerDecay).get();
5769     LHSTy = LHSExp->getType();
5770 
5771     BaseExpr = LHSExp;
5772     IndexExpr = RHSExp;
5773     ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5774   } else if (RHSTy->isArrayType()) {
5775     // Same as previous, except for 123[f().a] case
5776     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5777         << RHSExp->getSourceRange();
5778     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5779                                CK_ArrayToPointerDecay).get();
5780     RHSTy = RHSExp->getType();
5781 
5782     BaseExpr = RHSExp;
5783     IndexExpr = LHSExp;
5784     ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5785   } else {
5786     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5787        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5788   }
5789   // C99 6.5.2.1p1
5790   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5791     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5792                      << IndexExpr->getSourceRange());
5793 
5794   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5795        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5796          && !IndexExpr->isTypeDependent())
5797     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5798 
5799   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5800   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5801   // type. Note that Functions are not objects, and that (in C99 parlance)
5802   // incomplete types are not object types.
5803   if (ResultType->isFunctionType()) {
5804     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5805         << ResultType << BaseExpr->getSourceRange();
5806     return ExprError();
5807   }
5808 
5809   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5810     // GNU extension: subscripting on pointer to void
5811     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5812       << BaseExpr->getSourceRange();
5813 
5814     // C forbids expressions of unqualified void type from being l-values.
5815     // See IsCForbiddenLValueType.
5816     if (!ResultType.hasQualifiers())
5817       VK = VK_PRValue;
5818   } else if (!ResultType->isDependentType() &&
5819              RequireCompleteSizedType(
5820                  LLoc, ResultType,
5821                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5822     return ExprError();
5823 
5824   assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5825          !ResultType.isCForbiddenLValueType());
5826 
5827   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5828       FunctionScopes.size() > 1) {
5829     if (auto *TT =
5830             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5831       for (auto I = FunctionScopes.rbegin(),
5832                 E = std::prev(FunctionScopes.rend());
5833            I != E; ++I) {
5834         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5835         if (CSI == nullptr)
5836           break;
5837         DeclContext *DC = nullptr;
5838         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5839           DC = LSI->CallOperator;
5840         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5841           DC = CRSI->TheCapturedDecl;
5842         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5843           DC = BSI->TheDecl;
5844         if (DC) {
5845           if (DC->containsDecl(TT->getDecl()))
5846             break;
5847           captureVariablyModifiedType(
5848               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5849         }
5850       }
5851     }
5852   }
5853 
5854   return new (Context)
5855       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5856 }
5857 
5858 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5859                                   ParmVarDecl *Param) {
5860   if (Param->hasUnparsedDefaultArg()) {
5861     // If we've already cleared out the location for the default argument,
5862     // that means we're parsing it right now.
5863     if (!UnparsedDefaultArgLocs.count(Param)) {
5864       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5865       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5866       Param->setInvalidDecl();
5867       return true;
5868     }
5869 
5870     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5871         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5872     Diag(UnparsedDefaultArgLocs[Param],
5873          diag::note_default_argument_declared_here);
5874     return true;
5875   }
5876 
5877   if (Param->hasUninstantiatedDefaultArg() &&
5878       InstantiateDefaultArgument(CallLoc, FD, Param))
5879     return true;
5880 
5881   assert(Param->hasInit() && "default argument but no initializer?");
5882 
5883   // If the default expression creates temporaries, we need to
5884   // push them to the current stack of expression temporaries so they'll
5885   // be properly destroyed.
5886   // FIXME: We should really be rebuilding the default argument with new
5887   // bound temporaries; see the comment in PR5810.
5888   // We don't need to do that with block decls, though, because
5889   // blocks in default argument expression can never capture anything.
5890   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5891     // Set the "needs cleanups" bit regardless of whether there are
5892     // any explicit objects.
5893     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5894 
5895     // Append all the objects to the cleanup list.  Right now, this
5896     // should always be a no-op, because blocks in default argument
5897     // expressions should never be able to capture anything.
5898     assert(!Init->getNumObjects() &&
5899            "default argument expression has capturing blocks?");
5900   }
5901 
5902   // We already type-checked the argument, so we know it works.
5903   // Just mark all of the declarations in this potentially-evaluated expression
5904   // as being "referenced".
5905   EnterExpressionEvaluationContext EvalContext(
5906       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5907   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5908                                    /*SkipLocalVariables=*/true);
5909   return false;
5910 }
5911 
5912 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5913                                         FunctionDecl *FD, ParmVarDecl *Param) {
5914   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5915   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5916     return ExprError();
5917   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5918 }
5919 
5920 Sema::VariadicCallType
5921 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5922                           Expr *Fn) {
5923   if (Proto && Proto->isVariadic()) {
5924     if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5925       return VariadicConstructor;
5926     else if (Fn && Fn->getType()->isBlockPointerType())
5927       return VariadicBlock;
5928     else if (FDecl) {
5929       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5930         if (Method->isInstance())
5931           return VariadicMethod;
5932     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5933       return VariadicMethod;
5934     return VariadicFunction;
5935   }
5936   return VariadicDoesNotApply;
5937 }
5938 
5939 namespace {
5940 class FunctionCallCCC final : public FunctionCallFilterCCC {
5941 public:
5942   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5943                   unsigned NumArgs, MemberExpr *ME)
5944       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5945         FunctionName(FuncName) {}
5946 
5947   bool ValidateCandidate(const TypoCorrection &candidate) override {
5948     if (!candidate.getCorrectionSpecifier() ||
5949         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5950       return false;
5951     }
5952 
5953     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5954   }
5955 
5956   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5957     return std::make_unique<FunctionCallCCC>(*this);
5958   }
5959 
5960 private:
5961   const IdentifierInfo *const FunctionName;
5962 };
5963 }
5964 
5965 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5966                                                FunctionDecl *FDecl,
5967                                                ArrayRef<Expr *> Args) {
5968   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5969   DeclarationName FuncName = FDecl->getDeclName();
5970   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5971 
5972   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5973   if (TypoCorrection Corrected = S.CorrectTypo(
5974           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5975           S.getScopeForContext(S.CurContext), nullptr, CCC,
5976           Sema::CTK_ErrorRecovery)) {
5977     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5978       if (Corrected.isOverloaded()) {
5979         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5980         OverloadCandidateSet::iterator Best;
5981         for (NamedDecl *CD : Corrected) {
5982           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5983             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5984                                    OCS);
5985         }
5986         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5987         case OR_Success:
5988           ND = Best->FoundDecl;
5989           Corrected.setCorrectionDecl(ND);
5990           break;
5991         default:
5992           break;
5993         }
5994       }
5995       ND = ND->getUnderlyingDecl();
5996       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5997         return Corrected;
5998     }
5999   }
6000   return TypoCorrection();
6001 }
6002 
6003 /// ConvertArgumentsForCall - Converts the arguments specified in
6004 /// Args/NumArgs to the parameter types of the function FDecl with
6005 /// function prototype Proto. Call is the call expression itself, and
6006 /// Fn is the function expression. For a C++ member function, this
6007 /// routine does not attempt to convert the object argument. Returns
6008 /// true if the call is ill-formed.
6009 bool
6010 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6011                               FunctionDecl *FDecl,
6012                               const FunctionProtoType *Proto,
6013                               ArrayRef<Expr *> Args,
6014                               SourceLocation RParenLoc,
6015                               bool IsExecConfig) {
6016   // Bail out early if calling a builtin with custom typechecking.
6017   if (FDecl)
6018     if (unsigned ID = FDecl->getBuiltinID())
6019       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
6020         return false;
6021 
6022   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6023   // assignment, to the types of the corresponding parameter, ...
6024   unsigned NumParams = Proto->getNumParams();
6025   bool Invalid = false;
6026   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6027   unsigned FnKind = Fn->getType()->isBlockPointerType()
6028                        ? 1 /* block */
6029                        : (IsExecConfig ? 3 /* kernel function (exec config) */
6030                                        : 0 /* function */);
6031 
6032   // If too few arguments are available (and we don't have default
6033   // arguments for the remaining parameters), don't make the call.
6034   if (Args.size() < NumParams) {
6035     if (Args.size() < MinArgs) {
6036       TypoCorrection TC;
6037       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6038         unsigned diag_id =
6039             MinArgs == NumParams && !Proto->isVariadic()
6040                 ? diag::err_typecheck_call_too_few_args_suggest
6041                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6042         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
6043                                         << static_cast<unsigned>(Args.size())
6044                                         << TC.getCorrectionRange());
6045       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
6046         Diag(RParenLoc,
6047              MinArgs == NumParams && !Proto->isVariadic()
6048                  ? diag::err_typecheck_call_too_few_args_one
6049                  : diag::err_typecheck_call_too_few_args_at_least_one)
6050             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
6051       else
6052         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6053                             ? diag::err_typecheck_call_too_few_args
6054                             : diag::err_typecheck_call_too_few_args_at_least)
6055             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
6056             << Fn->getSourceRange();
6057 
6058       // Emit the location of the prototype.
6059       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6060         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6061 
6062       return true;
6063     }
6064     // We reserve space for the default arguments when we create
6065     // the call expression, before calling ConvertArgumentsForCall.
6066     assert((Call->getNumArgs() == NumParams) &&
6067            "We should have reserved space for the default arguments before!");
6068   }
6069 
6070   // If too many are passed and not variadic, error on the extras and drop
6071   // them.
6072   if (Args.size() > NumParams) {
6073     if (!Proto->isVariadic()) {
6074       TypoCorrection TC;
6075       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6076         unsigned diag_id =
6077             MinArgs == NumParams && !Proto->isVariadic()
6078                 ? diag::err_typecheck_call_too_many_args_suggest
6079                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6080         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
6081                                         << static_cast<unsigned>(Args.size())
6082                                         << TC.getCorrectionRange());
6083       } else if (NumParams == 1 && FDecl &&
6084                  FDecl->getParamDecl(0)->getDeclName())
6085         Diag(Args[NumParams]->getBeginLoc(),
6086              MinArgs == NumParams
6087                  ? diag::err_typecheck_call_too_many_args_one
6088                  : diag::err_typecheck_call_too_many_args_at_most_one)
6089             << FnKind << FDecl->getParamDecl(0)
6090             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
6091             << SourceRange(Args[NumParams]->getBeginLoc(),
6092                            Args.back()->getEndLoc());
6093       else
6094         Diag(Args[NumParams]->getBeginLoc(),
6095              MinArgs == NumParams
6096                  ? diag::err_typecheck_call_too_many_args
6097                  : diag::err_typecheck_call_too_many_args_at_most)
6098             << FnKind << NumParams << static_cast<unsigned>(Args.size())
6099             << Fn->getSourceRange()
6100             << SourceRange(Args[NumParams]->getBeginLoc(),
6101                            Args.back()->getEndLoc());
6102 
6103       // Emit the location of the prototype.
6104       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6105         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6106 
6107       // This deletes the extra arguments.
6108       Call->shrinkNumArgs(NumParams);
6109       return true;
6110     }
6111   }
6112   SmallVector<Expr *, 8> AllArgs;
6113   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6114 
6115   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6116                                    AllArgs, CallType);
6117   if (Invalid)
6118     return true;
6119   unsigned TotalNumArgs = AllArgs.size();
6120   for (unsigned i = 0; i < TotalNumArgs; ++i)
6121     Call->setArg(i, AllArgs[i]);
6122 
6123   Call->computeDependence();
6124   return false;
6125 }
6126 
6127 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6128                                   const FunctionProtoType *Proto,
6129                                   unsigned FirstParam, ArrayRef<Expr *> Args,
6130                                   SmallVectorImpl<Expr *> &AllArgs,
6131                                   VariadicCallType CallType, bool AllowExplicit,
6132                                   bool IsListInitialization) {
6133   unsigned NumParams = Proto->getNumParams();
6134   bool Invalid = false;
6135   size_t ArgIx = 0;
6136   // Continue to check argument types (even if we have too few/many args).
6137   for (unsigned i = FirstParam; i < NumParams; i++) {
6138     QualType ProtoArgType = Proto->getParamType(i);
6139 
6140     Expr *Arg;
6141     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6142     if (ArgIx < Args.size()) {
6143       Arg = Args[ArgIx++];
6144 
6145       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6146                               diag::err_call_incomplete_argument, Arg))
6147         return true;
6148 
6149       // Strip the unbridged-cast placeholder expression off, if applicable.
6150       bool CFAudited = false;
6151       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6152           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6153           (!Param || !Param->hasAttr<CFConsumedAttr>()))
6154         Arg = stripARCUnbridgedCast(Arg);
6155       else if (getLangOpts().ObjCAutoRefCount &&
6156                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6157                (!Param || !Param->hasAttr<CFConsumedAttr>()))
6158         CFAudited = true;
6159 
6160       if (Proto->getExtParameterInfo(i).isNoEscape() &&
6161           ProtoArgType->isBlockPointerType())
6162         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6163           BE->getBlockDecl()->setDoesNotEscape();
6164 
6165       InitializedEntity Entity =
6166           Param ? InitializedEntity::InitializeParameter(Context, Param,
6167                                                          ProtoArgType)
6168                 : InitializedEntity::InitializeParameter(
6169                       Context, ProtoArgType, Proto->isParamConsumed(i));
6170 
6171       // Remember that parameter belongs to a CF audited API.
6172       if (CFAudited)
6173         Entity.setParameterCFAudited();
6174 
6175       ExprResult ArgE = PerformCopyInitialization(
6176           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6177       if (ArgE.isInvalid())
6178         return true;
6179 
6180       Arg = ArgE.getAs<Expr>();
6181     } else {
6182       assert(Param && "can't use default arguments without a known callee");
6183 
6184       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6185       if (ArgExpr.isInvalid())
6186         return true;
6187 
6188       Arg = ArgExpr.getAs<Expr>();
6189     }
6190 
6191     // Check for array bounds violations for each argument to the call. This
6192     // check only triggers warnings when the argument isn't a more complex Expr
6193     // with its own checking, such as a BinaryOperator.
6194     CheckArrayAccess(Arg);
6195 
6196     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6197     CheckStaticArrayArgument(CallLoc, Param, Arg);
6198 
6199     AllArgs.push_back(Arg);
6200   }
6201 
6202   // If this is a variadic call, handle args passed through "...".
6203   if (CallType != VariadicDoesNotApply) {
6204     // Assume that extern "C" functions with variadic arguments that
6205     // return __unknown_anytype aren't *really* variadic.
6206     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6207         FDecl->isExternC()) {
6208       for (Expr *A : Args.slice(ArgIx)) {
6209         QualType paramType; // ignored
6210         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6211         Invalid |= arg.isInvalid();
6212         AllArgs.push_back(arg.get());
6213       }
6214 
6215     // Otherwise do argument promotion, (C99 6.5.2.2p7).
6216     } else {
6217       for (Expr *A : Args.slice(ArgIx)) {
6218         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6219         Invalid |= Arg.isInvalid();
6220         AllArgs.push_back(Arg.get());
6221       }
6222     }
6223 
6224     // Check for array bounds violations.
6225     for (Expr *A : Args.slice(ArgIx))
6226       CheckArrayAccess(A);
6227   }
6228   return Invalid;
6229 }
6230 
6231 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6232   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6233   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6234     TL = DTL.getOriginalLoc();
6235   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6236     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6237       << ATL.getLocalSourceRange();
6238 }
6239 
6240 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6241 /// array parameter, check that it is non-null, and that if it is formed by
6242 /// array-to-pointer decay, the underlying array is sufficiently large.
6243 ///
6244 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6245 /// array type derivation, then for each call to the function, the value of the
6246 /// corresponding actual argument shall provide access to the first element of
6247 /// an array with at least as many elements as specified by the size expression.
6248 void
6249 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6250                                ParmVarDecl *Param,
6251                                const Expr *ArgExpr) {
6252   // Static array parameters are not supported in C++.
6253   if (!Param || getLangOpts().CPlusPlus)
6254     return;
6255 
6256   QualType OrigTy = Param->getOriginalType();
6257 
6258   const ArrayType *AT = Context.getAsArrayType(OrigTy);
6259   if (!AT || AT->getSizeModifier() != ArrayType::Static)
6260     return;
6261 
6262   if (ArgExpr->isNullPointerConstant(Context,
6263                                      Expr::NPC_NeverValueDependent)) {
6264     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6265     DiagnoseCalleeStaticArrayParam(*this, Param);
6266     return;
6267   }
6268 
6269   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6270   if (!CAT)
6271     return;
6272 
6273   const ConstantArrayType *ArgCAT =
6274     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6275   if (!ArgCAT)
6276     return;
6277 
6278   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6279                                              ArgCAT->getElementType())) {
6280     if (ArgCAT->getSize().ult(CAT->getSize())) {
6281       Diag(CallLoc, diag::warn_static_array_too_small)
6282           << ArgExpr->getSourceRange()
6283           << (unsigned)ArgCAT->getSize().getZExtValue()
6284           << (unsigned)CAT->getSize().getZExtValue() << 0;
6285       DiagnoseCalleeStaticArrayParam(*this, Param);
6286     }
6287     return;
6288   }
6289 
6290   Optional<CharUnits> ArgSize =
6291       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6292   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6293   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6294     Diag(CallLoc, diag::warn_static_array_too_small)
6295         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6296         << (unsigned)ParmSize->getQuantity() << 1;
6297     DiagnoseCalleeStaticArrayParam(*this, Param);
6298   }
6299 }
6300 
6301 /// Given a function expression of unknown-any type, try to rebuild it
6302 /// to have a function type.
6303 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6304 
6305 /// Is the given type a placeholder that we need to lower out
6306 /// immediately during argument processing?
6307 static bool isPlaceholderToRemoveAsArg(QualType type) {
6308   // Placeholders are never sugared.
6309   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6310   if (!placeholder) return false;
6311 
6312   switch (placeholder->getKind()) {
6313   // Ignore all the non-placeholder types.
6314 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6315   case BuiltinType::Id:
6316 #include "clang/Basic/OpenCLImageTypes.def"
6317 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6318   case BuiltinType::Id:
6319 #include "clang/Basic/OpenCLExtensionTypes.def"
6320   // In practice we'll never use this, since all SVE types are sugared
6321   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6322 #define SVE_TYPE(Name, Id, SingletonId) \
6323   case BuiltinType::Id:
6324 #include "clang/Basic/AArch64SVEACLETypes.def"
6325 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6326   case BuiltinType::Id:
6327 #include "clang/Basic/PPCTypes.def"
6328 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6329 #include "clang/Basic/RISCVVTypes.def"
6330 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6331 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6332 #include "clang/AST/BuiltinTypes.def"
6333     return false;
6334 
6335   // We cannot lower out overload sets; they might validly be resolved
6336   // by the call machinery.
6337   case BuiltinType::Overload:
6338     return false;
6339 
6340   // Unbridged casts in ARC can be handled in some call positions and
6341   // should be left in place.
6342   case BuiltinType::ARCUnbridgedCast:
6343     return false;
6344 
6345   // Pseudo-objects should be converted as soon as possible.
6346   case BuiltinType::PseudoObject:
6347     return true;
6348 
6349   // The debugger mode could theoretically but currently does not try
6350   // to resolve unknown-typed arguments based on known parameter types.
6351   case BuiltinType::UnknownAny:
6352     return true;
6353 
6354   // These are always invalid as call arguments and should be reported.
6355   case BuiltinType::BoundMember:
6356   case BuiltinType::BuiltinFn:
6357   case BuiltinType::IncompleteMatrixIdx:
6358   case BuiltinType::OMPArraySection:
6359   case BuiltinType::OMPArrayShaping:
6360   case BuiltinType::OMPIterator:
6361     return true;
6362 
6363   }
6364   llvm_unreachable("bad builtin type kind");
6365 }
6366 
6367 /// Check an argument list for placeholders that we won't try to
6368 /// handle later.
6369 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6370   // Apply this processing to all the arguments at once instead of
6371   // dying at the first failure.
6372   bool hasInvalid = false;
6373   for (size_t i = 0, e = args.size(); i != e; i++) {
6374     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6375       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6376       if (result.isInvalid()) hasInvalid = true;
6377       else args[i] = result.get();
6378     }
6379   }
6380   return hasInvalid;
6381 }
6382 
6383 /// If a builtin function has a pointer argument with no explicit address
6384 /// space, then it should be able to accept a pointer to any address
6385 /// space as input.  In order to do this, we need to replace the
6386 /// standard builtin declaration with one that uses the same address space
6387 /// as the call.
6388 ///
6389 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6390 ///                  it does not contain any pointer arguments without
6391 ///                  an address space qualifer.  Otherwise the rewritten
6392 ///                  FunctionDecl is returned.
6393 /// TODO: Handle pointer return types.
6394 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6395                                                 FunctionDecl *FDecl,
6396                                                 MultiExprArg ArgExprs) {
6397 
6398   QualType DeclType = FDecl->getType();
6399   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6400 
6401   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6402       ArgExprs.size() < FT->getNumParams())
6403     return nullptr;
6404 
6405   bool NeedsNewDecl = false;
6406   unsigned i = 0;
6407   SmallVector<QualType, 8> OverloadParams;
6408 
6409   for (QualType ParamType : FT->param_types()) {
6410 
6411     // Convert array arguments to pointer to simplify type lookup.
6412     ExprResult ArgRes =
6413         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6414     if (ArgRes.isInvalid())
6415       return nullptr;
6416     Expr *Arg = ArgRes.get();
6417     QualType ArgType = Arg->getType();
6418     if (!ParamType->isPointerType() ||
6419         ParamType.hasAddressSpace() ||
6420         !ArgType->isPointerType() ||
6421         !ArgType->getPointeeType().hasAddressSpace()) {
6422       OverloadParams.push_back(ParamType);
6423       continue;
6424     }
6425 
6426     QualType PointeeType = ParamType->getPointeeType();
6427     if (PointeeType.hasAddressSpace())
6428       continue;
6429 
6430     NeedsNewDecl = true;
6431     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6432 
6433     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6434     OverloadParams.push_back(Context.getPointerType(PointeeType));
6435   }
6436 
6437   if (!NeedsNewDecl)
6438     return nullptr;
6439 
6440   FunctionProtoType::ExtProtoInfo EPI;
6441   EPI.Variadic = FT->isVariadic();
6442   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6443                                                 OverloadParams, EPI);
6444   DeclContext *Parent = FDecl->getParent();
6445   FunctionDecl *OverloadDecl = FunctionDecl::Create(
6446       Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6447       FDecl->getIdentifier(), OverloadTy,
6448       /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6449       false,
6450       /*hasPrototype=*/true);
6451   SmallVector<ParmVarDecl*, 16> Params;
6452   FT = cast<FunctionProtoType>(OverloadTy);
6453   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6454     QualType ParamType = FT->getParamType(i);
6455     ParmVarDecl *Parm =
6456         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6457                                 SourceLocation(), nullptr, ParamType,
6458                                 /*TInfo=*/nullptr, SC_None, nullptr);
6459     Parm->setScopeInfo(0, i);
6460     Params.push_back(Parm);
6461   }
6462   OverloadDecl->setParams(Params);
6463   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6464   return OverloadDecl;
6465 }
6466 
6467 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6468                                     FunctionDecl *Callee,
6469                                     MultiExprArg ArgExprs) {
6470   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6471   // similar attributes) really don't like it when functions are called with an
6472   // invalid number of args.
6473   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6474                          /*PartialOverloading=*/false) &&
6475       !Callee->isVariadic())
6476     return;
6477   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6478     return;
6479 
6480   if (const EnableIfAttr *Attr =
6481           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6482     S.Diag(Fn->getBeginLoc(),
6483            isa<CXXMethodDecl>(Callee)
6484                ? diag::err_ovl_no_viable_member_function_in_call
6485                : diag::err_ovl_no_viable_function_in_call)
6486         << Callee << Callee->getSourceRange();
6487     S.Diag(Callee->getLocation(),
6488            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6489         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6490     return;
6491   }
6492 }
6493 
6494 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6495     const UnresolvedMemberExpr *const UME, Sema &S) {
6496 
6497   const auto GetFunctionLevelDCIfCXXClass =
6498       [](Sema &S) -> const CXXRecordDecl * {
6499     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6500     if (!DC || !DC->getParent())
6501       return nullptr;
6502 
6503     // If the call to some member function was made from within a member
6504     // function body 'M' return return 'M's parent.
6505     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6506       return MD->getParent()->getCanonicalDecl();
6507     // else the call was made from within a default member initializer of a
6508     // class, so return the class.
6509     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6510       return RD->getCanonicalDecl();
6511     return nullptr;
6512   };
6513   // If our DeclContext is neither a member function nor a class (in the
6514   // case of a lambda in a default member initializer), we can't have an
6515   // enclosing 'this'.
6516 
6517   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6518   if (!CurParentClass)
6519     return false;
6520 
6521   // The naming class for implicit member functions call is the class in which
6522   // name lookup starts.
6523   const CXXRecordDecl *const NamingClass =
6524       UME->getNamingClass()->getCanonicalDecl();
6525   assert(NamingClass && "Must have naming class even for implicit access");
6526 
6527   // If the unresolved member functions were found in a 'naming class' that is
6528   // related (either the same or derived from) to the class that contains the
6529   // member function that itself contained the implicit member access.
6530 
6531   return CurParentClass == NamingClass ||
6532          CurParentClass->isDerivedFrom(NamingClass);
6533 }
6534 
6535 static void
6536 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6537     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6538 
6539   if (!UME)
6540     return;
6541 
6542   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6543   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6544   // already been captured, or if this is an implicit member function call (if
6545   // it isn't, an attempt to capture 'this' should already have been made).
6546   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6547       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6548     return;
6549 
6550   // Check if the naming class in which the unresolved members were found is
6551   // related (same as or is a base of) to the enclosing class.
6552 
6553   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6554     return;
6555 
6556 
6557   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6558   // If the enclosing function is not dependent, then this lambda is
6559   // capture ready, so if we can capture this, do so.
6560   if (!EnclosingFunctionCtx->isDependentContext()) {
6561     // If the current lambda and all enclosing lambdas can capture 'this' -
6562     // then go ahead and capture 'this' (since our unresolved overload set
6563     // contains at least one non-static member function).
6564     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6565       S.CheckCXXThisCapture(CallLoc);
6566   } else if (S.CurContext->isDependentContext()) {
6567     // ... since this is an implicit member reference, that might potentially
6568     // involve a 'this' capture, mark 'this' for potential capture in
6569     // enclosing lambdas.
6570     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6571       CurLSI->addPotentialThisCapture(CallLoc);
6572   }
6573 }
6574 
6575 // Once a call is fully resolved, warn for unqualified calls to specific
6576 // C++ standard functions, like move and forward.
6577 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) {
6578   // We are only checking unary move and forward so exit early here.
6579   if (Call->getNumArgs() != 1)
6580     return;
6581 
6582   Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6583   if (!E || isa<UnresolvedLookupExpr>(E))
6584     return;
6585   DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
6586   if (!DRE || !DRE->getLocation().isValid())
6587     return;
6588 
6589   if (DRE->getQualifier())
6590     return;
6591 
6592   const FunctionDecl *FD = Call->getDirectCallee();
6593   if (!FD)
6594     return;
6595 
6596   // Only warn for some functions deemed more frequent or problematic.
6597   unsigned BuiltinID = FD->getBuiltinID();
6598   if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6599     return;
6600 
6601   S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6602       << FD->getQualifiedNameAsString()
6603       << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6604 }
6605 
6606 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6607                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6608                                Expr *ExecConfig) {
6609   ExprResult Call =
6610       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6611                     /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6612   if (Call.isInvalid())
6613     return Call;
6614 
6615   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6616   // language modes.
6617   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6618     if (ULE->hasExplicitTemplateArgs() &&
6619         ULE->decls_begin() == ULE->decls_end()) {
6620       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6621                                  ? diag::warn_cxx17_compat_adl_only_template_id
6622                                  : diag::ext_adl_only_template_id)
6623           << ULE->getName();
6624     }
6625   }
6626 
6627   if (LangOpts.OpenMP)
6628     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6629                            ExecConfig);
6630   if (LangOpts.CPlusPlus) {
6631     CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6632     if (CE)
6633       DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
6634   }
6635   return Call;
6636 }
6637 
6638 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6639 /// This provides the location of the left/right parens and a list of comma
6640 /// locations.
6641 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6642                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6643                                Expr *ExecConfig, bool IsExecConfig,
6644                                bool AllowRecovery) {
6645   // Since this might be a postfix expression, get rid of ParenListExprs.
6646   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6647   if (Result.isInvalid()) return ExprError();
6648   Fn = Result.get();
6649 
6650   if (checkArgsForPlaceholders(*this, ArgExprs))
6651     return ExprError();
6652 
6653   if (getLangOpts().CPlusPlus) {
6654     // If this is a pseudo-destructor expression, build the call immediately.
6655     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6656       if (!ArgExprs.empty()) {
6657         // Pseudo-destructor calls should not have any arguments.
6658         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6659             << FixItHint::CreateRemoval(
6660                    SourceRange(ArgExprs.front()->getBeginLoc(),
6661                                ArgExprs.back()->getEndLoc()));
6662       }
6663 
6664       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6665                               VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6666     }
6667     if (Fn->getType() == Context.PseudoObjectTy) {
6668       ExprResult result = CheckPlaceholderExpr(Fn);
6669       if (result.isInvalid()) return ExprError();
6670       Fn = result.get();
6671     }
6672 
6673     // Determine whether this is a dependent call inside a C++ template,
6674     // in which case we won't do any semantic analysis now.
6675     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6676       if (ExecConfig) {
6677         return CUDAKernelCallExpr::Create(Context, Fn,
6678                                           cast<CallExpr>(ExecConfig), ArgExprs,
6679                                           Context.DependentTy, VK_PRValue,
6680                                           RParenLoc, CurFPFeatureOverrides());
6681       } else {
6682 
6683         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6684             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6685             Fn->getBeginLoc());
6686 
6687         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6688                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6689       }
6690     }
6691 
6692     // Determine whether this is a call to an object (C++ [over.call.object]).
6693     if (Fn->getType()->isRecordType())
6694       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6695                                           RParenLoc);
6696 
6697     if (Fn->getType() == Context.UnknownAnyTy) {
6698       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6699       if (result.isInvalid()) return ExprError();
6700       Fn = result.get();
6701     }
6702 
6703     if (Fn->getType() == Context.BoundMemberTy) {
6704       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6705                                        RParenLoc, ExecConfig, IsExecConfig,
6706                                        AllowRecovery);
6707     }
6708   }
6709 
6710   // Check for overloaded calls.  This can happen even in C due to extensions.
6711   if (Fn->getType() == Context.OverloadTy) {
6712     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6713 
6714     // We aren't supposed to apply this logic if there's an '&' involved.
6715     if (!find.HasFormOfMemberPointer) {
6716       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6717         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6718                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6719       OverloadExpr *ovl = find.Expression;
6720       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6721         return BuildOverloadedCallExpr(
6722             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6723             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6724       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6725                                        RParenLoc, ExecConfig, IsExecConfig,
6726                                        AllowRecovery);
6727     }
6728   }
6729 
6730   // If we're directly calling a function, get the appropriate declaration.
6731   if (Fn->getType() == Context.UnknownAnyTy) {
6732     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6733     if (result.isInvalid()) return ExprError();
6734     Fn = result.get();
6735   }
6736 
6737   Expr *NakedFn = Fn->IgnoreParens();
6738 
6739   bool CallingNDeclIndirectly = false;
6740   NamedDecl *NDecl = nullptr;
6741   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6742     if (UnOp->getOpcode() == UO_AddrOf) {
6743       CallingNDeclIndirectly = true;
6744       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6745     }
6746   }
6747 
6748   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6749     NDecl = DRE->getDecl();
6750 
6751     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6752     if (FDecl && FDecl->getBuiltinID()) {
6753       // Rewrite the function decl for this builtin by replacing parameters
6754       // with no explicit address space with the address space of the arguments
6755       // in ArgExprs.
6756       if ((FDecl =
6757                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6758         NDecl = FDecl;
6759         Fn = DeclRefExpr::Create(
6760             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6761             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6762             nullptr, DRE->isNonOdrUse());
6763       }
6764     }
6765   } else if (isa<MemberExpr>(NakedFn))
6766     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6767 
6768   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6769     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6770                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6771       return ExprError();
6772 
6773     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6774 
6775     // If this expression is a call to a builtin function in HIP device
6776     // compilation, allow a pointer-type argument to default address space to be
6777     // passed as a pointer-type parameter to a non-default address space.
6778     // If Arg is declared in the default address space and Param is declared
6779     // in a non-default address space, perform an implicit address space cast to
6780     // the parameter type.
6781     if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6782         FD->getBuiltinID()) {
6783       for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6784         ParmVarDecl *Param = FD->getParamDecl(Idx);
6785         if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6786             !ArgExprs[Idx]->getType()->isPointerType())
6787           continue;
6788 
6789         auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6790         auto ArgTy = ArgExprs[Idx]->getType();
6791         auto ArgPtTy = ArgTy->getPointeeType();
6792         auto ArgAS = ArgPtTy.getAddressSpace();
6793 
6794         // Add address space cast if target address spaces are different
6795         bool NeedImplicitASC =
6796           ParamAS != LangAS::Default &&       // Pointer params in generic AS don't need special handling.
6797           ( ArgAS == LangAS::Default  ||      // We do allow implicit conversion from generic AS
6798                                               // or from specific AS which has target AS matching that of Param.
6799           getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
6800         if (!NeedImplicitASC)
6801           continue;
6802 
6803         // First, ensure that the Arg is an RValue.
6804         if (ArgExprs[Idx]->isGLValue()) {
6805           ArgExprs[Idx] = ImplicitCastExpr::Create(
6806               Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6807               nullptr, VK_PRValue, FPOptionsOverride());
6808         }
6809 
6810         // Construct a new arg type with address space of Param
6811         Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6812         ArgPtQuals.setAddressSpace(ParamAS);
6813         auto NewArgPtTy =
6814             Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6815         auto NewArgTy =
6816             Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6817                                      ArgTy.getQualifiers());
6818 
6819         // Finally perform an implicit address space cast
6820         ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6821                                           CK_AddressSpaceConversion)
6822                             .get();
6823       }
6824     }
6825   }
6826 
6827   if (Context.isDependenceAllowed() &&
6828       (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6829     assert(!getLangOpts().CPlusPlus);
6830     assert((Fn->containsErrors() ||
6831             llvm::any_of(ArgExprs,
6832                          [](clang::Expr *E) { return E->containsErrors(); })) &&
6833            "should only occur in error-recovery path.");
6834     QualType ReturnType =
6835         llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6836             ? cast<FunctionDecl>(NDecl)->getCallResultType()
6837             : Context.DependentTy;
6838     return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6839                             Expr::getValueKindForType(ReturnType), RParenLoc,
6840                             CurFPFeatureOverrides());
6841   }
6842   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6843                                ExecConfig, IsExecConfig);
6844 }
6845 
6846 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6847 //  with the specified CallArgs
6848 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6849                                  MultiExprArg CallArgs) {
6850   StringRef Name = Context.BuiltinInfo.getName(Id);
6851   LookupResult R(*this, &Context.Idents.get(Name), Loc,
6852                  Sema::LookupOrdinaryName);
6853   LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6854 
6855   auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6856   assert(BuiltInDecl && "failed to find builtin declaration");
6857 
6858   ExprResult DeclRef =
6859       BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6860   assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6861 
6862   ExprResult Call =
6863       BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6864 
6865   assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6866   return Call.get();
6867 }
6868 
6869 /// Parse a __builtin_astype expression.
6870 ///
6871 /// __builtin_astype( value, dst type )
6872 ///
6873 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6874                                  SourceLocation BuiltinLoc,
6875                                  SourceLocation RParenLoc) {
6876   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6877   return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6878 }
6879 
6880 /// Create a new AsTypeExpr node (bitcast) from the arguments.
6881 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6882                                  SourceLocation BuiltinLoc,
6883                                  SourceLocation RParenLoc) {
6884   ExprValueKind VK = VK_PRValue;
6885   ExprObjectKind OK = OK_Ordinary;
6886   QualType SrcTy = E->getType();
6887   if (!SrcTy->isDependentType() &&
6888       Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6889     return ExprError(
6890         Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6891         << DestTy << SrcTy << E->getSourceRange());
6892   return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6893 }
6894 
6895 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6896 /// provided arguments.
6897 ///
6898 /// __builtin_convertvector( value, dst type )
6899 ///
6900 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6901                                         SourceLocation BuiltinLoc,
6902                                         SourceLocation RParenLoc) {
6903   TypeSourceInfo *TInfo;
6904   GetTypeFromParser(ParsedDestTy, &TInfo);
6905   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6906 }
6907 
6908 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6909 /// i.e. an expression not of \p OverloadTy.  The expression should
6910 /// unary-convert to an expression of function-pointer or
6911 /// block-pointer type.
6912 ///
6913 /// \param NDecl the declaration being called, if available
6914 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6915                                        SourceLocation LParenLoc,
6916                                        ArrayRef<Expr *> Args,
6917                                        SourceLocation RParenLoc, Expr *Config,
6918                                        bool IsExecConfig, ADLCallKind UsesADL) {
6919   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6920   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6921 
6922   // Functions with 'interrupt' attribute cannot be called directly.
6923   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6924     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6925     return ExprError();
6926   }
6927 
6928   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6929   // so there's some risk when calling out to non-interrupt handler functions
6930   // that the callee might not preserve them. This is easy to diagnose here,
6931   // but can be very challenging to debug.
6932   // Likewise, X86 interrupt handlers may only call routines with attribute
6933   // no_caller_saved_registers since there is no efficient way to
6934   // save and restore the non-GPR state.
6935   if (auto *Caller = getCurFunctionDecl()) {
6936     if (Caller->hasAttr<ARMInterruptAttr>()) {
6937       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6938       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6939         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6940         if (FDecl)
6941           Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6942       }
6943     }
6944     if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6945         ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6946       Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6947       if (FDecl)
6948         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6949     }
6950   }
6951 
6952   // Promote the function operand.
6953   // We special-case function promotion here because we only allow promoting
6954   // builtin functions to function pointers in the callee of a call.
6955   ExprResult Result;
6956   QualType ResultTy;
6957   if (BuiltinID &&
6958       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6959     // Extract the return type from the (builtin) function pointer type.
6960     // FIXME Several builtins still have setType in
6961     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6962     // Builtins.def to ensure they are correct before removing setType calls.
6963     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6964     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6965     ResultTy = FDecl->getCallResultType();
6966   } else {
6967     Result = CallExprUnaryConversions(Fn);
6968     ResultTy = Context.BoolTy;
6969   }
6970   if (Result.isInvalid())
6971     return ExprError();
6972   Fn = Result.get();
6973 
6974   // Check for a valid function type, but only if it is not a builtin which
6975   // requires custom type checking. These will be handled by
6976   // CheckBuiltinFunctionCall below just after creation of the call expression.
6977   const FunctionType *FuncT = nullptr;
6978   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6979   retry:
6980     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6981       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6982       // have type pointer to function".
6983       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6984       if (!FuncT)
6985         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6986                          << Fn->getType() << Fn->getSourceRange());
6987     } else if (const BlockPointerType *BPT =
6988                    Fn->getType()->getAs<BlockPointerType>()) {
6989       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6990     } else {
6991       // Handle calls to expressions of unknown-any type.
6992       if (Fn->getType() == Context.UnknownAnyTy) {
6993         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6994         if (rewrite.isInvalid())
6995           return ExprError();
6996         Fn = rewrite.get();
6997         goto retry;
6998       }
6999 
7000       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7001                        << Fn->getType() << Fn->getSourceRange());
7002     }
7003   }
7004 
7005   // Get the number of parameters in the function prototype, if any.
7006   // We will allocate space for max(Args.size(), NumParams) arguments
7007   // in the call expression.
7008   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7009   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7010 
7011   CallExpr *TheCall;
7012   if (Config) {
7013     assert(UsesADL == ADLCallKind::NotADL &&
7014            "CUDAKernelCallExpr should not use ADL");
7015     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7016                                          Args, ResultTy, VK_PRValue, RParenLoc,
7017                                          CurFPFeatureOverrides(), NumParams);
7018   } else {
7019     TheCall =
7020         CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7021                          CurFPFeatureOverrides(), NumParams, UsesADL);
7022   }
7023 
7024   if (!Context.isDependenceAllowed()) {
7025     // Forget about the nulled arguments since typo correction
7026     // do not handle them well.
7027     TheCall->shrinkNumArgs(Args.size());
7028     // C cannot always handle TypoExpr nodes in builtin calls and direct
7029     // function calls as their argument checking don't necessarily handle
7030     // dependent types properly, so make sure any TypoExprs have been
7031     // dealt with.
7032     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
7033     if (!Result.isUsable()) return ExprError();
7034     CallExpr *TheOldCall = TheCall;
7035     TheCall = dyn_cast<CallExpr>(Result.get());
7036     bool CorrectedTypos = TheCall != TheOldCall;
7037     if (!TheCall) return Result;
7038     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7039 
7040     // A new call expression node was created if some typos were corrected.
7041     // However it may not have been constructed with enough storage. In this
7042     // case, rebuild the node with enough storage. The waste of space is
7043     // immaterial since this only happens when some typos were corrected.
7044     if (CorrectedTypos && Args.size() < NumParams) {
7045       if (Config)
7046         TheCall = CUDAKernelCallExpr::Create(
7047             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
7048             RParenLoc, CurFPFeatureOverrides(), NumParams);
7049       else
7050         TheCall =
7051             CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7052                              CurFPFeatureOverrides(), NumParams, UsesADL);
7053     }
7054     // We can now handle the nulled arguments for the default arguments.
7055     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
7056   }
7057 
7058   // Bail out early if calling a builtin with custom type checking.
7059   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
7060     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7061 
7062   if (getLangOpts().CUDA) {
7063     if (Config) {
7064       // CUDA: Kernel calls must be to global functions
7065       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7066         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7067             << FDecl << Fn->getSourceRange());
7068 
7069       // CUDA: Kernel function must have 'void' return type
7070       if (!FuncT->getReturnType()->isVoidType() &&
7071           !FuncT->getReturnType()->getAs<AutoType>() &&
7072           !FuncT->getReturnType()->isInstantiationDependentType())
7073         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7074             << Fn->getType() << Fn->getSourceRange());
7075     } else {
7076       // CUDA: Calls to global functions must be configured
7077       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7078         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7079             << FDecl << Fn->getSourceRange());
7080     }
7081   }
7082 
7083   // Check for a valid return type
7084   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7085                           FDecl))
7086     return ExprError();
7087 
7088   // We know the result type of the call, set it.
7089   TheCall->setType(FuncT->getCallResultType(Context));
7090   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7091 
7092   if (Proto) {
7093     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7094                                 IsExecConfig))
7095       return ExprError();
7096   } else {
7097     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7098 
7099     if (FDecl) {
7100       // Check if we have too few/too many template arguments, based
7101       // on our knowledge of the function definition.
7102       const FunctionDecl *Def = nullptr;
7103       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7104         Proto = Def->getType()->getAs<FunctionProtoType>();
7105        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7106           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7107           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7108       }
7109 
7110       // If the function we're calling isn't a function prototype, but we have
7111       // a function prototype from a prior declaratiom, use that prototype.
7112       if (!FDecl->hasPrototype())
7113         Proto = FDecl->getType()->getAs<FunctionProtoType>();
7114     }
7115 
7116     // If we still haven't found a prototype to use but there are arguments to
7117     // the call, diagnose this as calling a function without a prototype.
7118     // However, if we found a function declaration, check to see if
7119     // -Wdeprecated-non-prototype was disabled where the function was declared.
7120     // If so, we will silence the diagnostic here on the assumption that this
7121     // interface is intentional and the user knows what they're doing. We will
7122     // also silence the diagnostic if there is a function declaration but it
7123     // was implicitly defined (the user already gets diagnostics about the
7124     // creation of the implicit function declaration, so the additional warning
7125     // is not helpful).
7126     if (!Proto && !Args.empty() &&
7127         (!FDecl || (!FDecl->isImplicit() &&
7128                     !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7129                                      FDecl->getLocation()))))
7130       Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7131           << (FDecl != nullptr) << FDecl;
7132 
7133     // Promote the arguments (C99 6.5.2.2p6).
7134     for (unsigned i = 0, e = Args.size(); i != e; i++) {
7135       Expr *Arg = Args[i];
7136 
7137       if (Proto && i < Proto->getNumParams()) {
7138         InitializedEntity Entity = InitializedEntity::InitializeParameter(
7139             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7140         ExprResult ArgE =
7141             PerformCopyInitialization(Entity, SourceLocation(), Arg);
7142         if (ArgE.isInvalid())
7143           return true;
7144 
7145         Arg = ArgE.getAs<Expr>();
7146 
7147       } else {
7148         ExprResult ArgE = DefaultArgumentPromotion(Arg);
7149 
7150         if (ArgE.isInvalid())
7151           return true;
7152 
7153         Arg = ArgE.getAs<Expr>();
7154       }
7155 
7156       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7157                               diag::err_call_incomplete_argument, Arg))
7158         return ExprError();
7159 
7160       TheCall->setArg(i, Arg);
7161     }
7162     TheCall->computeDependence();
7163   }
7164 
7165   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7166     if (!Method->isStatic())
7167       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7168         << Fn->getSourceRange());
7169 
7170   // Check for sentinels
7171   if (NDecl)
7172     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7173 
7174   // Warn for unions passing across security boundary (CMSE).
7175   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7176     for (unsigned i = 0, e = Args.size(); i != e; i++) {
7177       if (const auto *RT =
7178               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7179         if (RT->getDecl()->isOrContainsUnion())
7180           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7181               << 0 << i;
7182       }
7183     }
7184   }
7185 
7186   // Do special checking on direct calls to functions.
7187   if (FDecl) {
7188     if (CheckFunctionCall(FDecl, TheCall, Proto))
7189       return ExprError();
7190 
7191     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7192 
7193     if (BuiltinID)
7194       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7195   } else if (NDecl) {
7196     if (CheckPointerCall(NDecl, TheCall, Proto))
7197       return ExprError();
7198   } else {
7199     if (CheckOtherCall(TheCall, Proto))
7200       return ExprError();
7201   }
7202 
7203   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7204 }
7205 
7206 ExprResult
7207 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7208                            SourceLocation RParenLoc, Expr *InitExpr) {
7209   assert(Ty && "ActOnCompoundLiteral(): missing type");
7210   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7211 
7212   TypeSourceInfo *TInfo;
7213   QualType literalType = GetTypeFromParser(Ty, &TInfo);
7214   if (!TInfo)
7215     TInfo = Context.getTrivialTypeSourceInfo(literalType);
7216 
7217   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7218 }
7219 
7220 ExprResult
7221 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7222                                SourceLocation RParenLoc, Expr *LiteralExpr) {
7223   QualType literalType = TInfo->getType();
7224 
7225   if (literalType->isArrayType()) {
7226     if (RequireCompleteSizedType(
7227             LParenLoc, Context.getBaseElementType(literalType),
7228             diag::err_array_incomplete_or_sizeless_type,
7229             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7230       return ExprError();
7231     if (literalType->isVariableArrayType()) {
7232       if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7233                                            diag::err_variable_object_no_init)) {
7234         return ExprError();
7235       }
7236     }
7237   } else if (!literalType->isDependentType() &&
7238              RequireCompleteType(LParenLoc, literalType,
7239                diag::err_typecheck_decl_incomplete_type,
7240                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7241     return ExprError();
7242 
7243   InitializedEntity Entity
7244     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7245   InitializationKind Kind
7246     = InitializationKind::CreateCStyleCast(LParenLoc,
7247                                            SourceRange(LParenLoc, RParenLoc),
7248                                            /*InitList=*/true);
7249   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7250   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7251                                       &literalType);
7252   if (Result.isInvalid())
7253     return ExprError();
7254   LiteralExpr = Result.get();
7255 
7256   bool isFileScope = !CurContext->isFunctionOrMethod();
7257 
7258   // In C, compound literals are l-values for some reason.
7259   // For GCC compatibility, in C++, file-scope array compound literals with
7260   // constant initializers are also l-values, and compound literals are
7261   // otherwise prvalues.
7262   //
7263   // (GCC also treats C++ list-initialized file-scope array prvalues with
7264   // constant initializers as l-values, but that's non-conforming, so we don't
7265   // follow it there.)
7266   //
7267   // FIXME: It would be better to handle the lvalue cases as materializing and
7268   // lifetime-extending a temporary object, but our materialized temporaries
7269   // representation only supports lifetime extension from a variable, not "out
7270   // of thin air".
7271   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7272   // is bound to the result of applying array-to-pointer decay to the compound
7273   // literal.
7274   // FIXME: GCC supports compound literals of reference type, which should
7275   // obviously have a value kind derived from the kind of reference involved.
7276   ExprValueKind VK =
7277       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7278           ? VK_PRValue
7279           : VK_LValue;
7280 
7281   if (isFileScope)
7282     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7283       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7284         Expr *Init = ILE->getInit(i);
7285         ILE->setInit(i, ConstantExpr::Create(Context, Init));
7286       }
7287 
7288   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7289                                               VK, LiteralExpr, isFileScope);
7290   if (isFileScope) {
7291     if (!LiteralExpr->isTypeDependent() &&
7292         !LiteralExpr->isValueDependent() &&
7293         !literalType->isDependentType()) // C99 6.5.2.5p3
7294       if (CheckForConstantInitializer(LiteralExpr, literalType))
7295         return ExprError();
7296   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7297              literalType.getAddressSpace() != LangAS::Default) {
7298     // Embedded-C extensions to C99 6.5.2.5:
7299     //   "If the compound literal occurs inside the body of a function, the
7300     //   type name shall not be qualified by an address-space qualifier."
7301     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7302       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7303     return ExprError();
7304   }
7305 
7306   if (!isFileScope && !getLangOpts().CPlusPlus) {
7307     // Compound literals that have automatic storage duration are destroyed at
7308     // the end of the scope in C; in C++, they're just temporaries.
7309 
7310     // Emit diagnostics if it is or contains a C union type that is non-trivial
7311     // to destruct.
7312     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7313       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7314                             NTCUC_CompoundLiteral, NTCUK_Destruct);
7315 
7316     // Diagnose jumps that enter or exit the lifetime of the compound literal.
7317     if (literalType.isDestructedType()) {
7318       Cleanup.setExprNeedsCleanups(true);
7319       ExprCleanupObjects.push_back(E);
7320       getCurFunction()->setHasBranchProtectedScope();
7321     }
7322   }
7323 
7324   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7325       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7326     checkNonTrivialCUnionInInitializer(E->getInitializer(),
7327                                        E->getInitializer()->getExprLoc());
7328 
7329   return MaybeBindToTemporary(E);
7330 }
7331 
7332 ExprResult
7333 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7334                     SourceLocation RBraceLoc) {
7335   // Only produce each kind of designated initialization diagnostic once.
7336   SourceLocation FirstDesignator;
7337   bool DiagnosedArrayDesignator = false;
7338   bool DiagnosedNestedDesignator = false;
7339   bool DiagnosedMixedDesignator = false;
7340 
7341   // Check that any designated initializers are syntactically valid in the
7342   // current language mode.
7343   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7344     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7345       if (FirstDesignator.isInvalid())
7346         FirstDesignator = DIE->getBeginLoc();
7347 
7348       if (!getLangOpts().CPlusPlus)
7349         break;
7350 
7351       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7352         DiagnosedNestedDesignator = true;
7353         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7354           << DIE->getDesignatorsSourceRange();
7355       }
7356 
7357       for (auto &Desig : DIE->designators()) {
7358         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7359           DiagnosedArrayDesignator = true;
7360           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7361             << Desig.getSourceRange();
7362         }
7363       }
7364 
7365       if (!DiagnosedMixedDesignator &&
7366           !isa<DesignatedInitExpr>(InitArgList[0])) {
7367         DiagnosedMixedDesignator = true;
7368         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7369           << DIE->getSourceRange();
7370         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7371           << InitArgList[0]->getSourceRange();
7372       }
7373     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7374                isa<DesignatedInitExpr>(InitArgList[0])) {
7375       DiagnosedMixedDesignator = true;
7376       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7377       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7378         << DIE->getSourceRange();
7379       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7380         << InitArgList[I]->getSourceRange();
7381     }
7382   }
7383 
7384   if (FirstDesignator.isValid()) {
7385     // Only diagnose designated initiaization as a C++20 extension if we didn't
7386     // already diagnose use of (non-C++20) C99 designator syntax.
7387     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7388         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7389       Diag(FirstDesignator, getLangOpts().CPlusPlus20
7390                                 ? diag::warn_cxx17_compat_designated_init
7391                                 : diag::ext_cxx_designated_init);
7392     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7393       Diag(FirstDesignator, diag::ext_designated_init);
7394     }
7395   }
7396 
7397   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7398 }
7399 
7400 ExprResult
7401 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7402                     SourceLocation RBraceLoc) {
7403   // Semantic analysis for initializers is done by ActOnDeclarator() and
7404   // CheckInitializer() - it requires knowledge of the object being initialized.
7405 
7406   // Immediately handle non-overload placeholders.  Overloads can be
7407   // resolved contextually, but everything else here can't.
7408   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7409     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7410       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7411 
7412       // Ignore failures; dropping the entire initializer list because
7413       // of one failure would be terrible for indexing/etc.
7414       if (result.isInvalid()) continue;
7415 
7416       InitArgList[I] = result.get();
7417     }
7418   }
7419 
7420   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7421                                                RBraceLoc);
7422   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7423   return E;
7424 }
7425 
7426 /// Do an explicit extend of the given block pointer if we're in ARC.
7427 void Sema::maybeExtendBlockObject(ExprResult &E) {
7428   assert(E.get()->getType()->isBlockPointerType());
7429   assert(E.get()->isPRValue());
7430 
7431   // Only do this in an r-value context.
7432   if (!getLangOpts().ObjCAutoRefCount) return;
7433 
7434   E = ImplicitCastExpr::Create(
7435       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7436       /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7437   Cleanup.setExprNeedsCleanups(true);
7438 }
7439 
7440 /// Prepare a conversion of the given expression to an ObjC object
7441 /// pointer type.
7442 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7443   QualType type = E.get()->getType();
7444   if (type->isObjCObjectPointerType()) {
7445     return CK_BitCast;
7446   } else if (type->isBlockPointerType()) {
7447     maybeExtendBlockObject(E);
7448     return CK_BlockPointerToObjCPointerCast;
7449   } else {
7450     assert(type->isPointerType());
7451     return CK_CPointerToObjCPointerCast;
7452   }
7453 }
7454 
7455 /// Prepares for a scalar cast, performing all the necessary stages
7456 /// except the final cast and returning the kind required.
7457 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7458   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7459   // Also, callers should have filtered out the invalid cases with
7460   // pointers.  Everything else should be possible.
7461 
7462   QualType SrcTy = Src.get()->getType();
7463   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7464     return CK_NoOp;
7465 
7466   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7467   case Type::STK_MemberPointer:
7468     llvm_unreachable("member pointer type in C");
7469 
7470   case Type::STK_CPointer:
7471   case Type::STK_BlockPointer:
7472   case Type::STK_ObjCObjectPointer:
7473     switch (DestTy->getScalarTypeKind()) {
7474     case Type::STK_CPointer: {
7475       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7476       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7477       if (SrcAS != DestAS)
7478         return CK_AddressSpaceConversion;
7479       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7480         return CK_NoOp;
7481       return CK_BitCast;
7482     }
7483     case Type::STK_BlockPointer:
7484       return (SrcKind == Type::STK_BlockPointer
7485                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7486     case Type::STK_ObjCObjectPointer:
7487       if (SrcKind == Type::STK_ObjCObjectPointer)
7488         return CK_BitCast;
7489       if (SrcKind == Type::STK_CPointer)
7490         return CK_CPointerToObjCPointerCast;
7491       maybeExtendBlockObject(Src);
7492       return CK_BlockPointerToObjCPointerCast;
7493     case Type::STK_Bool:
7494       return CK_PointerToBoolean;
7495     case Type::STK_Integral:
7496       return CK_PointerToIntegral;
7497     case Type::STK_Floating:
7498     case Type::STK_FloatingComplex:
7499     case Type::STK_IntegralComplex:
7500     case Type::STK_MemberPointer:
7501     case Type::STK_FixedPoint:
7502       llvm_unreachable("illegal cast from pointer");
7503     }
7504     llvm_unreachable("Should have returned before this");
7505 
7506   case Type::STK_FixedPoint:
7507     switch (DestTy->getScalarTypeKind()) {
7508     case Type::STK_FixedPoint:
7509       return CK_FixedPointCast;
7510     case Type::STK_Bool:
7511       return CK_FixedPointToBoolean;
7512     case Type::STK_Integral:
7513       return CK_FixedPointToIntegral;
7514     case Type::STK_Floating:
7515       return CK_FixedPointToFloating;
7516     case Type::STK_IntegralComplex:
7517     case Type::STK_FloatingComplex:
7518       Diag(Src.get()->getExprLoc(),
7519            diag::err_unimplemented_conversion_with_fixed_point_type)
7520           << DestTy;
7521       return CK_IntegralCast;
7522     case Type::STK_CPointer:
7523     case Type::STK_ObjCObjectPointer:
7524     case Type::STK_BlockPointer:
7525     case Type::STK_MemberPointer:
7526       llvm_unreachable("illegal cast to pointer type");
7527     }
7528     llvm_unreachable("Should have returned before this");
7529 
7530   case Type::STK_Bool: // casting from bool is like casting from an integer
7531   case Type::STK_Integral:
7532     switch (DestTy->getScalarTypeKind()) {
7533     case Type::STK_CPointer:
7534     case Type::STK_ObjCObjectPointer:
7535     case Type::STK_BlockPointer:
7536       if (Src.get()->isNullPointerConstant(Context,
7537                                            Expr::NPC_ValueDependentIsNull))
7538         return CK_NullToPointer;
7539       return CK_IntegralToPointer;
7540     case Type::STK_Bool:
7541       return CK_IntegralToBoolean;
7542     case Type::STK_Integral:
7543       return CK_IntegralCast;
7544     case Type::STK_Floating:
7545       return CK_IntegralToFloating;
7546     case Type::STK_IntegralComplex:
7547       Src = ImpCastExprToType(Src.get(),
7548                       DestTy->castAs<ComplexType>()->getElementType(),
7549                       CK_IntegralCast);
7550       return CK_IntegralRealToComplex;
7551     case Type::STK_FloatingComplex:
7552       Src = ImpCastExprToType(Src.get(),
7553                       DestTy->castAs<ComplexType>()->getElementType(),
7554                       CK_IntegralToFloating);
7555       return CK_FloatingRealToComplex;
7556     case Type::STK_MemberPointer:
7557       llvm_unreachable("member pointer type in C");
7558     case Type::STK_FixedPoint:
7559       return CK_IntegralToFixedPoint;
7560     }
7561     llvm_unreachable("Should have returned before this");
7562 
7563   case Type::STK_Floating:
7564     switch (DestTy->getScalarTypeKind()) {
7565     case Type::STK_Floating:
7566       return CK_FloatingCast;
7567     case Type::STK_Bool:
7568       return CK_FloatingToBoolean;
7569     case Type::STK_Integral:
7570       return CK_FloatingToIntegral;
7571     case Type::STK_FloatingComplex:
7572       Src = ImpCastExprToType(Src.get(),
7573                               DestTy->castAs<ComplexType>()->getElementType(),
7574                               CK_FloatingCast);
7575       return CK_FloatingRealToComplex;
7576     case Type::STK_IntegralComplex:
7577       Src = ImpCastExprToType(Src.get(),
7578                               DestTy->castAs<ComplexType>()->getElementType(),
7579                               CK_FloatingToIntegral);
7580       return CK_IntegralRealToComplex;
7581     case Type::STK_CPointer:
7582     case Type::STK_ObjCObjectPointer:
7583     case Type::STK_BlockPointer:
7584       llvm_unreachable("valid float->pointer cast?");
7585     case Type::STK_MemberPointer:
7586       llvm_unreachable("member pointer type in C");
7587     case Type::STK_FixedPoint:
7588       return CK_FloatingToFixedPoint;
7589     }
7590     llvm_unreachable("Should have returned before this");
7591 
7592   case Type::STK_FloatingComplex:
7593     switch (DestTy->getScalarTypeKind()) {
7594     case Type::STK_FloatingComplex:
7595       return CK_FloatingComplexCast;
7596     case Type::STK_IntegralComplex:
7597       return CK_FloatingComplexToIntegralComplex;
7598     case Type::STK_Floating: {
7599       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7600       if (Context.hasSameType(ET, DestTy))
7601         return CK_FloatingComplexToReal;
7602       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7603       return CK_FloatingCast;
7604     }
7605     case Type::STK_Bool:
7606       return CK_FloatingComplexToBoolean;
7607     case Type::STK_Integral:
7608       Src = ImpCastExprToType(Src.get(),
7609                               SrcTy->castAs<ComplexType>()->getElementType(),
7610                               CK_FloatingComplexToReal);
7611       return CK_FloatingToIntegral;
7612     case Type::STK_CPointer:
7613     case Type::STK_ObjCObjectPointer:
7614     case Type::STK_BlockPointer:
7615       llvm_unreachable("valid complex float->pointer cast?");
7616     case Type::STK_MemberPointer:
7617       llvm_unreachable("member pointer type in C");
7618     case Type::STK_FixedPoint:
7619       Diag(Src.get()->getExprLoc(),
7620            diag::err_unimplemented_conversion_with_fixed_point_type)
7621           << SrcTy;
7622       return CK_IntegralCast;
7623     }
7624     llvm_unreachable("Should have returned before this");
7625 
7626   case Type::STK_IntegralComplex:
7627     switch (DestTy->getScalarTypeKind()) {
7628     case Type::STK_FloatingComplex:
7629       return CK_IntegralComplexToFloatingComplex;
7630     case Type::STK_IntegralComplex:
7631       return CK_IntegralComplexCast;
7632     case Type::STK_Integral: {
7633       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7634       if (Context.hasSameType(ET, DestTy))
7635         return CK_IntegralComplexToReal;
7636       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7637       return CK_IntegralCast;
7638     }
7639     case Type::STK_Bool:
7640       return CK_IntegralComplexToBoolean;
7641     case Type::STK_Floating:
7642       Src = ImpCastExprToType(Src.get(),
7643                               SrcTy->castAs<ComplexType>()->getElementType(),
7644                               CK_IntegralComplexToReal);
7645       return CK_IntegralToFloating;
7646     case Type::STK_CPointer:
7647     case Type::STK_ObjCObjectPointer:
7648     case Type::STK_BlockPointer:
7649       llvm_unreachable("valid complex int->pointer cast?");
7650     case Type::STK_MemberPointer:
7651       llvm_unreachable("member pointer type in C");
7652     case Type::STK_FixedPoint:
7653       Diag(Src.get()->getExprLoc(),
7654            diag::err_unimplemented_conversion_with_fixed_point_type)
7655           << SrcTy;
7656       return CK_IntegralCast;
7657     }
7658     llvm_unreachable("Should have returned before this");
7659   }
7660 
7661   llvm_unreachable("Unhandled scalar cast");
7662 }
7663 
7664 static bool breakDownVectorType(QualType type, uint64_t &len,
7665                                 QualType &eltType) {
7666   // Vectors are simple.
7667   if (const VectorType *vecType = type->getAs<VectorType>()) {
7668     len = vecType->getNumElements();
7669     eltType = vecType->getElementType();
7670     assert(eltType->isScalarType());
7671     return true;
7672   }
7673 
7674   // We allow lax conversion to and from non-vector types, but only if
7675   // they're real types (i.e. non-complex, non-pointer scalar types).
7676   if (!type->isRealType()) return false;
7677 
7678   len = 1;
7679   eltType = type;
7680   return true;
7681 }
7682 
7683 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7684 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7685 /// allowed?
7686 ///
7687 /// This will also return false if the two given types do not make sense from
7688 /// the perspective of SVE bitcasts.
7689 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7690   assert(srcTy->isVectorType() || destTy->isVectorType());
7691 
7692   auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7693     if (!FirstType->isSizelessBuiltinType())
7694       return false;
7695 
7696     const auto *VecTy = SecondType->getAs<VectorType>();
7697     return VecTy &&
7698            VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7699   };
7700 
7701   return ValidScalableConversion(srcTy, destTy) ||
7702          ValidScalableConversion(destTy, srcTy);
7703 }
7704 
7705 /// Are the two types matrix types and do they have the same dimensions i.e.
7706 /// do they have the same number of rows and the same number of columns?
7707 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7708   if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7709     return false;
7710 
7711   const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7712   const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7713 
7714   return matSrcType->getNumRows() == matDestType->getNumRows() &&
7715          matSrcType->getNumColumns() == matDestType->getNumColumns();
7716 }
7717 
7718 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7719   assert(DestTy->isVectorType() || SrcTy->isVectorType());
7720 
7721   uint64_t SrcLen, DestLen;
7722   QualType SrcEltTy, DestEltTy;
7723   if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7724     return false;
7725   if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7726     return false;
7727 
7728   // ASTContext::getTypeSize will return the size rounded up to a
7729   // power of 2, so instead of using that, we need to use the raw
7730   // element size multiplied by the element count.
7731   uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7732   uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7733 
7734   return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7735 }
7736 
7737 // This returns true if at least one of the types is an altivec vector.
7738 bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
7739   assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7740          "expected at least one type to be a vector here");
7741 
7742   bool IsSrcTyAltivec =
7743       SrcTy->isVectorType() && (SrcTy->castAs<VectorType>()->getVectorKind() ==
7744                                 VectorType::AltiVecVector);
7745   bool IsDestTyAltivec = DestTy->isVectorType() &&
7746                          (DestTy->castAs<VectorType>()->getVectorKind() ==
7747                           VectorType::AltiVecVector);
7748 
7749   return (IsSrcTyAltivec || IsDestTyAltivec);
7750 }
7751 
7752 // This returns true if both vectors have the same element type.
7753 bool Sema::areSameVectorElemTypes(QualType SrcTy, QualType DestTy) {
7754   assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7755          "expected at least one type to be a vector here");
7756 
7757   uint64_t SrcLen, DestLen;
7758   QualType SrcEltTy, DestEltTy;
7759   if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7760     return false;
7761   if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7762     return false;
7763 
7764   return (SrcEltTy == DestEltTy);
7765 }
7766 
7767 /// Are the two types lax-compatible vector types?  That is, given
7768 /// that one of them is a vector, do they have equal storage sizes,
7769 /// where the storage size is the number of elements times the element
7770 /// size?
7771 ///
7772 /// This will also return false if either of the types is neither a
7773 /// vector nor a real type.
7774 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7775   assert(destTy->isVectorType() || srcTy->isVectorType());
7776 
7777   // Disallow lax conversions between scalars and ExtVectors (these
7778   // conversions are allowed for other vector types because common headers
7779   // depend on them).  Most scalar OP ExtVector cases are handled by the
7780   // splat path anyway, which does what we want (convert, not bitcast).
7781   // What this rules out for ExtVectors is crazy things like char4*float.
7782   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7783   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7784 
7785   return areVectorTypesSameSize(srcTy, destTy);
7786 }
7787 
7788 /// Is this a legal conversion between two types, one of which is
7789 /// known to be a vector type?
7790 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7791   assert(destTy->isVectorType() || srcTy->isVectorType());
7792 
7793   switch (Context.getLangOpts().getLaxVectorConversions()) {
7794   case LangOptions::LaxVectorConversionKind::None:
7795     return false;
7796 
7797   case LangOptions::LaxVectorConversionKind::Integer:
7798     if (!srcTy->isIntegralOrEnumerationType()) {
7799       auto *Vec = srcTy->getAs<VectorType>();
7800       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7801         return false;
7802     }
7803     if (!destTy->isIntegralOrEnumerationType()) {
7804       auto *Vec = destTy->getAs<VectorType>();
7805       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7806         return false;
7807     }
7808     // OK, integer (vector) -> integer (vector) bitcast.
7809     break;
7810 
7811     case LangOptions::LaxVectorConversionKind::All:
7812     break;
7813   }
7814 
7815   return areLaxCompatibleVectorTypes(srcTy, destTy);
7816 }
7817 
7818 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7819                            CastKind &Kind) {
7820   if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7821     if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7822       return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7823              << DestTy << SrcTy << R;
7824     }
7825   } else if (SrcTy->isMatrixType()) {
7826     return Diag(R.getBegin(),
7827                 diag::err_invalid_conversion_between_matrix_and_type)
7828            << SrcTy << DestTy << R;
7829   } else if (DestTy->isMatrixType()) {
7830     return Diag(R.getBegin(),
7831                 diag::err_invalid_conversion_between_matrix_and_type)
7832            << DestTy << SrcTy << R;
7833   }
7834 
7835   Kind = CK_MatrixCast;
7836   return false;
7837 }
7838 
7839 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7840                            CastKind &Kind) {
7841   assert(VectorTy->isVectorType() && "Not a vector type!");
7842 
7843   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7844     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7845       return Diag(R.getBegin(),
7846                   Ty->isVectorType() ?
7847                   diag::err_invalid_conversion_between_vectors :
7848                   diag::err_invalid_conversion_between_vector_and_integer)
7849         << VectorTy << Ty << R;
7850   } else
7851     return Diag(R.getBegin(),
7852                 diag::err_invalid_conversion_between_vector_and_scalar)
7853       << VectorTy << Ty << R;
7854 
7855   Kind = CK_BitCast;
7856   return false;
7857 }
7858 
7859 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7860   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7861 
7862   if (DestElemTy == SplattedExpr->getType())
7863     return SplattedExpr;
7864 
7865   assert(DestElemTy->isFloatingType() ||
7866          DestElemTy->isIntegralOrEnumerationType());
7867 
7868   CastKind CK;
7869   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7870     // OpenCL requires that we convert `true` boolean expressions to -1, but
7871     // only when splatting vectors.
7872     if (DestElemTy->isFloatingType()) {
7873       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7874       // in two steps: boolean to signed integral, then to floating.
7875       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7876                                                  CK_BooleanToSignedIntegral);
7877       SplattedExpr = CastExprRes.get();
7878       CK = CK_IntegralToFloating;
7879     } else {
7880       CK = CK_BooleanToSignedIntegral;
7881     }
7882   } else {
7883     ExprResult CastExprRes = SplattedExpr;
7884     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7885     if (CastExprRes.isInvalid())
7886       return ExprError();
7887     SplattedExpr = CastExprRes.get();
7888   }
7889   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7890 }
7891 
7892 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7893                                     Expr *CastExpr, CastKind &Kind) {
7894   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7895 
7896   QualType SrcTy = CastExpr->getType();
7897 
7898   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7899   // an ExtVectorType.
7900   // In OpenCL, casts between vectors of different types are not allowed.
7901   // (See OpenCL 6.2).
7902   if (SrcTy->isVectorType()) {
7903     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7904         (getLangOpts().OpenCL &&
7905          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7906       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7907         << DestTy << SrcTy << R;
7908       return ExprError();
7909     }
7910     Kind = CK_BitCast;
7911     return CastExpr;
7912   }
7913 
7914   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7915   // conversion will take place first from scalar to elt type, and then
7916   // splat from elt type to vector.
7917   if (SrcTy->isPointerType())
7918     return Diag(R.getBegin(),
7919                 diag::err_invalid_conversion_between_vector_and_scalar)
7920       << DestTy << SrcTy << R;
7921 
7922   Kind = CK_VectorSplat;
7923   return prepareVectorSplat(DestTy, CastExpr);
7924 }
7925 
7926 ExprResult
7927 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7928                     Declarator &D, ParsedType &Ty,
7929                     SourceLocation RParenLoc, Expr *CastExpr) {
7930   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7931          "ActOnCastExpr(): missing type or expr");
7932 
7933   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7934   if (D.isInvalidType())
7935     return ExprError();
7936 
7937   if (getLangOpts().CPlusPlus) {
7938     // Check that there are no default arguments (C++ only).
7939     CheckExtraCXXDefaultArguments(D);
7940   } else {
7941     // Make sure any TypoExprs have been dealt with.
7942     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7943     if (!Res.isUsable())
7944       return ExprError();
7945     CastExpr = Res.get();
7946   }
7947 
7948   checkUnusedDeclAttributes(D);
7949 
7950   QualType castType = castTInfo->getType();
7951   Ty = CreateParsedType(castType, castTInfo);
7952 
7953   bool isVectorLiteral = false;
7954 
7955   // Check for an altivec or OpenCL literal,
7956   // i.e. all the elements are integer constants.
7957   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7958   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7959   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7960        && castType->isVectorType() && (PE || PLE)) {
7961     if (PLE && PLE->getNumExprs() == 0) {
7962       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7963       return ExprError();
7964     }
7965     if (PE || PLE->getNumExprs() == 1) {
7966       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7967       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7968         isVectorLiteral = true;
7969     }
7970     else
7971       isVectorLiteral = true;
7972   }
7973 
7974   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7975   // then handle it as such.
7976   if (isVectorLiteral)
7977     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7978 
7979   // If the Expr being casted is a ParenListExpr, handle it specially.
7980   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7981   // sequence of BinOp comma operators.
7982   if (isa<ParenListExpr>(CastExpr)) {
7983     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7984     if (Result.isInvalid()) return ExprError();
7985     CastExpr = Result.get();
7986   }
7987 
7988   if (getLangOpts().CPlusPlus && !castType->isVoidType())
7989     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7990 
7991   CheckTollFreeBridgeCast(castType, CastExpr);
7992 
7993   CheckObjCBridgeRelatedCast(castType, CastExpr);
7994 
7995   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7996 
7997   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7998 }
7999 
8000 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8001                                     SourceLocation RParenLoc, Expr *E,
8002                                     TypeSourceInfo *TInfo) {
8003   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8004          "Expected paren or paren list expression");
8005 
8006   Expr **exprs;
8007   unsigned numExprs;
8008   Expr *subExpr;
8009   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8010   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8011     LiteralLParenLoc = PE->getLParenLoc();
8012     LiteralRParenLoc = PE->getRParenLoc();
8013     exprs = PE->getExprs();
8014     numExprs = PE->getNumExprs();
8015   } else { // isa<ParenExpr> by assertion at function entrance
8016     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8017     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8018     subExpr = cast<ParenExpr>(E)->getSubExpr();
8019     exprs = &subExpr;
8020     numExprs = 1;
8021   }
8022 
8023   QualType Ty = TInfo->getType();
8024   assert(Ty->isVectorType() && "Expected vector type");
8025 
8026   SmallVector<Expr *, 8> initExprs;
8027   const VectorType *VTy = Ty->castAs<VectorType>();
8028   unsigned numElems = VTy->getNumElements();
8029 
8030   // '(...)' form of vector initialization in AltiVec: the number of
8031   // initializers must be one or must match the size of the vector.
8032   // If a single value is specified in the initializer then it will be
8033   // replicated to all the components of the vector
8034   if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
8035                                  VTy->getElementType()))
8036     return ExprError();
8037   if (ShouldSplatAltivecScalarInCast(VTy)) {
8038     // The number of initializers must be one or must match the size of the
8039     // vector. If a single value is specified in the initializer then it will
8040     // be replicated to all the components of the vector
8041     if (numExprs == 1) {
8042       QualType ElemTy = VTy->getElementType();
8043       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8044       if (Literal.isInvalid())
8045         return ExprError();
8046       Literal = ImpCastExprToType(Literal.get(), ElemTy,
8047                                   PrepareScalarCast(Literal, ElemTy));
8048       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8049     }
8050     else if (numExprs < numElems) {
8051       Diag(E->getExprLoc(),
8052            diag::err_incorrect_number_of_vector_initializers);
8053       return ExprError();
8054     }
8055     else
8056       initExprs.append(exprs, exprs + numExprs);
8057   }
8058   else {
8059     // For OpenCL, when the number of initializers is a single value,
8060     // it will be replicated to all components of the vector.
8061     if (getLangOpts().OpenCL &&
8062         VTy->getVectorKind() == VectorType::GenericVector &&
8063         numExprs == 1) {
8064         QualType ElemTy = VTy->getElementType();
8065         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8066         if (Literal.isInvalid())
8067           return ExprError();
8068         Literal = ImpCastExprToType(Literal.get(), ElemTy,
8069                                     PrepareScalarCast(Literal, ElemTy));
8070         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8071     }
8072 
8073     initExprs.append(exprs, exprs + numExprs);
8074   }
8075   // FIXME: This means that pretty-printing the final AST will produce curly
8076   // braces instead of the original commas.
8077   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8078                                                    initExprs, LiteralRParenLoc);
8079   initE->setType(Ty);
8080   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8081 }
8082 
8083 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8084 /// the ParenListExpr into a sequence of comma binary operators.
8085 ExprResult
8086 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8087   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8088   if (!E)
8089     return OrigExpr;
8090 
8091   ExprResult Result(E->getExpr(0));
8092 
8093   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8094     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8095                         E->getExpr(i));
8096 
8097   if (Result.isInvalid()) return ExprError();
8098 
8099   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8100 }
8101 
8102 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8103                                     SourceLocation R,
8104                                     MultiExprArg Val) {
8105   return ParenListExpr::Create(Context, L, Val, R);
8106 }
8107 
8108 /// Emit a specialized diagnostic when one expression is a null pointer
8109 /// constant and the other is not a pointer.  Returns true if a diagnostic is
8110 /// emitted.
8111 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8112                                       SourceLocation QuestionLoc) {
8113   Expr *NullExpr = LHSExpr;
8114   Expr *NonPointerExpr = RHSExpr;
8115   Expr::NullPointerConstantKind NullKind =
8116       NullExpr->isNullPointerConstant(Context,
8117                                       Expr::NPC_ValueDependentIsNotNull);
8118 
8119   if (NullKind == Expr::NPCK_NotNull) {
8120     NullExpr = RHSExpr;
8121     NonPointerExpr = LHSExpr;
8122     NullKind =
8123         NullExpr->isNullPointerConstant(Context,
8124                                         Expr::NPC_ValueDependentIsNotNull);
8125   }
8126 
8127   if (NullKind == Expr::NPCK_NotNull)
8128     return false;
8129 
8130   if (NullKind == Expr::NPCK_ZeroExpression)
8131     return false;
8132 
8133   if (NullKind == Expr::NPCK_ZeroLiteral) {
8134     // In this case, check to make sure that we got here from a "NULL"
8135     // string in the source code.
8136     NullExpr = NullExpr->IgnoreParenImpCasts();
8137     SourceLocation loc = NullExpr->getExprLoc();
8138     if (!findMacroSpelling(loc, "NULL"))
8139       return false;
8140   }
8141 
8142   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8143   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8144       << NonPointerExpr->getType() << DiagType
8145       << NonPointerExpr->getSourceRange();
8146   return true;
8147 }
8148 
8149 /// Return false if the condition expression is valid, true otherwise.
8150 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
8151   QualType CondTy = Cond->getType();
8152 
8153   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8154   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8155     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8156       << CondTy << Cond->getSourceRange();
8157     return true;
8158   }
8159 
8160   // C99 6.5.15p2
8161   if (CondTy->isScalarType()) return false;
8162 
8163   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8164     << CondTy << Cond->getSourceRange();
8165   return true;
8166 }
8167 
8168 /// Handle when one or both operands are void type.
8169 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
8170                                          ExprResult &RHS) {
8171     Expr *LHSExpr = LHS.get();
8172     Expr *RHSExpr = RHS.get();
8173 
8174     if (!LHSExpr->getType()->isVoidType())
8175       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8176           << RHSExpr->getSourceRange();
8177     if (!RHSExpr->getType()->isVoidType())
8178       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8179           << LHSExpr->getSourceRange();
8180     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
8181     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
8182     return S.Context.VoidTy;
8183 }
8184 
8185 /// Return false if the NullExpr can be promoted to PointerTy,
8186 /// true otherwise.
8187 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8188                                         QualType PointerTy) {
8189   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8190       !NullExpr.get()->isNullPointerConstant(S.Context,
8191                                             Expr::NPC_ValueDependentIsNull))
8192     return true;
8193 
8194   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8195   return false;
8196 }
8197 
8198 /// Checks compatibility between two pointers and return the resulting
8199 /// type.
8200 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8201                                                      ExprResult &RHS,
8202                                                      SourceLocation Loc) {
8203   QualType LHSTy = LHS.get()->getType();
8204   QualType RHSTy = RHS.get()->getType();
8205 
8206   if (S.Context.hasSameType(LHSTy, RHSTy)) {
8207     // Two identical pointers types are always compatible.
8208     return LHSTy;
8209   }
8210 
8211   QualType lhptee, rhptee;
8212 
8213   // Get the pointee types.
8214   bool IsBlockPointer = false;
8215   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8216     lhptee = LHSBTy->getPointeeType();
8217     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8218     IsBlockPointer = true;
8219   } else {
8220     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8221     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8222   }
8223 
8224   // C99 6.5.15p6: If both operands are pointers to compatible types or to
8225   // differently qualified versions of compatible types, the result type is
8226   // a pointer to an appropriately qualified version of the composite
8227   // type.
8228 
8229   // Only CVR-qualifiers exist in the standard, and the differently-qualified
8230   // clause doesn't make sense for our extensions. E.g. address space 2 should
8231   // be incompatible with address space 3: they may live on different devices or
8232   // anything.
8233   Qualifiers lhQual = lhptee.getQualifiers();
8234   Qualifiers rhQual = rhptee.getQualifiers();
8235 
8236   LangAS ResultAddrSpace = LangAS::Default;
8237   LangAS LAddrSpace = lhQual.getAddressSpace();
8238   LangAS RAddrSpace = rhQual.getAddressSpace();
8239 
8240   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8241   // spaces is disallowed.
8242   if (lhQual.isAddressSpaceSupersetOf(rhQual))
8243     ResultAddrSpace = LAddrSpace;
8244   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8245     ResultAddrSpace = RAddrSpace;
8246   else {
8247     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8248         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8249         << RHS.get()->getSourceRange();
8250     return QualType();
8251   }
8252 
8253   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8254   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8255   lhQual.removeCVRQualifiers();
8256   rhQual.removeCVRQualifiers();
8257 
8258   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8259   // (C99 6.7.3) for address spaces. We assume that the check should behave in
8260   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8261   // qual types are compatible iff
8262   //  * corresponded types are compatible
8263   //  * CVR qualifiers are equal
8264   //  * address spaces are equal
8265   // Thus for conditional operator we merge CVR and address space unqualified
8266   // pointees and if there is a composite type we return a pointer to it with
8267   // merged qualifiers.
8268   LHSCastKind =
8269       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8270   RHSCastKind =
8271       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8272   lhQual.removeAddressSpace();
8273   rhQual.removeAddressSpace();
8274 
8275   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8276   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8277 
8278   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
8279 
8280   if (CompositeTy.isNull()) {
8281     // In this situation, we assume void* type. No especially good
8282     // reason, but this is what gcc does, and we do have to pick
8283     // to get a consistent AST.
8284     QualType incompatTy;
8285     incompatTy = S.Context.getPointerType(
8286         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8287     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8288     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8289 
8290     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8291     // for casts between types with incompatible address space qualifiers.
8292     // For the following code the compiler produces casts between global and
8293     // local address spaces of the corresponded innermost pointees:
8294     // local int *global *a;
8295     // global int *global *b;
8296     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8297     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8298         << LHSTy << RHSTy << LHS.get()->getSourceRange()
8299         << RHS.get()->getSourceRange();
8300 
8301     return incompatTy;
8302   }
8303 
8304   // The pointer types are compatible.
8305   // In case of OpenCL ResultTy should have the address space qualifier
8306   // which is a superset of address spaces of both the 2nd and the 3rd
8307   // operands of the conditional operator.
8308   QualType ResultTy = [&, ResultAddrSpace]() {
8309     if (S.getLangOpts().OpenCL) {
8310       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8311       CompositeQuals.setAddressSpace(ResultAddrSpace);
8312       return S.Context
8313           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8314           .withCVRQualifiers(MergedCVRQual);
8315     }
8316     return CompositeTy.withCVRQualifiers(MergedCVRQual);
8317   }();
8318   if (IsBlockPointer)
8319     ResultTy = S.Context.getBlockPointerType(ResultTy);
8320   else
8321     ResultTy = S.Context.getPointerType(ResultTy);
8322 
8323   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8324   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8325   return ResultTy;
8326 }
8327 
8328 /// Return the resulting type when the operands are both block pointers.
8329 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8330                                                           ExprResult &LHS,
8331                                                           ExprResult &RHS,
8332                                                           SourceLocation Loc) {
8333   QualType LHSTy = LHS.get()->getType();
8334   QualType RHSTy = RHS.get()->getType();
8335 
8336   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8337     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8338       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8339       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8340       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8341       return destType;
8342     }
8343     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8344       << LHSTy << RHSTy << LHS.get()->getSourceRange()
8345       << RHS.get()->getSourceRange();
8346     return QualType();
8347   }
8348 
8349   // We have 2 block pointer types.
8350   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8351 }
8352 
8353 /// Return the resulting type when the operands are both pointers.
8354 static QualType
8355 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8356                                             ExprResult &RHS,
8357                                             SourceLocation Loc) {
8358   // get the pointer types
8359   QualType LHSTy = LHS.get()->getType();
8360   QualType RHSTy = RHS.get()->getType();
8361 
8362   // get the "pointed to" types
8363   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8364   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8365 
8366   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8367   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8368     // Figure out necessary qualifiers (C99 6.5.15p6)
8369     QualType destPointee
8370       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8371     QualType destType = S.Context.getPointerType(destPointee);
8372     // Add qualifiers if necessary.
8373     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8374     // Promote to void*.
8375     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8376     return destType;
8377   }
8378   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8379     QualType destPointee
8380       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8381     QualType destType = S.Context.getPointerType(destPointee);
8382     // Add qualifiers if necessary.
8383     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8384     // Promote to void*.
8385     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8386     return destType;
8387   }
8388 
8389   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8390 }
8391 
8392 /// Return false if the first expression is not an integer and the second
8393 /// expression is not a pointer, true otherwise.
8394 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8395                                         Expr* PointerExpr, SourceLocation Loc,
8396                                         bool IsIntFirstExpr) {
8397   if (!PointerExpr->getType()->isPointerType() ||
8398       !Int.get()->getType()->isIntegerType())
8399     return false;
8400 
8401   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8402   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8403 
8404   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8405     << Expr1->getType() << Expr2->getType()
8406     << Expr1->getSourceRange() << Expr2->getSourceRange();
8407   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8408                             CK_IntegralToPointer);
8409   return true;
8410 }
8411 
8412 /// Simple conversion between integer and floating point types.
8413 ///
8414 /// Used when handling the OpenCL conditional operator where the
8415 /// condition is a vector while the other operands are scalar.
8416 ///
8417 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8418 /// types are either integer or floating type. Between the two
8419 /// operands, the type with the higher rank is defined as the "result
8420 /// type". The other operand needs to be promoted to the same type. No
8421 /// other type promotion is allowed. We cannot use
8422 /// UsualArithmeticConversions() for this purpose, since it always
8423 /// promotes promotable types.
8424 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8425                                             ExprResult &RHS,
8426                                             SourceLocation QuestionLoc) {
8427   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8428   if (LHS.isInvalid())
8429     return QualType();
8430   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8431   if (RHS.isInvalid())
8432     return QualType();
8433 
8434   // For conversion purposes, we ignore any qualifiers.
8435   // For example, "const float" and "float" are equivalent.
8436   QualType LHSType =
8437     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8438   QualType RHSType =
8439     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8440 
8441   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8442     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8443       << LHSType << LHS.get()->getSourceRange();
8444     return QualType();
8445   }
8446 
8447   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8448     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8449       << RHSType << RHS.get()->getSourceRange();
8450     return QualType();
8451   }
8452 
8453   // If both types are identical, no conversion is needed.
8454   if (LHSType == RHSType)
8455     return LHSType;
8456 
8457   // Now handle "real" floating types (i.e. float, double, long double).
8458   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8459     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8460                                  /*IsCompAssign = */ false);
8461 
8462   // Finally, we have two differing integer types.
8463   return handleIntegerConversion<doIntegralCast, doIntegralCast>
8464   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8465 }
8466 
8467 /// Convert scalar operands to a vector that matches the
8468 ///        condition in length.
8469 ///
8470 /// Used when handling the OpenCL conditional operator where the
8471 /// condition is a vector while the other operands are scalar.
8472 ///
8473 /// We first compute the "result type" for the scalar operands
8474 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8475 /// into a vector of that type where the length matches the condition
8476 /// vector type. s6.11.6 requires that the element types of the result
8477 /// and the condition must have the same number of bits.
8478 static QualType
8479 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8480                               QualType CondTy, SourceLocation QuestionLoc) {
8481   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8482   if (ResTy.isNull()) return QualType();
8483 
8484   const VectorType *CV = CondTy->getAs<VectorType>();
8485   assert(CV);
8486 
8487   // Determine the vector result type
8488   unsigned NumElements = CV->getNumElements();
8489   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8490 
8491   // Ensure that all types have the same number of bits
8492   if (S.Context.getTypeSize(CV->getElementType())
8493       != S.Context.getTypeSize(ResTy)) {
8494     // Since VectorTy is created internally, it does not pretty print
8495     // with an OpenCL name. Instead, we just print a description.
8496     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8497     SmallString<64> Str;
8498     llvm::raw_svector_ostream OS(Str);
8499     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8500     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8501       << CondTy << OS.str();
8502     return QualType();
8503   }
8504 
8505   // Convert operands to the vector result type
8506   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8507   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8508 
8509   return VectorTy;
8510 }
8511 
8512 /// Return false if this is a valid OpenCL condition vector
8513 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8514                                        SourceLocation QuestionLoc) {
8515   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8516   // integral type.
8517   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8518   assert(CondTy);
8519   QualType EleTy = CondTy->getElementType();
8520   if (EleTy->isIntegerType()) return false;
8521 
8522   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8523     << Cond->getType() << Cond->getSourceRange();
8524   return true;
8525 }
8526 
8527 /// Return false if the vector condition type and the vector
8528 ///        result type are compatible.
8529 ///
8530 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8531 /// number of elements, and their element types have the same number
8532 /// of bits.
8533 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8534                               SourceLocation QuestionLoc) {
8535   const VectorType *CV = CondTy->getAs<VectorType>();
8536   const VectorType *RV = VecResTy->getAs<VectorType>();
8537   assert(CV && RV);
8538 
8539   if (CV->getNumElements() != RV->getNumElements()) {
8540     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8541       << CondTy << VecResTy;
8542     return true;
8543   }
8544 
8545   QualType CVE = CV->getElementType();
8546   QualType RVE = RV->getElementType();
8547 
8548   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8549     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8550       << CondTy << VecResTy;
8551     return true;
8552   }
8553 
8554   return false;
8555 }
8556 
8557 /// Return the resulting type for the conditional operator in
8558 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8559 ///        s6.3.i) when the condition is a vector type.
8560 static QualType
8561 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8562                              ExprResult &LHS, ExprResult &RHS,
8563                              SourceLocation QuestionLoc) {
8564   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8565   if (Cond.isInvalid())
8566     return QualType();
8567   QualType CondTy = Cond.get()->getType();
8568 
8569   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8570     return QualType();
8571 
8572   // If either operand is a vector then find the vector type of the
8573   // result as specified in OpenCL v1.1 s6.3.i.
8574   if (LHS.get()->getType()->isVectorType() ||
8575       RHS.get()->getType()->isVectorType()) {
8576     bool IsBoolVecLang =
8577         !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8578     QualType VecResTy =
8579         S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8580                               /*isCompAssign*/ false,
8581                               /*AllowBothBool*/ true,
8582                               /*AllowBoolConversions*/ false,
8583                               /*AllowBooleanOperation*/ IsBoolVecLang,
8584                               /*ReportInvalid*/ true);
8585     if (VecResTy.isNull())
8586       return QualType();
8587     // The result type must match the condition type as specified in
8588     // OpenCL v1.1 s6.11.6.
8589     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8590       return QualType();
8591     return VecResTy;
8592   }
8593 
8594   // Both operands are scalar.
8595   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8596 }
8597 
8598 /// Return true if the Expr is block type
8599 static bool checkBlockType(Sema &S, const Expr *E) {
8600   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8601     QualType Ty = CE->getCallee()->getType();
8602     if (Ty->isBlockPointerType()) {
8603       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8604       return true;
8605     }
8606   }
8607   return false;
8608 }
8609 
8610 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8611 /// In that case, LHS = cond.
8612 /// C99 6.5.15
8613 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8614                                         ExprResult &RHS, ExprValueKind &VK,
8615                                         ExprObjectKind &OK,
8616                                         SourceLocation QuestionLoc) {
8617 
8618   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8619   if (!LHSResult.isUsable()) return QualType();
8620   LHS = LHSResult;
8621 
8622   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8623   if (!RHSResult.isUsable()) return QualType();
8624   RHS = RHSResult;
8625 
8626   // C++ is sufficiently different to merit its own checker.
8627   if (getLangOpts().CPlusPlus)
8628     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8629 
8630   VK = VK_PRValue;
8631   OK = OK_Ordinary;
8632 
8633   if (Context.isDependenceAllowed() &&
8634       (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8635        RHS.get()->isTypeDependent())) {
8636     assert(!getLangOpts().CPlusPlus);
8637     assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8638             RHS.get()->containsErrors()) &&
8639            "should only occur in error-recovery path.");
8640     return Context.DependentTy;
8641   }
8642 
8643   // The OpenCL operator with a vector condition is sufficiently
8644   // different to merit its own checker.
8645   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8646       Cond.get()->getType()->isExtVectorType())
8647     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8648 
8649   // First, check the condition.
8650   Cond = UsualUnaryConversions(Cond.get());
8651   if (Cond.isInvalid())
8652     return QualType();
8653   if (checkCondition(*this, Cond.get(), QuestionLoc))
8654     return QualType();
8655 
8656   // Now check the two expressions.
8657   if (LHS.get()->getType()->isVectorType() ||
8658       RHS.get()->getType()->isVectorType())
8659     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8660                                /*AllowBothBool*/ true,
8661                                /*AllowBoolConversions*/ false,
8662                                /*AllowBooleanOperation*/ false,
8663                                /*ReportInvalid*/ true);
8664 
8665   QualType ResTy =
8666       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8667   if (LHS.isInvalid() || RHS.isInvalid())
8668     return QualType();
8669 
8670   QualType LHSTy = LHS.get()->getType();
8671   QualType RHSTy = RHS.get()->getType();
8672 
8673   // Diagnose attempts to convert between __ibm128, __float128 and long double
8674   // where such conversions currently can't be handled.
8675   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8676     Diag(QuestionLoc,
8677          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8678       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8679     return QualType();
8680   }
8681 
8682   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8683   // selection operator (?:).
8684   if (getLangOpts().OpenCL &&
8685       ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8686     return QualType();
8687   }
8688 
8689   // If both operands have arithmetic type, do the usual arithmetic conversions
8690   // to find a common type: C99 6.5.15p3,5.
8691   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8692     // Disallow invalid arithmetic conversions, such as those between bit-
8693     // precise integers types of different sizes, or between a bit-precise
8694     // integer and another type.
8695     if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8696       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8697           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8698           << RHS.get()->getSourceRange();
8699       return QualType();
8700     }
8701 
8702     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8703     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8704 
8705     return ResTy;
8706   }
8707 
8708   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8709   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8710     return LHSTy;
8711   }
8712 
8713   // If both operands are the same structure or union type, the result is that
8714   // type.
8715   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8716     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8717       if (LHSRT->getDecl() == RHSRT->getDecl())
8718         // "If both the operands have structure or union type, the result has
8719         // that type."  This implies that CV qualifiers are dropped.
8720         return LHSTy.getUnqualifiedType();
8721     // FIXME: Type of conditional expression must be complete in C mode.
8722   }
8723 
8724   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8725   // The following || allows only one side to be void (a GCC-ism).
8726   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8727     return checkConditionalVoidType(*this, LHS, RHS);
8728   }
8729 
8730   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8731   // the type of the other operand."
8732   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8733   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8734 
8735   // All objective-c pointer type analysis is done here.
8736   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8737                                                         QuestionLoc);
8738   if (LHS.isInvalid() || RHS.isInvalid())
8739     return QualType();
8740   if (!compositeType.isNull())
8741     return compositeType;
8742 
8743 
8744   // Handle block pointer types.
8745   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8746     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8747                                                      QuestionLoc);
8748 
8749   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8750   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8751     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8752                                                        QuestionLoc);
8753 
8754   // GCC compatibility: soften pointer/integer mismatch.  Note that
8755   // null pointers have been filtered out by this point.
8756   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8757       /*IsIntFirstExpr=*/true))
8758     return RHSTy;
8759   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8760       /*IsIntFirstExpr=*/false))
8761     return LHSTy;
8762 
8763   // Allow ?: operations in which both operands have the same
8764   // built-in sizeless type.
8765   if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8766     return LHSTy;
8767 
8768   // Emit a better diagnostic if one of the expressions is a null pointer
8769   // constant and the other is not a pointer type. In this case, the user most
8770   // likely forgot to take the address of the other expression.
8771   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8772     return QualType();
8773 
8774   // Otherwise, the operands are not compatible.
8775   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8776     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8777     << RHS.get()->getSourceRange();
8778   return QualType();
8779 }
8780 
8781 /// FindCompositeObjCPointerType - Helper method to find composite type of
8782 /// two objective-c pointer types of the two input expressions.
8783 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8784                                             SourceLocation QuestionLoc) {
8785   QualType LHSTy = LHS.get()->getType();
8786   QualType RHSTy = RHS.get()->getType();
8787 
8788   // Handle things like Class and struct objc_class*.  Here we case the result
8789   // to the pseudo-builtin, because that will be implicitly cast back to the
8790   // redefinition type if an attempt is made to access its fields.
8791   if (LHSTy->isObjCClassType() &&
8792       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8793     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8794     return LHSTy;
8795   }
8796   if (RHSTy->isObjCClassType() &&
8797       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8798     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8799     return RHSTy;
8800   }
8801   // And the same for struct objc_object* / id
8802   if (LHSTy->isObjCIdType() &&
8803       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8804     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8805     return LHSTy;
8806   }
8807   if (RHSTy->isObjCIdType() &&
8808       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8809     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8810     return RHSTy;
8811   }
8812   // And the same for struct objc_selector* / SEL
8813   if (Context.isObjCSelType(LHSTy) &&
8814       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8815     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8816     return LHSTy;
8817   }
8818   if (Context.isObjCSelType(RHSTy) &&
8819       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8820     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8821     return RHSTy;
8822   }
8823   // Check constraints for Objective-C object pointers types.
8824   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8825 
8826     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8827       // Two identical object pointer types are always compatible.
8828       return LHSTy;
8829     }
8830     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8831     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8832     QualType compositeType = LHSTy;
8833 
8834     // If both operands are interfaces and either operand can be
8835     // assigned to the other, use that type as the composite
8836     // type. This allows
8837     //   xxx ? (A*) a : (B*) b
8838     // where B is a subclass of A.
8839     //
8840     // Additionally, as for assignment, if either type is 'id'
8841     // allow silent coercion. Finally, if the types are
8842     // incompatible then make sure to use 'id' as the composite
8843     // type so the result is acceptable for sending messages to.
8844 
8845     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8846     // It could return the composite type.
8847     if (!(compositeType =
8848           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8849       // Nothing more to do.
8850     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8851       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8852     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8853       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8854     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8855                 RHSOPT->isObjCQualifiedIdType()) &&
8856                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8857                                                          true)) {
8858       // Need to handle "id<xx>" explicitly.
8859       // GCC allows qualified id and any Objective-C type to devolve to
8860       // id. Currently localizing to here until clear this should be
8861       // part of ObjCQualifiedIdTypesAreCompatible.
8862       compositeType = Context.getObjCIdType();
8863     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8864       compositeType = Context.getObjCIdType();
8865     } else {
8866       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8867       << LHSTy << RHSTy
8868       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8869       QualType incompatTy = Context.getObjCIdType();
8870       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8871       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8872       return incompatTy;
8873     }
8874     // The object pointer types are compatible.
8875     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8876     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8877     return compositeType;
8878   }
8879   // Check Objective-C object pointer types and 'void *'
8880   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8881     if (getLangOpts().ObjCAutoRefCount) {
8882       // ARC forbids the implicit conversion of object pointers to 'void *',
8883       // so these types are not compatible.
8884       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8885           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8886       LHS = RHS = true;
8887       return QualType();
8888     }
8889     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8890     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8891     QualType destPointee
8892     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8893     QualType destType = Context.getPointerType(destPointee);
8894     // Add qualifiers if necessary.
8895     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8896     // Promote to void*.
8897     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8898     return destType;
8899   }
8900   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8901     if (getLangOpts().ObjCAutoRefCount) {
8902       // ARC forbids the implicit conversion of object pointers to 'void *',
8903       // so these types are not compatible.
8904       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8905           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8906       LHS = RHS = true;
8907       return QualType();
8908     }
8909     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8910     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8911     QualType destPointee
8912     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8913     QualType destType = Context.getPointerType(destPointee);
8914     // Add qualifiers if necessary.
8915     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8916     // Promote to void*.
8917     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8918     return destType;
8919   }
8920   return QualType();
8921 }
8922 
8923 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8924 /// ParenRange in parentheses.
8925 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8926                                const PartialDiagnostic &Note,
8927                                SourceRange ParenRange) {
8928   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8929   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8930       EndLoc.isValid()) {
8931     Self.Diag(Loc, Note)
8932       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8933       << FixItHint::CreateInsertion(EndLoc, ")");
8934   } else {
8935     // We can't display the parentheses, so just show the bare note.
8936     Self.Diag(Loc, Note) << ParenRange;
8937   }
8938 }
8939 
8940 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8941   return BinaryOperator::isAdditiveOp(Opc) ||
8942          BinaryOperator::isMultiplicativeOp(Opc) ||
8943          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8944   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8945   // not any of the logical operators.  Bitwise-xor is commonly used as a
8946   // logical-xor because there is no logical-xor operator.  The logical
8947   // operators, including uses of xor, have a high false positive rate for
8948   // precedence warnings.
8949 }
8950 
8951 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8952 /// expression, either using a built-in or overloaded operator,
8953 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8954 /// expression.
8955 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8956                                    Expr **RHSExprs) {
8957   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8958   E = E->IgnoreImpCasts();
8959   E = E->IgnoreConversionOperatorSingleStep();
8960   E = E->IgnoreImpCasts();
8961   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8962     E = MTE->getSubExpr();
8963     E = E->IgnoreImpCasts();
8964   }
8965 
8966   // Built-in binary operator.
8967   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8968     if (IsArithmeticOp(OP->getOpcode())) {
8969       *Opcode = OP->getOpcode();
8970       *RHSExprs = OP->getRHS();
8971       return true;
8972     }
8973   }
8974 
8975   // Overloaded operator.
8976   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8977     if (Call->getNumArgs() != 2)
8978       return false;
8979 
8980     // Make sure this is really a binary operator that is safe to pass into
8981     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8982     OverloadedOperatorKind OO = Call->getOperator();
8983     if (OO < OO_Plus || OO > OO_Arrow ||
8984         OO == OO_PlusPlus || OO == OO_MinusMinus)
8985       return false;
8986 
8987     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8988     if (IsArithmeticOp(OpKind)) {
8989       *Opcode = OpKind;
8990       *RHSExprs = Call->getArg(1);
8991       return true;
8992     }
8993   }
8994 
8995   return false;
8996 }
8997 
8998 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8999 /// or is a logical expression such as (x==y) which has int type, but is
9000 /// commonly interpreted as boolean.
9001 static bool ExprLooksBoolean(Expr *E) {
9002   E = E->IgnoreParenImpCasts();
9003 
9004   if (E->getType()->isBooleanType())
9005     return true;
9006   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
9007     return OP->isComparisonOp() || OP->isLogicalOp();
9008   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
9009     return OP->getOpcode() == UO_LNot;
9010   if (E->getType()->isPointerType())
9011     return true;
9012   // FIXME: What about overloaded operator calls returning "unspecified boolean
9013   // type"s (commonly pointer-to-members)?
9014 
9015   return false;
9016 }
9017 
9018 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9019 /// and binary operator are mixed in a way that suggests the programmer assumed
9020 /// the conditional operator has higher precedence, for example:
9021 /// "int x = a + someBinaryCondition ? 1 : 2".
9022 static void DiagnoseConditionalPrecedence(Sema &Self,
9023                                           SourceLocation OpLoc,
9024                                           Expr *Condition,
9025                                           Expr *LHSExpr,
9026                                           Expr *RHSExpr) {
9027   BinaryOperatorKind CondOpcode;
9028   Expr *CondRHS;
9029 
9030   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9031     return;
9032   if (!ExprLooksBoolean(CondRHS))
9033     return;
9034 
9035   // The condition is an arithmetic binary expression, with a right-
9036   // hand side that looks boolean, so warn.
9037 
9038   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9039                         ? diag::warn_precedence_bitwise_conditional
9040                         : diag::warn_precedence_conditional;
9041 
9042   Self.Diag(OpLoc, DiagID)
9043       << Condition->getSourceRange()
9044       << BinaryOperator::getOpcodeStr(CondOpcode);
9045 
9046   SuggestParentheses(
9047       Self, OpLoc,
9048       Self.PDiag(diag::note_precedence_silence)
9049           << BinaryOperator::getOpcodeStr(CondOpcode),
9050       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9051 
9052   SuggestParentheses(Self, OpLoc,
9053                      Self.PDiag(diag::note_precedence_conditional_first),
9054                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9055 }
9056 
9057 /// Compute the nullability of a conditional expression.
9058 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9059                                               QualType LHSTy, QualType RHSTy,
9060                                               ASTContext &Ctx) {
9061   if (!ResTy->isAnyPointerType())
9062     return ResTy;
9063 
9064   auto GetNullability = [&Ctx](QualType Ty) {
9065     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
9066     if (Kind) {
9067       // For our purposes, treat _Nullable_result as _Nullable.
9068       if (*Kind == NullabilityKind::NullableResult)
9069         return NullabilityKind::Nullable;
9070       return *Kind;
9071     }
9072     return NullabilityKind::Unspecified;
9073   };
9074 
9075   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9076   NullabilityKind MergedKind;
9077 
9078   // Compute nullability of a binary conditional expression.
9079   if (IsBin) {
9080     if (LHSKind == NullabilityKind::NonNull)
9081       MergedKind = NullabilityKind::NonNull;
9082     else
9083       MergedKind = RHSKind;
9084   // Compute nullability of a normal conditional expression.
9085   } else {
9086     if (LHSKind == NullabilityKind::Nullable ||
9087         RHSKind == NullabilityKind::Nullable)
9088       MergedKind = NullabilityKind::Nullable;
9089     else if (LHSKind == NullabilityKind::NonNull)
9090       MergedKind = RHSKind;
9091     else if (RHSKind == NullabilityKind::NonNull)
9092       MergedKind = LHSKind;
9093     else
9094       MergedKind = NullabilityKind::Unspecified;
9095   }
9096 
9097   // Return if ResTy already has the correct nullability.
9098   if (GetNullability(ResTy) == MergedKind)
9099     return ResTy;
9100 
9101   // Strip all nullability from ResTy.
9102   while (ResTy->getNullability(Ctx))
9103     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9104 
9105   // Create a new AttributedType with the new nullability kind.
9106   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
9107   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
9108 }
9109 
9110 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
9111 /// in the case of a the GNU conditional expr extension.
9112 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9113                                     SourceLocation ColonLoc,
9114                                     Expr *CondExpr, Expr *LHSExpr,
9115                                     Expr *RHSExpr) {
9116   if (!Context.isDependenceAllowed()) {
9117     // C cannot handle TypoExpr nodes in the condition because it
9118     // doesn't handle dependent types properly, so make sure any TypoExprs have
9119     // been dealt with before checking the operands.
9120     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9121     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9122     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9123 
9124     if (!CondResult.isUsable())
9125       return ExprError();
9126 
9127     if (LHSExpr) {
9128       if (!LHSResult.isUsable())
9129         return ExprError();
9130     }
9131 
9132     if (!RHSResult.isUsable())
9133       return ExprError();
9134 
9135     CondExpr = CondResult.get();
9136     LHSExpr = LHSResult.get();
9137     RHSExpr = RHSResult.get();
9138   }
9139 
9140   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9141   // was the condition.
9142   OpaqueValueExpr *opaqueValue = nullptr;
9143   Expr *commonExpr = nullptr;
9144   if (!LHSExpr) {
9145     commonExpr = CondExpr;
9146     // Lower out placeholder types first.  This is important so that we don't
9147     // try to capture a placeholder. This happens in few cases in C++; such
9148     // as Objective-C++'s dictionary subscripting syntax.
9149     if (commonExpr->hasPlaceholderType()) {
9150       ExprResult result = CheckPlaceholderExpr(commonExpr);
9151       if (!result.isUsable()) return ExprError();
9152       commonExpr = result.get();
9153     }
9154     // We usually want to apply unary conversions *before* saving, except
9155     // in the special case of a C++ l-value conditional.
9156     if (!(getLangOpts().CPlusPlus
9157           && !commonExpr->isTypeDependent()
9158           && commonExpr->getValueKind() == RHSExpr->getValueKind()
9159           && commonExpr->isGLValue()
9160           && commonExpr->isOrdinaryOrBitFieldObject()
9161           && RHSExpr->isOrdinaryOrBitFieldObject()
9162           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9163       ExprResult commonRes = UsualUnaryConversions(commonExpr);
9164       if (commonRes.isInvalid())
9165         return ExprError();
9166       commonExpr = commonRes.get();
9167     }
9168 
9169     // If the common expression is a class or array prvalue, materialize it
9170     // so that we can safely refer to it multiple times.
9171     if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9172                                     commonExpr->getType()->isArrayType())) {
9173       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9174       if (MatExpr.isInvalid())
9175         return ExprError();
9176       commonExpr = MatExpr.get();
9177     }
9178 
9179     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9180                                                 commonExpr->getType(),
9181                                                 commonExpr->getValueKind(),
9182                                                 commonExpr->getObjectKind(),
9183                                                 commonExpr);
9184     LHSExpr = CondExpr = opaqueValue;
9185   }
9186 
9187   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9188   ExprValueKind VK = VK_PRValue;
9189   ExprObjectKind OK = OK_Ordinary;
9190   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9191   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9192                                              VK, OK, QuestionLoc);
9193   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9194       RHS.isInvalid())
9195     return ExprError();
9196 
9197   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9198                                 RHS.get());
9199 
9200   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9201 
9202   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9203                                          Context);
9204 
9205   if (!commonExpr)
9206     return new (Context)
9207         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9208                             RHS.get(), result, VK, OK);
9209 
9210   return new (Context) BinaryConditionalOperator(
9211       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9212       ColonLoc, result, VK, OK);
9213 }
9214 
9215 // Check if we have a conversion between incompatible cmse function pointer
9216 // types, that is, a conversion between a function pointer with the
9217 // cmse_nonsecure_call attribute and one without.
9218 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9219                                           QualType ToType) {
9220   if (const auto *ToFn =
9221           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9222     if (const auto *FromFn =
9223             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9224       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9225       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9226 
9227       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9228     }
9229   }
9230   return false;
9231 }
9232 
9233 // checkPointerTypesForAssignment - This is a very tricky routine (despite
9234 // being closely modeled after the C99 spec:-). The odd characteristic of this
9235 // routine is it effectively iqnores the qualifiers on the top level pointee.
9236 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9237 // FIXME: add a couple examples in this comment.
9238 static Sema::AssignConvertType
9239 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
9240   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9241   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9242 
9243   // get the "pointed to" type (ignoring qualifiers at the top level)
9244   const Type *lhptee, *rhptee;
9245   Qualifiers lhq, rhq;
9246   std::tie(lhptee, lhq) =
9247       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9248   std::tie(rhptee, rhq) =
9249       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9250 
9251   Sema::AssignConvertType ConvTy = Sema::Compatible;
9252 
9253   // C99 6.5.16.1p1: This following citation is common to constraints
9254   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9255   // qualifiers of the type *pointed to* by the right;
9256 
9257   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9258   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9259       lhq.compatiblyIncludesObjCLifetime(rhq)) {
9260     // Ignore lifetime for further calculation.
9261     lhq.removeObjCLifetime();
9262     rhq.removeObjCLifetime();
9263   }
9264 
9265   if (!lhq.compatiblyIncludes(rhq)) {
9266     // Treat address-space mismatches as fatal.
9267     if (!lhq.isAddressSpaceSupersetOf(rhq))
9268       return Sema::IncompatiblePointerDiscardsQualifiers;
9269 
9270     // It's okay to add or remove GC or lifetime qualifiers when converting to
9271     // and from void*.
9272     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9273                         .compatiblyIncludes(
9274                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9275              && (lhptee->isVoidType() || rhptee->isVoidType()))
9276       ; // keep old
9277 
9278     // Treat lifetime mismatches as fatal.
9279     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9280       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9281 
9282     // For GCC/MS compatibility, other qualifier mismatches are treated
9283     // as still compatible in C.
9284     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9285   }
9286 
9287   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9288   // incomplete type and the other is a pointer to a qualified or unqualified
9289   // version of void...
9290   if (lhptee->isVoidType()) {
9291     if (rhptee->isIncompleteOrObjectType())
9292       return ConvTy;
9293 
9294     // As an extension, we allow cast to/from void* to function pointer.
9295     assert(rhptee->isFunctionType());
9296     return Sema::FunctionVoidPointer;
9297   }
9298 
9299   if (rhptee->isVoidType()) {
9300     if (lhptee->isIncompleteOrObjectType())
9301       return ConvTy;
9302 
9303     // As an extension, we allow cast to/from void* to function pointer.
9304     assert(lhptee->isFunctionType());
9305     return Sema::FunctionVoidPointer;
9306   }
9307 
9308   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9309   // unqualified versions of compatible types, ...
9310   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9311   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9312     // Check if the pointee types are compatible ignoring the sign.
9313     // We explicitly check for char so that we catch "char" vs
9314     // "unsigned char" on systems where "char" is unsigned.
9315     if (lhptee->isCharType())
9316       ltrans = S.Context.UnsignedCharTy;
9317     else if (lhptee->hasSignedIntegerRepresentation())
9318       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9319 
9320     if (rhptee->isCharType())
9321       rtrans = S.Context.UnsignedCharTy;
9322     else if (rhptee->hasSignedIntegerRepresentation())
9323       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9324 
9325     if (ltrans == rtrans) {
9326       // Types are compatible ignoring the sign. Qualifier incompatibility
9327       // takes priority over sign incompatibility because the sign
9328       // warning can be disabled.
9329       if (ConvTy != Sema::Compatible)
9330         return ConvTy;
9331 
9332       return Sema::IncompatiblePointerSign;
9333     }
9334 
9335     // If we are a multi-level pointer, it's possible that our issue is simply
9336     // one of qualification - e.g. char ** -> const char ** is not allowed. If
9337     // the eventual target type is the same and the pointers have the same
9338     // level of indirection, this must be the issue.
9339     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9340       do {
9341         std::tie(lhptee, lhq) =
9342           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9343         std::tie(rhptee, rhq) =
9344           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9345 
9346         // Inconsistent address spaces at this point is invalid, even if the
9347         // address spaces would be compatible.
9348         // FIXME: This doesn't catch address space mismatches for pointers of
9349         // different nesting levels, like:
9350         //   __local int *** a;
9351         //   int ** b = a;
9352         // It's not clear how to actually determine when such pointers are
9353         // invalidly incompatible.
9354         if (lhq.getAddressSpace() != rhq.getAddressSpace())
9355           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9356 
9357       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9358 
9359       if (lhptee == rhptee)
9360         return Sema::IncompatibleNestedPointerQualifiers;
9361     }
9362 
9363     // General pointer incompatibility takes priority over qualifiers.
9364     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9365       return Sema::IncompatibleFunctionPointer;
9366     return Sema::IncompatiblePointer;
9367   }
9368   if (!S.getLangOpts().CPlusPlus &&
9369       S.IsFunctionConversion(ltrans, rtrans, ltrans))
9370     return Sema::IncompatibleFunctionPointer;
9371   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9372     return Sema::IncompatibleFunctionPointer;
9373   return ConvTy;
9374 }
9375 
9376 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9377 /// block pointer types are compatible or whether a block and normal pointer
9378 /// are compatible. It is more restrict than comparing two function pointer
9379 // types.
9380 static Sema::AssignConvertType
9381 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9382                                     QualType RHSType) {
9383   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9384   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9385 
9386   QualType lhptee, rhptee;
9387 
9388   // get the "pointed to" type (ignoring qualifiers at the top level)
9389   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9390   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9391 
9392   // In C++, the types have to match exactly.
9393   if (S.getLangOpts().CPlusPlus)
9394     return Sema::IncompatibleBlockPointer;
9395 
9396   Sema::AssignConvertType ConvTy = Sema::Compatible;
9397 
9398   // For blocks we enforce that qualifiers are identical.
9399   Qualifiers LQuals = lhptee.getLocalQualifiers();
9400   Qualifiers RQuals = rhptee.getLocalQualifiers();
9401   if (S.getLangOpts().OpenCL) {
9402     LQuals.removeAddressSpace();
9403     RQuals.removeAddressSpace();
9404   }
9405   if (LQuals != RQuals)
9406     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9407 
9408   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9409   // assignment.
9410   // The current behavior is similar to C++ lambdas. A block might be
9411   // assigned to a variable iff its return type and parameters are compatible
9412   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9413   // an assignment. Presumably it should behave in way that a function pointer
9414   // assignment does in C, so for each parameter and return type:
9415   //  * CVR and address space of LHS should be a superset of CVR and address
9416   //  space of RHS.
9417   //  * unqualified types should be compatible.
9418   if (S.getLangOpts().OpenCL) {
9419     if (!S.Context.typesAreBlockPointerCompatible(
9420             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9421             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9422       return Sema::IncompatibleBlockPointer;
9423   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9424     return Sema::IncompatibleBlockPointer;
9425 
9426   return ConvTy;
9427 }
9428 
9429 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9430 /// for assignment compatibility.
9431 static Sema::AssignConvertType
9432 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9433                                    QualType RHSType) {
9434   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9435   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9436 
9437   if (LHSType->isObjCBuiltinType()) {
9438     // Class is not compatible with ObjC object pointers.
9439     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9440         !RHSType->isObjCQualifiedClassType())
9441       return Sema::IncompatiblePointer;
9442     return Sema::Compatible;
9443   }
9444   if (RHSType->isObjCBuiltinType()) {
9445     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9446         !LHSType->isObjCQualifiedClassType())
9447       return Sema::IncompatiblePointer;
9448     return Sema::Compatible;
9449   }
9450   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9451   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9452 
9453   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9454       // make an exception for id<P>
9455       !LHSType->isObjCQualifiedIdType())
9456     return Sema::CompatiblePointerDiscardsQualifiers;
9457 
9458   if (S.Context.typesAreCompatible(LHSType, RHSType))
9459     return Sema::Compatible;
9460   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9461     return Sema::IncompatibleObjCQualifiedId;
9462   return Sema::IncompatiblePointer;
9463 }
9464 
9465 Sema::AssignConvertType
9466 Sema::CheckAssignmentConstraints(SourceLocation Loc,
9467                                  QualType LHSType, QualType RHSType) {
9468   // Fake up an opaque expression.  We don't actually care about what
9469   // cast operations are required, so if CheckAssignmentConstraints
9470   // adds casts to this they'll be wasted, but fortunately that doesn't
9471   // usually happen on valid code.
9472   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9473   ExprResult RHSPtr = &RHSExpr;
9474   CastKind K;
9475 
9476   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9477 }
9478 
9479 /// This helper function returns true if QT is a vector type that has element
9480 /// type ElementType.
9481 static bool isVector(QualType QT, QualType ElementType) {
9482   if (const VectorType *VT = QT->getAs<VectorType>())
9483     return VT->getElementType().getCanonicalType() == ElementType;
9484   return false;
9485 }
9486 
9487 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9488 /// has code to accommodate several GCC extensions when type checking
9489 /// pointers. Here are some objectionable examples that GCC considers warnings:
9490 ///
9491 ///  int a, *pint;
9492 ///  short *pshort;
9493 ///  struct foo *pfoo;
9494 ///
9495 ///  pint = pshort; // warning: assignment from incompatible pointer type
9496 ///  a = pint; // warning: assignment makes integer from pointer without a cast
9497 ///  pint = a; // warning: assignment makes pointer from integer without a cast
9498 ///  pint = pfoo; // warning: assignment from incompatible pointer type
9499 ///
9500 /// As a result, the code for dealing with pointers is more complex than the
9501 /// C99 spec dictates.
9502 ///
9503 /// Sets 'Kind' for any result kind except Incompatible.
9504 Sema::AssignConvertType
9505 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9506                                  CastKind &Kind, bool ConvertRHS) {
9507   QualType RHSType = RHS.get()->getType();
9508   QualType OrigLHSType = LHSType;
9509 
9510   // Get canonical types.  We're not formatting these types, just comparing
9511   // them.
9512   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9513   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9514 
9515   // Common case: no conversion required.
9516   if (LHSType == RHSType) {
9517     Kind = CK_NoOp;
9518     return Compatible;
9519   }
9520 
9521   // If the LHS has an __auto_type, there are no additional type constraints
9522   // to be worried about.
9523   if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9524     if (AT->isGNUAutoType()) {
9525       Kind = CK_NoOp;
9526       return Compatible;
9527     }
9528   }
9529 
9530   // If we have an atomic type, try a non-atomic assignment, then just add an
9531   // atomic qualification step.
9532   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9533     Sema::AssignConvertType result =
9534       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9535     if (result != Compatible)
9536       return result;
9537     if (Kind != CK_NoOp && ConvertRHS)
9538       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9539     Kind = CK_NonAtomicToAtomic;
9540     return Compatible;
9541   }
9542 
9543   // If the left-hand side is a reference type, then we are in a
9544   // (rare!) case where we've allowed the use of references in C,
9545   // e.g., as a parameter type in a built-in function. In this case,
9546   // just make sure that the type referenced is compatible with the
9547   // right-hand side type. The caller is responsible for adjusting
9548   // LHSType so that the resulting expression does not have reference
9549   // type.
9550   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9551     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9552       Kind = CK_LValueBitCast;
9553       return Compatible;
9554     }
9555     return Incompatible;
9556   }
9557 
9558   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9559   // to the same ExtVector type.
9560   if (LHSType->isExtVectorType()) {
9561     if (RHSType->isExtVectorType())
9562       return Incompatible;
9563     if (RHSType->isArithmeticType()) {
9564       // CK_VectorSplat does T -> vector T, so first cast to the element type.
9565       if (ConvertRHS)
9566         RHS = prepareVectorSplat(LHSType, RHS.get());
9567       Kind = CK_VectorSplat;
9568       return Compatible;
9569     }
9570   }
9571 
9572   // Conversions to or from vector type.
9573   if (LHSType->isVectorType() || RHSType->isVectorType()) {
9574     if (LHSType->isVectorType() && RHSType->isVectorType()) {
9575       // Allow assignments of an AltiVec vector type to an equivalent GCC
9576       // vector type and vice versa
9577       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9578         Kind = CK_BitCast;
9579         return Compatible;
9580       }
9581 
9582       // If we are allowing lax vector conversions, and LHS and RHS are both
9583       // vectors, the total size only needs to be the same. This is a bitcast;
9584       // no bits are changed but the result type is different.
9585       if (isLaxVectorConversion(RHSType, LHSType)) {
9586         // The default for lax vector conversions with Altivec vectors will
9587         // change, so if we are converting between vector types where
9588         // at least one is an Altivec vector, emit a warning.
9589         if (anyAltivecTypes(RHSType, LHSType) &&
9590             !areSameVectorElemTypes(RHSType, LHSType))
9591           Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9592               << RHSType << LHSType;
9593         Kind = CK_BitCast;
9594         return IncompatibleVectors;
9595       }
9596     }
9597 
9598     // When the RHS comes from another lax conversion (e.g. binops between
9599     // scalars and vectors) the result is canonicalized as a vector. When the
9600     // LHS is also a vector, the lax is allowed by the condition above. Handle
9601     // the case where LHS is a scalar.
9602     if (LHSType->isScalarType()) {
9603       const VectorType *VecType = RHSType->getAs<VectorType>();
9604       if (VecType && VecType->getNumElements() == 1 &&
9605           isLaxVectorConversion(RHSType, LHSType)) {
9606         if (VecType->getVectorKind() == VectorType::AltiVecVector)
9607           Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9608               << RHSType << LHSType;
9609         ExprResult *VecExpr = &RHS;
9610         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9611         Kind = CK_BitCast;
9612         return Compatible;
9613       }
9614     }
9615 
9616     // Allow assignments between fixed-length and sizeless SVE vectors.
9617     if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9618         (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9619       if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9620           Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9621         Kind = CK_BitCast;
9622         return Compatible;
9623       }
9624 
9625     return Incompatible;
9626   }
9627 
9628   // Diagnose attempts to convert between __ibm128, __float128 and long double
9629   // where such conversions currently can't be handled.
9630   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9631     return Incompatible;
9632 
9633   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9634   // discards the imaginary part.
9635   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9636       !LHSType->getAs<ComplexType>())
9637     return Incompatible;
9638 
9639   // Arithmetic conversions.
9640   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9641       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9642     if (ConvertRHS)
9643       Kind = PrepareScalarCast(RHS, LHSType);
9644     return Compatible;
9645   }
9646 
9647   // Conversions to normal pointers.
9648   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9649     // U* -> T*
9650     if (isa<PointerType>(RHSType)) {
9651       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9652       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9653       if (AddrSpaceL != AddrSpaceR)
9654         Kind = CK_AddressSpaceConversion;
9655       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9656         Kind = CK_NoOp;
9657       else
9658         Kind = CK_BitCast;
9659       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9660     }
9661 
9662     // int -> T*
9663     if (RHSType->isIntegerType()) {
9664       Kind = CK_IntegralToPointer; // FIXME: null?
9665       return IntToPointer;
9666     }
9667 
9668     // C pointers are not compatible with ObjC object pointers,
9669     // with two exceptions:
9670     if (isa<ObjCObjectPointerType>(RHSType)) {
9671       //  - conversions to void*
9672       if (LHSPointer->getPointeeType()->isVoidType()) {
9673         Kind = CK_BitCast;
9674         return Compatible;
9675       }
9676 
9677       //  - conversions from 'Class' to the redefinition type
9678       if (RHSType->isObjCClassType() &&
9679           Context.hasSameType(LHSType,
9680                               Context.getObjCClassRedefinitionType())) {
9681         Kind = CK_BitCast;
9682         return Compatible;
9683       }
9684 
9685       Kind = CK_BitCast;
9686       return IncompatiblePointer;
9687     }
9688 
9689     // U^ -> void*
9690     if (RHSType->getAs<BlockPointerType>()) {
9691       if (LHSPointer->getPointeeType()->isVoidType()) {
9692         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9693         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9694                                 ->getPointeeType()
9695                                 .getAddressSpace();
9696         Kind =
9697             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9698         return Compatible;
9699       }
9700     }
9701 
9702     return Incompatible;
9703   }
9704 
9705   // Conversions to block pointers.
9706   if (isa<BlockPointerType>(LHSType)) {
9707     // U^ -> T^
9708     if (RHSType->isBlockPointerType()) {
9709       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9710                               ->getPointeeType()
9711                               .getAddressSpace();
9712       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9713                               ->getPointeeType()
9714                               .getAddressSpace();
9715       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9716       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9717     }
9718 
9719     // int or null -> T^
9720     if (RHSType->isIntegerType()) {
9721       Kind = CK_IntegralToPointer; // FIXME: null
9722       return IntToBlockPointer;
9723     }
9724 
9725     // id -> T^
9726     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9727       Kind = CK_AnyPointerToBlockPointerCast;
9728       return Compatible;
9729     }
9730 
9731     // void* -> T^
9732     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9733       if (RHSPT->getPointeeType()->isVoidType()) {
9734         Kind = CK_AnyPointerToBlockPointerCast;
9735         return Compatible;
9736       }
9737 
9738     return Incompatible;
9739   }
9740 
9741   // Conversions to Objective-C pointers.
9742   if (isa<ObjCObjectPointerType>(LHSType)) {
9743     // A* -> B*
9744     if (RHSType->isObjCObjectPointerType()) {
9745       Kind = CK_BitCast;
9746       Sema::AssignConvertType result =
9747         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9748       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9749           result == Compatible &&
9750           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9751         result = IncompatibleObjCWeakRef;
9752       return result;
9753     }
9754 
9755     // int or null -> A*
9756     if (RHSType->isIntegerType()) {
9757       Kind = CK_IntegralToPointer; // FIXME: null
9758       return IntToPointer;
9759     }
9760 
9761     // In general, C pointers are not compatible with ObjC object pointers,
9762     // with two exceptions:
9763     if (isa<PointerType>(RHSType)) {
9764       Kind = CK_CPointerToObjCPointerCast;
9765 
9766       //  - conversions from 'void*'
9767       if (RHSType->isVoidPointerType()) {
9768         return Compatible;
9769       }
9770 
9771       //  - conversions to 'Class' from its redefinition type
9772       if (LHSType->isObjCClassType() &&
9773           Context.hasSameType(RHSType,
9774                               Context.getObjCClassRedefinitionType())) {
9775         return Compatible;
9776       }
9777 
9778       return IncompatiblePointer;
9779     }
9780 
9781     // Only under strict condition T^ is compatible with an Objective-C pointer.
9782     if (RHSType->isBlockPointerType() &&
9783         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9784       if (ConvertRHS)
9785         maybeExtendBlockObject(RHS);
9786       Kind = CK_BlockPointerToObjCPointerCast;
9787       return Compatible;
9788     }
9789 
9790     return Incompatible;
9791   }
9792 
9793   // Conversions from pointers that are not covered by the above.
9794   if (isa<PointerType>(RHSType)) {
9795     // T* -> _Bool
9796     if (LHSType == Context.BoolTy) {
9797       Kind = CK_PointerToBoolean;
9798       return Compatible;
9799     }
9800 
9801     // T* -> int
9802     if (LHSType->isIntegerType()) {
9803       Kind = CK_PointerToIntegral;
9804       return PointerToInt;
9805     }
9806 
9807     return Incompatible;
9808   }
9809 
9810   // Conversions from Objective-C pointers that are not covered by the above.
9811   if (isa<ObjCObjectPointerType>(RHSType)) {
9812     // T* -> _Bool
9813     if (LHSType == Context.BoolTy) {
9814       Kind = CK_PointerToBoolean;
9815       return Compatible;
9816     }
9817 
9818     // T* -> int
9819     if (LHSType->isIntegerType()) {
9820       Kind = CK_PointerToIntegral;
9821       return PointerToInt;
9822     }
9823 
9824     return Incompatible;
9825   }
9826 
9827   // struct A -> struct B
9828   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9829     if (Context.typesAreCompatible(LHSType, RHSType)) {
9830       Kind = CK_NoOp;
9831       return Compatible;
9832     }
9833   }
9834 
9835   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9836     Kind = CK_IntToOCLSampler;
9837     return Compatible;
9838   }
9839 
9840   return Incompatible;
9841 }
9842 
9843 /// Constructs a transparent union from an expression that is
9844 /// used to initialize the transparent union.
9845 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9846                                       ExprResult &EResult, QualType UnionType,
9847                                       FieldDecl *Field) {
9848   // Build an initializer list that designates the appropriate member
9849   // of the transparent union.
9850   Expr *E = EResult.get();
9851   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9852                                                    E, SourceLocation());
9853   Initializer->setType(UnionType);
9854   Initializer->setInitializedFieldInUnion(Field);
9855 
9856   // Build a compound literal constructing a value of the transparent
9857   // union type from this initializer list.
9858   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9859   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9860                                         VK_PRValue, Initializer, false);
9861 }
9862 
9863 Sema::AssignConvertType
9864 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9865                                                ExprResult &RHS) {
9866   QualType RHSType = RHS.get()->getType();
9867 
9868   // If the ArgType is a Union type, we want to handle a potential
9869   // transparent_union GCC extension.
9870   const RecordType *UT = ArgType->getAsUnionType();
9871   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9872     return Incompatible;
9873 
9874   // The field to initialize within the transparent union.
9875   RecordDecl *UD = UT->getDecl();
9876   FieldDecl *InitField = nullptr;
9877   // It's compatible if the expression matches any of the fields.
9878   for (auto *it : UD->fields()) {
9879     if (it->getType()->isPointerType()) {
9880       // If the transparent union contains a pointer type, we allow:
9881       // 1) void pointer
9882       // 2) null pointer constant
9883       if (RHSType->isPointerType())
9884         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9885           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9886           InitField = it;
9887           break;
9888         }
9889 
9890       if (RHS.get()->isNullPointerConstant(Context,
9891                                            Expr::NPC_ValueDependentIsNull)) {
9892         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9893                                 CK_NullToPointer);
9894         InitField = it;
9895         break;
9896       }
9897     }
9898 
9899     CastKind Kind;
9900     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9901           == Compatible) {
9902       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9903       InitField = it;
9904       break;
9905     }
9906   }
9907 
9908   if (!InitField)
9909     return Incompatible;
9910 
9911   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9912   return Compatible;
9913 }
9914 
9915 Sema::AssignConvertType
9916 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9917                                        bool Diagnose,
9918                                        bool DiagnoseCFAudited,
9919                                        bool ConvertRHS) {
9920   // We need to be able to tell the caller whether we diagnosed a problem, if
9921   // they ask us to issue diagnostics.
9922   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9923 
9924   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9925   // we can't avoid *all* modifications at the moment, so we need some somewhere
9926   // to put the updated value.
9927   ExprResult LocalRHS = CallerRHS;
9928   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9929 
9930   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9931     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9932       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9933           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9934         Diag(RHS.get()->getExprLoc(),
9935              diag::warn_noderef_to_dereferenceable_pointer)
9936             << RHS.get()->getSourceRange();
9937       }
9938     }
9939   }
9940 
9941   if (getLangOpts().CPlusPlus) {
9942     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9943       // C++ 5.17p3: If the left operand is not of class type, the
9944       // expression is implicitly converted (C++ 4) to the
9945       // cv-unqualified type of the left operand.
9946       QualType RHSType = RHS.get()->getType();
9947       if (Diagnose) {
9948         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9949                                         AA_Assigning);
9950       } else {
9951         ImplicitConversionSequence ICS =
9952             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9953                                   /*SuppressUserConversions=*/false,
9954                                   AllowedExplicit::None,
9955                                   /*InOverloadResolution=*/false,
9956                                   /*CStyle=*/false,
9957                                   /*AllowObjCWritebackConversion=*/false);
9958         if (ICS.isFailure())
9959           return Incompatible;
9960         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9961                                         ICS, AA_Assigning);
9962       }
9963       if (RHS.isInvalid())
9964         return Incompatible;
9965       Sema::AssignConvertType result = Compatible;
9966       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9967           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9968         result = IncompatibleObjCWeakRef;
9969       return result;
9970     }
9971 
9972     // FIXME: Currently, we fall through and treat C++ classes like C
9973     // structures.
9974     // FIXME: We also fall through for atomics; not sure what should
9975     // happen there, though.
9976   } else if (RHS.get()->getType() == Context.OverloadTy) {
9977     // As a set of extensions to C, we support overloading on functions. These
9978     // functions need to be resolved here.
9979     DeclAccessPair DAP;
9980     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9981             RHS.get(), LHSType, /*Complain=*/false, DAP))
9982       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9983     else
9984       return Incompatible;
9985   }
9986 
9987   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9988   // a null pointer constant.
9989   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9990        LHSType->isBlockPointerType()) &&
9991       RHS.get()->isNullPointerConstant(Context,
9992                                        Expr::NPC_ValueDependentIsNull)) {
9993     if (Diagnose || ConvertRHS) {
9994       CastKind Kind;
9995       CXXCastPath Path;
9996       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9997                              /*IgnoreBaseAccess=*/false, Diagnose);
9998       if (ConvertRHS)
9999         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10000     }
10001     return Compatible;
10002   }
10003 
10004   // OpenCL queue_t type assignment.
10005   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10006                                  Context, Expr::NPC_ValueDependentIsNull)) {
10007     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10008     return Compatible;
10009   }
10010 
10011   // This check seems unnatural, however it is necessary to ensure the proper
10012   // conversion of functions/arrays. If the conversion were done for all
10013   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10014   // expressions that suppress this implicit conversion (&, sizeof).
10015   //
10016   // Suppress this for references: C++ 8.5.3p5.
10017   if (!LHSType->isReferenceType()) {
10018     // FIXME: We potentially allocate here even if ConvertRHS is false.
10019     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
10020     if (RHS.isInvalid())
10021       return Incompatible;
10022   }
10023   CastKind Kind;
10024   Sema::AssignConvertType result =
10025     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10026 
10027   // C99 6.5.16.1p2: The value of the right operand is converted to the
10028   // type of the assignment expression.
10029   // CheckAssignmentConstraints allows the left-hand side to be a reference,
10030   // so that we can use references in built-in functions even in C.
10031   // The getNonReferenceType() call makes sure that the resulting expression
10032   // does not have reference type.
10033   if (result != Incompatible && RHS.get()->getType() != LHSType) {
10034     QualType Ty = LHSType.getNonLValueExprType(Context);
10035     Expr *E = RHS.get();
10036 
10037     // Check for various Objective-C errors. If we are not reporting
10038     // diagnostics and just checking for errors, e.g., during overload
10039     // resolution, return Incompatible to indicate the failure.
10040     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10041         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
10042                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
10043       if (!Diagnose)
10044         return Incompatible;
10045     }
10046     if (getLangOpts().ObjC &&
10047         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10048                                            E->getType(), E, Diagnose) ||
10049          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10050       if (!Diagnose)
10051         return Incompatible;
10052       // Replace the expression with a corrected version and continue so we
10053       // can find further errors.
10054       RHS = E;
10055       return Compatible;
10056     }
10057 
10058     if (ConvertRHS)
10059       RHS = ImpCastExprToType(E, Ty, Kind);
10060   }
10061 
10062   return result;
10063 }
10064 
10065 namespace {
10066 /// The original operand to an operator, prior to the application of the usual
10067 /// arithmetic conversions and converting the arguments of a builtin operator
10068 /// candidate.
10069 struct OriginalOperand {
10070   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10071     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10072       Op = MTE->getSubExpr();
10073     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10074       Op = BTE->getSubExpr();
10075     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10076       Orig = ICE->getSubExprAsWritten();
10077       Conversion = ICE->getConversionFunction();
10078     }
10079   }
10080 
10081   QualType getType() const { return Orig->getType(); }
10082 
10083   Expr *Orig;
10084   NamedDecl *Conversion;
10085 };
10086 }
10087 
10088 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10089                                ExprResult &RHS) {
10090   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10091 
10092   Diag(Loc, diag::err_typecheck_invalid_operands)
10093     << OrigLHS.getType() << OrigRHS.getType()
10094     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10095 
10096   // If a user-defined conversion was applied to either of the operands prior
10097   // to applying the built-in operator rules, tell the user about it.
10098   if (OrigLHS.Conversion) {
10099     Diag(OrigLHS.Conversion->getLocation(),
10100          diag::note_typecheck_invalid_operands_converted)
10101       << 0 << LHS.get()->getType();
10102   }
10103   if (OrigRHS.Conversion) {
10104     Diag(OrigRHS.Conversion->getLocation(),
10105          diag::note_typecheck_invalid_operands_converted)
10106       << 1 << RHS.get()->getType();
10107   }
10108 
10109   return QualType();
10110 }
10111 
10112 // Diagnose cases where a scalar was implicitly converted to a vector and
10113 // diagnose the underlying types. Otherwise, diagnose the error
10114 // as invalid vector logical operands for non-C++ cases.
10115 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10116                                             ExprResult &RHS) {
10117   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10118   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10119 
10120   bool LHSNatVec = LHSType->isVectorType();
10121   bool RHSNatVec = RHSType->isVectorType();
10122 
10123   if (!(LHSNatVec && RHSNatVec)) {
10124     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10125     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10126     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10127         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10128         << Vector->getSourceRange();
10129     return QualType();
10130   }
10131 
10132   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10133       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10134       << RHS.get()->getSourceRange();
10135 
10136   return QualType();
10137 }
10138 
10139 /// Try to convert a value of non-vector type to a vector type by converting
10140 /// the type to the element type of the vector and then performing a splat.
10141 /// If the language is OpenCL, we only use conversions that promote scalar
10142 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10143 /// for float->int.
10144 ///
10145 /// OpenCL V2.0 6.2.6.p2:
10146 /// An error shall occur if any scalar operand type has greater rank
10147 /// than the type of the vector element.
10148 ///
10149 /// \param scalar - if non-null, actually perform the conversions
10150 /// \return true if the operation fails (but without diagnosing the failure)
10151 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10152                                      QualType scalarTy,
10153                                      QualType vectorEltTy,
10154                                      QualType vectorTy,
10155                                      unsigned &DiagID) {
10156   // The conversion to apply to the scalar before splatting it,
10157   // if necessary.
10158   CastKind scalarCast = CK_NoOp;
10159 
10160   if (vectorEltTy->isIntegralType(S.Context)) {
10161     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10162         (scalarTy->isIntegerType() &&
10163          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10164       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10165       return true;
10166     }
10167     if (!scalarTy->isIntegralType(S.Context))
10168       return true;
10169     scalarCast = CK_IntegralCast;
10170   } else if (vectorEltTy->isRealFloatingType()) {
10171     if (scalarTy->isRealFloatingType()) {
10172       if (S.getLangOpts().OpenCL &&
10173           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10174         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10175         return true;
10176       }
10177       scalarCast = CK_FloatingCast;
10178     }
10179     else if (scalarTy->isIntegralType(S.Context))
10180       scalarCast = CK_IntegralToFloating;
10181     else
10182       return true;
10183   } else {
10184     return true;
10185   }
10186 
10187   // Adjust scalar if desired.
10188   if (scalar) {
10189     if (scalarCast != CK_NoOp)
10190       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10191     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10192   }
10193   return false;
10194 }
10195 
10196 /// Convert vector E to a vector with the same number of elements but different
10197 /// element type.
10198 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10199   const auto *VecTy = E->getType()->getAs<VectorType>();
10200   assert(VecTy && "Expression E must be a vector");
10201   QualType NewVecTy =
10202       VecTy->isExtVectorType()
10203           ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10204           : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10205                                     VecTy->getVectorKind());
10206 
10207   // Look through the implicit cast. Return the subexpression if its type is
10208   // NewVecTy.
10209   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10210     if (ICE->getSubExpr()->getType() == NewVecTy)
10211       return ICE->getSubExpr();
10212 
10213   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10214   return S.ImpCastExprToType(E, NewVecTy, Cast);
10215 }
10216 
10217 /// Test if a (constant) integer Int can be casted to another integer type
10218 /// IntTy without losing precision.
10219 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10220                                       QualType OtherIntTy) {
10221   QualType IntTy = Int->get()->getType().getUnqualifiedType();
10222 
10223   // Reject cases where the value of the Int is unknown as that would
10224   // possibly cause truncation, but accept cases where the scalar can be
10225   // demoted without loss of precision.
10226   Expr::EvalResult EVResult;
10227   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10228   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10229   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10230   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10231 
10232   if (CstInt) {
10233     // If the scalar is constant and is of a higher order and has more active
10234     // bits that the vector element type, reject it.
10235     llvm::APSInt Result = EVResult.Val.getInt();
10236     unsigned NumBits = IntSigned
10237                            ? (Result.isNegative() ? Result.getMinSignedBits()
10238                                                   : Result.getActiveBits())
10239                            : Result.getActiveBits();
10240     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10241       return true;
10242 
10243     // If the signedness of the scalar type and the vector element type
10244     // differs and the number of bits is greater than that of the vector
10245     // element reject it.
10246     return (IntSigned != OtherIntSigned &&
10247             NumBits > S.Context.getIntWidth(OtherIntTy));
10248   }
10249 
10250   // Reject cases where the value of the scalar is not constant and it's
10251   // order is greater than that of the vector element type.
10252   return (Order < 0);
10253 }
10254 
10255 /// Test if a (constant) integer Int can be casted to floating point type
10256 /// FloatTy without losing precision.
10257 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10258                                      QualType FloatTy) {
10259   QualType IntTy = Int->get()->getType().getUnqualifiedType();
10260 
10261   // Determine if the integer constant can be expressed as a floating point
10262   // number of the appropriate type.
10263   Expr::EvalResult EVResult;
10264   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10265 
10266   uint64_t Bits = 0;
10267   if (CstInt) {
10268     // Reject constants that would be truncated if they were converted to
10269     // the floating point type. Test by simple to/from conversion.
10270     // FIXME: Ideally the conversion to an APFloat and from an APFloat
10271     //        could be avoided if there was a convertFromAPInt method
10272     //        which could signal back if implicit truncation occurred.
10273     llvm::APSInt Result = EVResult.Val.getInt();
10274     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10275     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10276                            llvm::APFloat::rmTowardZero);
10277     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10278                              !IntTy->hasSignedIntegerRepresentation());
10279     bool Ignored = false;
10280     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10281                            &Ignored);
10282     if (Result != ConvertBack)
10283       return true;
10284   } else {
10285     // Reject types that cannot be fully encoded into the mantissa of
10286     // the float.
10287     Bits = S.Context.getTypeSize(IntTy);
10288     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10289         S.Context.getFloatTypeSemantics(FloatTy));
10290     if (Bits > FloatPrec)
10291       return true;
10292   }
10293 
10294   return false;
10295 }
10296 
10297 /// Attempt to convert and splat Scalar into a vector whose types matches
10298 /// Vector following GCC conversion rules. The rule is that implicit
10299 /// conversion can occur when Scalar can be casted to match Vector's element
10300 /// type without causing truncation of Scalar.
10301 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10302                                         ExprResult *Vector) {
10303   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10304   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10305   QualType VectorEltTy;
10306 
10307   if (const auto *VT = VectorTy->getAs<VectorType>()) {
10308     assert(!isa<ExtVectorType>(VT) &&
10309            "ExtVectorTypes should not be handled here!");
10310     VectorEltTy = VT->getElementType();
10311   } else if (VectorTy->isVLSTBuiltinType()) {
10312     VectorEltTy =
10313         VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10314   } else {
10315     llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10316   }
10317 
10318   // Reject cases where the vector element type or the scalar element type are
10319   // not integral or floating point types.
10320   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10321     return true;
10322 
10323   // The conversion to apply to the scalar before splatting it,
10324   // if necessary.
10325   CastKind ScalarCast = CK_NoOp;
10326 
10327   // Accept cases where the vector elements are integers and the scalar is
10328   // an integer.
10329   // FIXME: Notionally if the scalar was a floating point value with a precise
10330   //        integral representation, we could cast it to an appropriate integer
10331   //        type and then perform the rest of the checks here. GCC will perform
10332   //        this conversion in some cases as determined by the input language.
10333   //        We should accept it on a language independent basis.
10334   if (VectorEltTy->isIntegralType(S.Context) &&
10335       ScalarTy->isIntegralType(S.Context) &&
10336       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10337 
10338     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10339       return true;
10340 
10341     ScalarCast = CK_IntegralCast;
10342   } else if (VectorEltTy->isIntegralType(S.Context) &&
10343              ScalarTy->isRealFloatingType()) {
10344     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10345       ScalarCast = CK_FloatingToIntegral;
10346     else
10347       return true;
10348   } else if (VectorEltTy->isRealFloatingType()) {
10349     if (ScalarTy->isRealFloatingType()) {
10350 
10351       // Reject cases where the scalar type is not a constant and has a higher
10352       // Order than the vector element type.
10353       llvm::APFloat Result(0.0);
10354 
10355       // Determine whether this is a constant scalar. In the event that the
10356       // value is dependent (and thus cannot be evaluated by the constant
10357       // evaluator), skip the evaluation. This will then diagnose once the
10358       // expression is instantiated.
10359       bool CstScalar = Scalar->get()->isValueDependent() ||
10360                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
10361       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10362       if (!CstScalar && Order < 0)
10363         return true;
10364 
10365       // If the scalar cannot be safely casted to the vector element type,
10366       // reject it.
10367       if (CstScalar) {
10368         bool Truncated = false;
10369         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10370                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
10371         if (Truncated)
10372           return true;
10373       }
10374 
10375       ScalarCast = CK_FloatingCast;
10376     } else if (ScalarTy->isIntegralType(S.Context)) {
10377       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10378         return true;
10379 
10380       ScalarCast = CK_IntegralToFloating;
10381     } else
10382       return true;
10383   } else if (ScalarTy->isEnumeralType())
10384     return true;
10385 
10386   // Adjust scalar if desired.
10387   if (Scalar) {
10388     if (ScalarCast != CK_NoOp)
10389       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10390     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10391   }
10392   return false;
10393 }
10394 
10395 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10396                                    SourceLocation Loc, bool IsCompAssign,
10397                                    bool AllowBothBool,
10398                                    bool AllowBoolConversions,
10399                                    bool AllowBoolOperation,
10400                                    bool ReportInvalid) {
10401   if (!IsCompAssign) {
10402     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10403     if (LHS.isInvalid())
10404       return QualType();
10405   }
10406   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10407   if (RHS.isInvalid())
10408     return QualType();
10409 
10410   // For conversion purposes, we ignore any qualifiers.
10411   // For example, "const float" and "float" are equivalent.
10412   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10413   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10414 
10415   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10416   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10417   assert(LHSVecType || RHSVecType);
10418 
10419   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10420       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10421     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10422 
10423   // AltiVec-style "vector bool op vector bool" combinations are allowed
10424   // for some operators but not others.
10425   if (!AllowBothBool &&
10426       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10427       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10428     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10429 
10430   // This operation may not be performed on boolean vectors.
10431   if (!AllowBoolOperation &&
10432       (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10433     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10434 
10435   // If the vector types are identical, return.
10436   if (Context.hasSameType(LHSType, RHSType))
10437     return LHSType;
10438 
10439   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10440   if (LHSVecType && RHSVecType &&
10441       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10442     if (isa<ExtVectorType>(LHSVecType)) {
10443       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10444       return LHSType;
10445     }
10446 
10447     if (!IsCompAssign)
10448       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10449     return RHSType;
10450   }
10451 
10452   // AllowBoolConversions says that bool and non-bool AltiVec vectors
10453   // can be mixed, with the result being the non-bool type.  The non-bool
10454   // operand must have integer element type.
10455   if (AllowBoolConversions && LHSVecType && RHSVecType &&
10456       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10457       (Context.getTypeSize(LHSVecType->getElementType()) ==
10458        Context.getTypeSize(RHSVecType->getElementType()))) {
10459     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10460         LHSVecType->getElementType()->isIntegerType() &&
10461         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10462       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10463       return LHSType;
10464     }
10465     if (!IsCompAssign &&
10466         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10467         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10468         RHSVecType->getElementType()->isIntegerType()) {
10469       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10470       return RHSType;
10471     }
10472   }
10473 
10474   // Expressions containing fixed-length and sizeless SVE vectors are invalid
10475   // since the ambiguity can affect the ABI.
10476   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10477     const VectorType *VecType = SecondType->getAs<VectorType>();
10478     return FirstType->isSizelessBuiltinType() && VecType &&
10479            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10480             VecType->getVectorKind() ==
10481                 VectorType::SveFixedLengthPredicateVector);
10482   };
10483 
10484   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10485     Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10486     return QualType();
10487   }
10488 
10489   // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10490   // since the ambiguity can affect the ABI.
10491   auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10492     const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10493     const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10494 
10495     if (FirstVecType && SecondVecType)
10496       return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10497              (SecondVecType->getVectorKind() ==
10498                   VectorType::SveFixedLengthDataVector ||
10499               SecondVecType->getVectorKind() ==
10500                   VectorType::SveFixedLengthPredicateVector);
10501 
10502     return FirstType->isSizelessBuiltinType() && SecondVecType &&
10503            SecondVecType->getVectorKind() == VectorType::GenericVector;
10504   };
10505 
10506   if (IsSveGnuConversion(LHSType, RHSType) ||
10507       IsSveGnuConversion(RHSType, LHSType)) {
10508     Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10509     return QualType();
10510   }
10511 
10512   // If there's a vector type and a scalar, try to convert the scalar to
10513   // the vector element type and splat.
10514   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10515   if (!RHSVecType) {
10516     if (isa<ExtVectorType>(LHSVecType)) {
10517       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10518                                     LHSVecType->getElementType(), LHSType,
10519                                     DiagID))
10520         return LHSType;
10521     } else {
10522       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10523         return LHSType;
10524     }
10525   }
10526   if (!LHSVecType) {
10527     if (isa<ExtVectorType>(RHSVecType)) {
10528       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10529                                     LHSType, RHSVecType->getElementType(),
10530                                     RHSType, DiagID))
10531         return RHSType;
10532     } else {
10533       if (LHS.get()->isLValue() ||
10534           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10535         return RHSType;
10536     }
10537   }
10538 
10539   // FIXME: The code below also handles conversion between vectors and
10540   // non-scalars, we should break this down into fine grained specific checks
10541   // and emit proper diagnostics.
10542   QualType VecType = LHSVecType ? LHSType : RHSType;
10543   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10544   QualType OtherType = LHSVecType ? RHSType : LHSType;
10545   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10546   if (isLaxVectorConversion(OtherType, VecType)) {
10547     if (anyAltivecTypes(RHSType, LHSType) &&
10548         !areSameVectorElemTypes(RHSType, LHSType))
10549       Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10550     // If we're allowing lax vector conversions, only the total (data) size
10551     // needs to be the same. For non compound assignment, if one of the types is
10552     // scalar, the result is always the vector type.
10553     if (!IsCompAssign) {
10554       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10555       return VecType;
10556     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10557     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10558     // type. Note that this is already done by non-compound assignments in
10559     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10560     // <1 x T> -> T. The result is also a vector type.
10561     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10562                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10563       ExprResult *RHSExpr = &RHS;
10564       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10565       return VecType;
10566     }
10567   }
10568 
10569   // Okay, the expression is invalid.
10570 
10571   // If there's a non-vector, non-real operand, diagnose that.
10572   if ((!RHSVecType && !RHSType->isRealType()) ||
10573       (!LHSVecType && !LHSType->isRealType())) {
10574     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10575       << LHSType << RHSType
10576       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10577     return QualType();
10578   }
10579 
10580   // OpenCL V1.1 6.2.6.p1:
10581   // If the operands are of more than one vector type, then an error shall
10582   // occur. Implicit conversions between vector types are not permitted, per
10583   // section 6.2.1.
10584   if (getLangOpts().OpenCL &&
10585       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10586       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10587     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10588                                                            << RHSType;
10589     return QualType();
10590   }
10591 
10592 
10593   // If there is a vector type that is not a ExtVector and a scalar, we reach
10594   // this point if scalar could not be converted to the vector's element type
10595   // without truncation.
10596   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10597       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10598     QualType Scalar = LHSVecType ? RHSType : LHSType;
10599     QualType Vector = LHSVecType ? LHSType : RHSType;
10600     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10601     Diag(Loc,
10602          diag::err_typecheck_vector_not_convertable_implict_truncation)
10603         << ScalarOrVector << Scalar << Vector;
10604 
10605     return QualType();
10606   }
10607 
10608   // Otherwise, use the generic diagnostic.
10609   Diag(Loc, DiagID)
10610     << LHSType << RHSType
10611     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10612   return QualType();
10613 }
10614 
10615 QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10616                                            SourceLocation Loc,
10617                                            bool IsCompAssign,
10618                                            ArithConvKind OperationKind) {
10619   if (!IsCompAssign) {
10620     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10621     if (LHS.isInvalid())
10622       return QualType();
10623   }
10624   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10625   if (RHS.isInvalid())
10626     return QualType();
10627 
10628   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10629   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10630 
10631   const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10632   const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10633 
10634   unsigned DiagID = diag::err_typecheck_invalid_operands;
10635   if ((OperationKind == ACK_Arithmetic) &&
10636       ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10637        (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10638     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10639                       << RHS.get()->getSourceRange();
10640     return QualType();
10641   }
10642 
10643   if (Context.hasSameType(LHSType, RHSType))
10644     return LHSType;
10645 
10646   if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) {
10647     if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10648       return LHSType;
10649   }
10650   if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) {
10651     if (LHS.get()->isLValue() ||
10652         !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10653       return RHSType;
10654   }
10655 
10656   if ((!LHSType->isVLSTBuiltinType() && !LHSType->isRealType()) ||
10657       (!RHSType->isVLSTBuiltinType() && !RHSType->isRealType())) {
10658     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10659         << LHSType << RHSType << LHS.get()->getSourceRange()
10660         << RHS.get()->getSourceRange();
10661     return QualType();
10662   }
10663 
10664   if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
10665       Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10666           Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10667     Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10668         << LHSType << RHSType << LHS.get()->getSourceRange()
10669         << RHS.get()->getSourceRange();
10670     return QualType();
10671   }
10672 
10673   if (LHSType->isVLSTBuiltinType() || RHSType->isVLSTBuiltinType()) {
10674     QualType Scalar = LHSType->isVLSTBuiltinType() ? RHSType : LHSType;
10675     QualType Vector = LHSType->isVLSTBuiltinType() ? LHSType : RHSType;
10676     bool ScalarOrVector =
10677         LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType();
10678 
10679     Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10680         << ScalarOrVector << Scalar << Vector;
10681 
10682     return QualType();
10683   }
10684 
10685   Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10686                     << RHS.get()->getSourceRange();
10687   return QualType();
10688 }
10689 
10690 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10691 // expression.  These are mainly cases where the null pointer is used as an
10692 // integer instead of a pointer.
10693 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10694                                 SourceLocation Loc, bool IsCompare) {
10695   // The canonical way to check for a GNU null is with isNullPointerConstant,
10696   // but we use a bit of a hack here for speed; this is a relatively
10697   // hot path, and isNullPointerConstant is slow.
10698   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10699   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10700 
10701   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10702 
10703   // Avoid analyzing cases where the result will either be invalid (and
10704   // diagnosed as such) or entirely valid and not something to warn about.
10705   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10706       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10707     return;
10708 
10709   // Comparison operations would not make sense with a null pointer no matter
10710   // what the other expression is.
10711   if (!IsCompare) {
10712     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10713         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10714         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10715     return;
10716   }
10717 
10718   // The rest of the operations only make sense with a null pointer
10719   // if the other expression is a pointer.
10720   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10721       NonNullType->canDecayToPointerType())
10722     return;
10723 
10724   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10725       << LHSNull /* LHS is NULL */ << NonNullType
10726       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10727 }
10728 
10729 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10730                                           SourceLocation Loc) {
10731   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10732   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10733   if (!LUE || !RUE)
10734     return;
10735   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10736       RUE->getKind() != UETT_SizeOf)
10737     return;
10738 
10739   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10740   QualType LHSTy = LHSArg->getType();
10741   QualType RHSTy;
10742 
10743   if (RUE->isArgumentType())
10744     RHSTy = RUE->getArgumentType().getNonReferenceType();
10745   else
10746     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10747 
10748   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10749     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10750       return;
10751 
10752     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10753     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10754       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10755         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10756             << LHSArgDecl;
10757     }
10758   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10759     QualType ArrayElemTy = ArrayTy->getElementType();
10760     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10761         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10762         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10763         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10764       return;
10765     S.Diag(Loc, diag::warn_division_sizeof_array)
10766         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10767     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10768       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10769         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10770             << LHSArgDecl;
10771     }
10772 
10773     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10774   }
10775 }
10776 
10777 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10778                                                ExprResult &RHS,
10779                                                SourceLocation Loc, bool IsDiv) {
10780   // Check for division/remainder by zero.
10781   Expr::EvalResult RHSValue;
10782   if (!RHS.get()->isValueDependent() &&
10783       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10784       RHSValue.Val.getInt() == 0)
10785     S.DiagRuntimeBehavior(Loc, RHS.get(),
10786                           S.PDiag(diag::warn_remainder_division_by_zero)
10787                             << IsDiv << RHS.get()->getSourceRange());
10788 }
10789 
10790 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10791                                            SourceLocation Loc,
10792                                            bool IsCompAssign, bool IsDiv) {
10793   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10794 
10795   QualType LHSTy = LHS.get()->getType();
10796   QualType RHSTy = RHS.get()->getType();
10797   if (LHSTy->isVectorType() || RHSTy->isVectorType())
10798     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10799                                /*AllowBothBool*/ getLangOpts().AltiVec,
10800                                /*AllowBoolConversions*/ false,
10801                                /*AllowBooleanOperation*/ false,
10802                                /*ReportInvalid*/ true);
10803   if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType())
10804     return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10805                                        ACK_Arithmetic);
10806   if (!IsDiv &&
10807       (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10808     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10809   // For division, only matrix-by-scalar is supported. Other combinations with
10810   // matrix types are invalid.
10811   if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10812     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10813 
10814   QualType compType = UsualArithmeticConversions(
10815       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10816   if (LHS.isInvalid() || RHS.isInvalid())
10817     return QualType();
10818 
10819 
10820   if (compType.isNull() || !compType->isArithmeticType())
10821     return InvalidOperands(Loc, LHS, RHS);
10822   if (IsDiv) {
10823     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10824     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10825   }
10826   return compType;
10827 }
10828 
10829 QualType Sema::CheckRemainderOperands(
10830   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10831   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10832 
10833   if (LHS.get()->getType()->isVectorType() ||
10834       RHS.get()->getType()->isVectorType()) {
10835     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10836         RHS.get()->getType()->hasIntegerRepresentation())
10837       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10838                                  /*AllowBothBool*/ getLangOpts().AltiVec,
10839                                  /*AllowBoolConversions*/ false,
10840                                  /*AllowBooleanOperation*/ false,
10841                                  /*ReportInvalid*/ true);
10842     return InvalidOperands(Loc, LHS, RHS);
10843   }
10844 
10845   if (LHS.get()->getType()->isVLSTBuiltinType() ||
10846       RHS.get()->getType()->isVLSTBuiltinType()) {
10847     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10848         RHS.get()->getType()->hasIntegerRepresentation())
10849       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10850                                          ACK_Arithmetic);
10851 
10852     return InvalidOperands(Loc, LHS, RHS);
10853   }
10854 
10855   QualType compType = UsualArithmeticConversions(
10856       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10857   if (LHS.isInvalid() || RHS.isInvalid())
10858     return QualType();
10859 
10860   if (compType.isNull() || !compType->isIntegerType())
10861     return InvalidOperands(Loc, LHS, RHS);
10862   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10863   return compType;
10864 }
10865 
10866 /// Diagnose invalid arithmetic on two void pointers.
10867 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10868                                                 Expr *LHSExpr, Expr *RHSExpr) {
10869   S.Diag(Loc, S.getLangOpts().CPlusPlus
10870                 ? diag::err_typecheck_pointer_arith_void_type
10871                 : diag::ext_gnu_void_ptr)
10872     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10873                             << RHSExpr->getSourceRange();
10874 }
10875 
10876 /// Diagnose invalid arithmetic on a void pointer.
10877 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10878                                             Expr *Pointer) {
10879   S.Diag(Loc, S.getLangOpts().CPlusPlus
10880                 ? diag::err_typecheck_pointer_arith_void_type
10881                 : diag::ext_gnu_void_ptr)
10882     << 0 /* one pointer */ << Pointer->getSourceRange();
10883 }
10884 
10885 /// Diagnose invalid arithmetic on a null pointer.
10886 ///
10887 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10888 /// idiom, which we recognize as a GNU extension.
10889 ///
10890 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10891                                             Expr *Pointer, bool IsGNUIdiom) {
10892   if (IsGNUIdiom)
10893     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10894       << Pointer->getSourceRange();
10895   else
10896     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10897       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10898 }
10899 
10900 /// Diagnose invalid subraction on a null pointer.
10901 ///
10902 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10903                                              Expr *Pointer, bool BothNull) {
10904   // Null - null is valid in C++ [expr.add]p7
10905   if (BothNull && S.getLangOpts().CPlusPlus)
10906     return;
10907 
10908   // Is this s a macro from a system header?
10909   if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10910     return;
10911 
10912   S.DiagRuntimeBehavior(Loc, Pointer,
10913                         S.PDiag(diag::warn_pointer_sub_null_ptr)
10914                             << S.getLangOpts().CPlusPlus
10915                             << Pointer->getSourceRange());
10916 }
10917 
10918 /// Diagnose invalid arithmetic on two function pointers.
10919 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10920                                                     Expr *LHS, Expr *RHS) {
10921   assert(LHS->getType()->isAnyPointerType());
10922   assert(RHS->getType()->isAnyPointerType());
10923   S.Diag(Loc, S.getLangOpts().CPlusPlus
10924                 ? diag::err_typecheck_pointer_arith_function_type
10925                 : diag::ext_gnu_ptr_func_arith)
10926     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10927     // We only show the second type if it differs from the first.
10928     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10929                                                    RHS->getType())
10930     << RHS->getType()->getPointeeType()
10931     << LHS->getSourceRange() << RHS->getSourceRange();
10932 }
10933 
10934 /// Diagnose invalid arithmetic on a function pointer.
10935 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10936                                                 Expr *Pointer) {
10937   assert(Pointer->getType()->isAnyPointerType());
10938   S.Diag(Loc, S.getLangOpts().CPlusPlus
10939                 ? diag::err_typecheck_pointer_arith_function_type
10940                 : diag::ext_gnu_ptr_func_arith)
10941     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10942     << 0 /* one pointer, so only one type */
10943     << Pointer->getSourceRange();
10944 }
10945 
10946 /// Emit error if Operand is incomplete pointer type
10947 ///
10948 /// \returns True if pointer has incomplete type
10949 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10950                                                  Expr *Operand) {
10951   QualType ResType = Operand->getType();
10952   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10953     ResType = ResAtomicType->getValueType();
10954 
10955   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10956   QualType PointeeTy = ResType->getPointeeType();
10957   return S.RequireCompleteSizedType(
10958       Loc, PointeeTy,
10959       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10960       Operand->getSourceRange());
10961 }
10962 
10963 /// Check the validity of an arithmetic pointer operand.
10964 ///
10965 /// If the operand has pointer type, this code will check for pointer types
10966 /// which are invalid in arithmetic operations. These will be diagnosed
10967 /// appropriately, including whether or not the use is supported as an
10968 /// extension.
10969 ///
10970 /// \returns True when the operand is valid to use (even if as an extension).
10971 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10972                                             Expr *Operand) {
10973   QualType ResType = Operand->getType();
10974   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10975     ResType = ResAtomicType->getValueType();
10976 
10977   if (!ResType->isAnyPointerType()) return true;
10978 
10979   QualType PointeeTy = ResType->getPointeeType();
10980   if (PointeeTy->isVoidType()) {
10981     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10982     return !S.getLangOpts().CPlusPlus;
10983   }
10984   if (PointeeTy->isFunctionType()) {
10985     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10986     return !S.getLangOpts().CPlusPlus;
10987   }
10988 
10989   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10990 
10991   return true;
10992 }
10993 
10994 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10995 /// operands.
10996 ///
10997 /// This routine will diagnose any invalid arithmetic on pointer operands much
10998 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10999 /// for emitting a single diagnostic even for operations where both LHS and RHS
11000 /// are (potentially problematic) pointers.
11001 ///
11002 /// \returns True when the operand is valid to use (even if as an extension).
11003 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11004                                                 Expr *LHSExpr, Expr *RHSExpr) {
11005   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11006   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11007   if (!isLHSPointer && !isRHSPointer) return true;
11008 
11009   QualType LHSPointeeTy, RHSPointeeTy;
11010   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11011   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11012 
11013   // if both are pointers check if operation is valid wrt address spaces
11014   if (isLHSPointer && isRHSPointer) {
11015     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
11016       S.Diag(Loc,
11017              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11018           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11019           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11020       return false;
11021     }
11022   }
11023 
11024   // Check for arithmetic on pointers to incomplete types.
11025   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11026   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11027   if (isLHSVoidPtr || isRHSVoidPtr) {
11028     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11029     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11030     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11031 
11032     return !S.getLangOpts().CPlusPlus;
11033   }
11034 
11035   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11036   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11037   if (isLHSFuncPtr || isRHSFuncPtr) {
11038     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11039     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11040                                                                 RHSExpr);
11041     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11042 
11043     return !S.getLangOpts().CPlusPlus;
11044   }
11045 
11046   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11047     return false;
11048   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11049     return false;
11050 
11051   return true;
11052 }
11053 
11054 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11055 /// literal.
11056 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11057                                   Expr *LHSExpr, Expr *RHSExpr) {
11058   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11059   Expr* IndexExpr = RHSExpr;
11060   if (!StrExpr) {
11061     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11062     IndexExpr = LHSExpr;
11063   }
11064 
11065   bool IsStringPlusInt = StrExpr &&
11066       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11067   if (!IsStringPlusInt || IndexExpr->isValueDependent())
11068     return;
11069 
11070   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11071   Self.Diag(OpLoc, diag::warn_string_plus_int)
11072       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11073 
11074   // Only print a fixit for "str" + int, not for int + "str".
11075   if (IndexExpr == RHSExpr) {
11076     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11077     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11078         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11079         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11080         << FixItHint::CreateInsertion(EndLoc, "]");
11081   } else
11082     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11083 }
11084 
11085 /// Emit a warning when adding a char literal to a string.
11086 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11087                                    Expr *LHSExpr, Expr *RHSExpr) {
11088   const Expr *StringRefExpr = LHSExpr;
11089   const CharacterLiteral *CharExpr =
11090       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11091 
11092   if (!CharExpr) {
11093     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11094     StringRefExpr = RHSExpr;
11095   }
11096 
11097   if (!CharExpr || !StringRefExpr)
11098     return;
11099 
11100   const QualType StringType = StringRefExpr->getType();
11101 
11102   // Return if not a PointerType.
11103   if (!StringType->isAnyPointerType())
11104     return;
11105 
11106   // Return if not a CharacterType.
11107   if (!StringType->getPointeeType()->isAnyCharacterType())
11108     return;
11109 
11110   ASTContext &Ctx = Self.getASTContext();
11111   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11112 
11113   const QualType CharType = CharExpr->getType();
11114   if (!CharType->isAnyCharacterType() &&
11115       CharType->isIntegerType() &&
11116       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11117     Self.Diag(OpLoc, diag::warn_string_plus_char)
11118         << DiagRange << Ctx.CharTy;
11119   } else {
11120     Self.Diag(OpLoc, diag::warn_string_plus_char)
11121         << DiagRange << CharExpr->getType();
11122   }
11123 
11124   // Only print a fixit for str + char, not for char + str.
11125   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11126     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11127     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11128         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11129         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11130         << FixItHint::CreateInsertion(EndLoc, "]");
11131   } else {
11132     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11133   }
11134 }
11135 
11136 /// Emit error when two pointers are incompatible.
11137 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11138                                            Expr *LHSExpr, Expr *RHSExpr) {
11139   assert(LHSExpr->getType()->isAnyPointerType());
11140   assert(RHSExpr->getType()->isAnyPointerType());
11141   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11142     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11143     << RHSExpr->getSourceRange();
11144 }
11145 
11146 // C99 6.5.6
11147 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11148                                      SourceLocation Loc, BinaryOperatorKind Opc,
11149                                      QualType* CompLHSTy) {
11150   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11151 
11152   if (LHS.get()->getType()->isVectorType() ||
11153       RHS.get()->getType()->isVectorType()) {
11154     QualType compType =
11155         CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11156                             /*AllowBothBool*/ getLangOpts().AltiVec,
11157                             /*AllowBoolConversions*/ getLangOpts().ZVector,
11158                             /*AllowBooleanOperation*/ false,
11159                             /*ReportInvalid*/ true);
11160     if (CompLHSTy) *CompLHSTy = compType;
11161     return compType;
11162   }
11163 
11164   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11165       RHS.get()->getType()->isVLSTBuiltinType()) {
11166     QualType compType =
11167         CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11168     if (CompLHSTy)
11169       *CompLHSTy = compType;
11170     return compType;
11171   }
11172 
11173   if (LHS.get()->getType()->isConstantMatrixType() ||
11174       RHS.get()->getType()->isConstantMatrixType()) {
11175     QualType compType =
11176         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11177     if (CompLHSTy)
11178       *CompLHSTy = compType;
11179     return compType;
11180   }
11181 
11182   QualType compType = UsualArithmeticConversions(
11183       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11184   if (LHS.isInvalid() || RHS.isInvalid())
11185     return QualType();
11186 
11187   // Diagnose "string literal" '+' int and string '+' "char literal".
11188   if (Opc == BO_Add) {
11189     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11190     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11191   }
11192 
11193   // handle the common case first (both operands are arithmetic).
11194   if (!compType.isNull() && compType->isArithmeticType()) {
11195     if (CompLHSTy) *CompLHSTy = compType;
11196     return compType;
11197   }
11198 
11199   // Type-checking.  Ultimately the pointer's going to be in PExp;
11200   // note that we bias towards the LHS being the pointer.
11201   Expr *PExp = LHS.get(), *IExp = RHS.get();
11202 
11203   bool isObjCPointer;
11204   if (PExp->getType()->isPointerType()) {
11205     isObjCPointer = false;
11206   } else if (PExp->getType()->isObjCObjectPointerType()) {
11207     isObjCPointer = true;
11208   } else {
11209     std::swap(PExp, IExp);
11210     if (PExp->getType()->isPointerType()) {
11211       isObjCPointer = false;
11212     } else if (PExp->getType()->isObjCObjectPointerType()) {
11213       isObjCPointer = true;
11214     } else {
11215       return InvalidOperands(Loc, LHS, RHS);
11216     }
11217   }
11218   assert(PExp->getType()->isAnyPointerType());
11219 
11220   if (!IExp->getType()->isIntegerType())
11221     return InvalidOperands(Loc, LHS, RHS);
11222 
11223   // Adding to a null pointer results in undefined behavior.
11224   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11225           Context, Expr::NPC_ValueDependentIsNotNull)) {
11226     // In C++ adding zero to a null pointer is defined.
11227     Expr::EvalResult KnownVal;
11228     if (!getLangOpts().CPlusPlus ||
11229         (!IExp->isValueDependent() &&
11230          (!IExp->EvaluateAsInt(KnownVal, Context) ||
11231           KnownVal.Val.getInt() != 0))) {
11232       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11233       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11234           Context, BO_Add, PExp, IExp);
11235       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11236     }
11237   }
11238 
11239   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11240     return QualType();
11241 
11242   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11243     return QualType();
11244 
11245   // Check array bounds for pointer arithemtic
11246   CheckArrayAccess(PExp, IExp);
11247 
11248   if (CompLHSTy) {
11249     QualType LHSTy = Context.isPromotableBitField(LHS.get());
11250     if (LHSTy.isNull()) {
11251       LHSTy = LHS.get()->getType();
11252       if (LHSTy->isPromotableIntegerType())
11253         LHSTy = Context.getPromotedIntegerType(LHSTy);
11254     }
11255     *CompLHSTy = LHSTy;
11256   }
11257 
11258   return PExp->getType();
11259 }
11260 
11261 // C99 6.5.6
11262 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11263                                         SourceLocation Loc,
11264                                         QualType* CompLHSTy) {
11265   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11266 
11267   if (LHS.get()->getType()->isVectorType() ||
11268       RHS.get()->getType()->isVectorType()) {
11269     QualType compType =
11270         CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11271                             /*AllowBothBool*/ getLangOpts().AltiVec,
11272                             /*AllowBoolConversions*/ getLangOpts().ZVector,
11273                             /*AllowBooleanOperation*/ false,
11274                             /*ReportInvalid*/ true);
11275     if (CompLHSTy) *CompLHSTy = compType;
11276     return compType;
11277   }
11278 
11279   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11280       RHS.get()->getType()->isVLSTBuiltinType()) {
11281     QualType compType =
11282         CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11283     if (CompLHSTy)
11284       *CompLHSTy = compType;
11285     return compType;
11286   }
11287 
11288   if (LHS.get()->getType()->isConstantMatrixType() ||
11289       RHS.get()->getType()->isConstantMatrixType()) {
11290     QualType compType =
11291         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11292     if (CompLHSTy)
11293       *CompLHSTy = compType;
11294     return compType;
11295   }
11296 
11297   QualType compType = UsualArithmeticConversions(
11298       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11299   if (LHS.isInvalid() || RHS.isInvalid())
11300     return QualType();
11301 
11302   // Enforce type constraints: C99 6.5.6p3.
11303 
11304   // Handle the common case first (both operands are arithmetic).
11305   if (!compType.isNull() && compType->isArithmeticType()) {
11306     if (CompLHSTy) *CompLHSTy = compType;
11307     return compType;
11308   }
11309 
11310   // Either ptr - int   or   ptr - ptr.
11311   if (LHS.get()->getType()->isAnyPointerType()) {
11312     QualType lpointee = LHS.get()->getType()->getPointeeType();
11313 
11314     // Diagnose bad cases where we step over interface counts.
11315     if (LHS.get()->getType()->isObjCObjectPointerType() &&
11316         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11317       return QualType();
11318 
11319     // The result type of a pointer-int computation is the pointer type.
11320     if (RHS.get()->getType()->isIntegerType()) {
11321       // Subtracting from a null pointer should produce a warning.
11322       // The last argument to the diagnose call says this doesn't match the
11323       // GNU int-to-pointer idiom.
11324       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11325                                            Expr::NPC_ValueDependentIsNotNull)) {
11326         // In C++ adding zero to a null pointer is defined.
11327         Expr::EvalResult KnownVal;
11328         if (!getLangOpts().CPlusPlus ||
11329             (!RHS.get()->isValueDependent() &&
11330              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11331               KnownVal.Val.getInt() != 0))) {
11332           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11333         }
11334       }
11335 
11336       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11337         return QualType();
11338 
11339       // Check array bounds for pointer arithemtic
11340       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11341                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11342 
11343       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11344       return LHS.get()->getType();
11345     }
11346 
11347     // Handle pointer-pointer subtractions.
11348     if (const PointerType *RHSPTy
11349           = RHS.get()->getType()->getAs<PointerType>()) {
11350       QualType rpointee = RHSPTy->getPointeeType();
11351 
11352       if (getLangOpts().CPlusPlus) {
11353         // Pointee types must be the same: C++ [expr.add]
11354         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11355           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11356         }
11357       } else {
11358         // Pointee types must be compatible C99 6.5.6p3
11359         if (!Context.typesAreCompatible(
11360                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11361                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11362           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11363           return QualType();
11364         }
11365       }
11366 
11367       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11368                                                LHS.get(), RHS.get()))
11369         return QualType();
11370 
11371       bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11372           Context, Expr::NPC_ValueDependentIsNotNull);
11373       bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11374           Context, Expr::NPC_ValueDependentIsNotNull);
11375 
11376       // Subtracting nullptr or from nullptr is suspect
11377       if (LHSIsNullPtr)
11378         diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11379       if (RHSIsNullPtr)
11380         diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11381 
11382       // The pointee type may have zero size.  As an extension, a structure or
11383       // union may have zero size or an array may have zero length.  In this
11384       // case subtraction does not make sense.
11385       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11386         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11387         if (ElementSize.isZero()) {
11388           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11389             << rpointee.getUnqualifiedType()
11390             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11391         }
11392       }
11393 
11394       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11395       return Context.getPointerDiffType();
11396     }
11397   }
11398 
11399   return InvalidOperands(Loc, LHS, RHS);
11400 }
11401 
11402 static bool isScopedEnumerationType(QualType T) {
11403   if (const EnumType *ET = T->getAs<EnumType>())
11404     return ET->getDecl()->isScoped();
11405   return false;
11406 }
11407 
11408 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11409                                    SourceLocation Loc, BinaryOperatorKind Opc,
11410                                    QualType LHSType) {
11411   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11412   // so skip remaining warnings as we don't want to modify values within Sema.
11413   if (S.getLangOpts().OpenCL)
11414     return;
11415 
11416   // Check right/shifter operand
11417   Expr::EvalResult RHSResult;
11418   if (RHS.get()->isValueDependent() ||
11419       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11420     return;
11421   llvm::APSInt Right = RHSResult.Val.getInt();
11422 
11423   if (Right.isNegative()) {
11424     S.DiagRuntimeBehavior(Loc, RHS.get(),
11425                           S.PDiag(diag::warn_shift_negative)
11426                             << RHS.get()->getSourceRange());
11427     return;
11428   }
11429 
11430   QualType LHSExprType = LHS.get()->getType();
11431   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11432   if (LHSExprType->isBitIntType())
11433     LeftSize = S.Context.getIntWidth(LHSExprType);
11434   else if (LHSExprType->isFixedPointType()) {
11435     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11436     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11437   }
11438   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11439   if (Right.uge(LeftBits)) {
11440     S.DiagRuntimeBehavior(Loc, RHS.get(),
11441                           S.PDiag(diag::warn_shift_gt_typewidth)
11442                             << RHS.get()->getSourceRange());
11443     return;
11444   }
11445 
11446   // FIXME: We probably need to handle fixed point types specially here.
11447   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11448     return;
11449 
11450   // When left shifting an ICE which is signed, we can check for overflow which
11451   // according to C++ standards prior to C++2a has undefined behavior
11452   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11453   // more than the maximum value representable in the result type, so never
11454   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11455   // expression is still probably a bug.)
11456   Expr::EvalResult LHSResult;
11457   if (LHS.get()->isValueDependent() ||
11458       LHSType->hasUnsignedIntegerRepresentation() ||
11459       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11460     return;
11461   llvm::APSInt Left = LHSResult.Val.getInt();
11462 
11463   // Don't warn if signed overflow is defined, then all the rest of the
11464   // diagnostics will not be triggered because the behavior is defined.
11465   // Also don't warn in C++20 mode (and newer), as signed left shifts
11466   // always wrap and never overflow.
11467   if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11468     return;
11469 
11470   // If LHS does not have a non-negative value then, the
11471   // behavior is undefined before C++2a. Warn about it.
11472   if (Left.isNegative()) {
11473     S.DiagRuntimeBehavior(Loc, LHS.get(),
11474                           S.PDiag(diag::warn_shift_lhs_negative)
11475                             << LHS.get()->getSourceRange());
11476     return;
11477   }
11478 
11479   llvm::APInt ResultBits =
11480       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
11481   if (LeftBits.uge(ResultBits))
11482     return;
11483   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11484   Result = Result.shl(Right);
11485 
11486   // Print the bit representation of the signed integer as an unsigned
11487   // hexadecimal number.
11488   SmallString<40> HexResult;
11489   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11490 
11491   // If we are only missing a sign bit, this is less likely to result in actual
11492   // bugs -- if the result is cast back to an unsigned type, it will have the
11493   // expected value. Thus we place this behind a different warning that can be
11494   // turned off separately if needed.
11495   if (LeftBits == ResultBits - 1) {
11496     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11497         << HexResult << LHSType
11498         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11499     return;
11500   }
11501 
11502   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11503     << HexResult.str() << Result.getMinSignedBits() << LHSType
11504     << Left.getBitWidth() << LHS.get()->getSourceRange()
11505     << RHS.get()->getSourceRange();
11506 }
11507 
11508 /// Return the resulting type when a vector is shifted
11509 ///        by a scalar or vector shift amount.
11510 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11511                                  SourceLocation Loc, bool IsCompAssign) {
11512   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11513   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11514       !LHS.get()->getType()->isVectorType()) {
11515     S.Diag(Loc, diag::err_shift_rhs_only_vector)
11516       << RHS.get()->getType() << LHS.get()->getType()
11517       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11518     return QualType();
11519   }
11520 
11521   if (!IsCompAssign) {
11522     LHS = S.UsualUnaryConversions(LHS.get());
11523     if (LHS.isInvalid()) return QualType();
11524   }
11525 
11526   RHS = S.UsualUnaryConversions(RHS.get());
11527   if (RHS.isInvalid()) return QualType();
11528 
11529   QualType LHSType = LHS.get()->getType();
11530   // Note that LHS might be a scalar because the routine calls not only in
11531   // OpenCL case.
11532   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11533   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11534 
11535   // Note that RHS might not be a vector.
11536   QualType RHSType = RHS.get()->getType();
11537   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11538   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11539 
11540   // Do not allow shifts for boolean vectors.
11541   if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11542       (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11543     S.Diag(Loc, diag::err_typecheck_invalid_operands)
11544         << LHS.get()->getType() << RHS.get()->getType()
11545         << LHS.get()->getSourceRange();
11546     return QualType();
11547   }
11548 
11549   // The operands need to be integers.
11550   if (!LHSEleType->isIntegerType()) {
11551     S.Diag(Loc, diag::err_typecheck_expect_int)
11552       << LHS.get()->getType() << LHS.get()->getSourceRange();
11553     return QualType();
11554   }
11555 
11556   if (!RHSEleType->isIntegerType()) {
11557     S.Diag(Loc, diag::err_typecheck_expect_int)
11558       << RHS.get()->getType() << RHS.get()->getSourceRange();
11559     return QualType();
11560   }
11561 
11562   if (!LHSVecTy) {
11563     assert(RHSVecTy);
11564     if (IsCompAssign)
11565       return RHSType;
11566     if (LHSEleType != RHSEleType) {
11567       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11568       LHSEleType = RHSEleType;
11569     }
11570     QualType VecTy =
11571         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11572     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11573     LHSType = VecTy;
11574   } else if (RHSVecTy) {
11575     // OpenCL v1.1 s6.3.j says that for vector types, the operators
11576     // are applied component-wise. So if RHS is a vector, then ensure
11577     // that the number of elements is the same as LHS...
11578     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11579       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11580         << LHS.get()->getType() << RHS.get()->getType()
11581         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11582       return QualType();
11583     }
11584     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11585       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11586       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11587       if (LHSBT != RHSBT &&
11588           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11589         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11590             << LHS.get()->getType() << RHS.get()->getType()
11591             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11592       }
11593     }
11594   } else {
11595     // ...else expand RHS to match the number of elements in LHS.
11596     QualType VecTy =
11597       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11598     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11599   }
11600 
11601   return LHSType;
11602 }
11603 
11604 static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
11605                                          ExprResult &RHS, SourceLocation Loc,
11606                                          bool IsCompAssign) {
11607   if (!IsCompAssign) {
11608     LHS = S.UsualUnaryConversions(LHS.get());
11609     if (LHS.isInvalid())
11610       return QualType();
11611   }
11612 
11613   RHS = S.UsualUnaryConversions(RHS.get());
11614   if (RHS.isInvalid())
11615     return QualType();
11616 
11617   QualType LHSType = LHS.get()->getType();
11618   const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11619   QualType LHSEleType = LHSType->isVLSTBuiltinType()
11620                             ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11621                             : LHSType;
11622 
11623   // Note that RHS might not be a vector
11624   QualType RHSType = RHS.get()->getType();
11625   const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11626   QualType RHSEleType = RHSType->isVLSTBuiltinType()
11627                             ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11628                             : RHSType;
11629 
11630   if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11631       (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11632     S.Diag(Loc, diag::err_typecheck_invalid_operands)
11633         << LHSType << RHSType << LHS.get()->getSourceRange();
11634     return QualType();
11635   }
11636 
11637   if (!LHSEleType->isIntegerType()) {
11638     S.Diag(Loc, diag::err_typecheck_expect_int)
11639         << LHS.get()->getType() << LHS.get()->getSourceRange();
11640     return QualType();
11641   }
11642 
11643   if (!RHSEleType->isIntegerType()) {
11644     S.Diag(Loc, diag::err_typecheck_expect_int)
11645         << RHS.get()->getType() << RHS.get()->getSourceRange();
11646     return QualType();
11647   }
11648 
11649   if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
11650       (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11651        S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11652     S.Diag(Loc, diag::err_typecheck_invalid_operands)
11653         << LHSType << RHSType << LHS.get()->getSourceRange()
11654         << RHS.get()->getSourceRange();
11655     return QualType();
11656   }
11657 
11658   if (!LHSType->isVLSTBuiltinType()) {
11659     assert(RHSType->isVLSTBuiltinType());
11660     if (IsCompAssign)
11661       return RHSType;
11662     if (LHSEleType != RHSEleType) {
11663       LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11664       LHSEleType = RHSEleType;
11665     }
11666     const llvm::ElementCount VecSize =
11667         S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11668     QualType VecTy =
11669         S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11670     LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11671     LHSType = VecTy;
11672   } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) {
11673     if (S.Context.getTypeSize(RHSBuiltinTy) !=
11674         S.Context.getTypeSize(LHSBuiltinTy)) {
11675       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11676           << LHSType << RHSType << LHS.get()->getSourceRange()
11677           << RHS.get()->getSourceRange();
11678       return QualType();
11679     }
11680   } else {
11681     const llvm::ElementCount VecSize =
11682         S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11683     if (LHSEleType != RHSEleType) {
11684       RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11685       RHSEleType = LHSEleType;
11686     }
11687     QualType VecTy =
11688         S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11689     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11690   }
11691 
11692   return LHSType;
11693 }
11694 
11695 // C99 6.5.7
11696 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11697                                   SourceLocation Loc, BinaryOperatorKind Opc,
11698                                   bool IsCompAssign) {
11699   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11700 
11701   // Vector shifts promote their scalar inputs to vector type.
11702   if (LHS.get()->getType()->isVectorType() ||
11703       RHS.get()->getType()->isVectorType()) {
11704     if (LangOpts.ZVector) {
11705       // The shift operators for the z vector extensions work basically
11706       // like general shifts, except that neither the LHS nor the RHS is
11707       // allowed to be a "vector bool".
11708       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11709         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11710           return InvalidOperands(Loc, LHS, RHS);
11711       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11712         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11713           return InvalidOperands(Loc, LHS, RHS);
11714     }
11715     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11716   }
11717 
11718   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11719       RHS.get()->getType()->isVLSTBuiltinType())
11720     return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11721 
11722   // Shifts don't perform usual arithmetic conversions, they just do integer
11723   // promotions on each operand. C99 6.5.7p3
11724 
11725   // For the LHS, do usual unary conversions, but then reset them away
11726   // if this is a compound assignment.
11727   ExprResult OldLHS = LHS;
11728   LHS = UsualUnaryConversions(LHS.get());
11729   if (LHS.isInvalid())
11730     return QualType();
11731   QualType LHSType = LHS.get()->getType();
11732   if (IsCompAssign) LHS = OldLHS;
11733 
11734   // The RHS is simpler.
11735   RHS = UsualUnaryConversions(RHS.get());
11736   if (RHS.isInvalid())
11737     return QualType();
11738   QualType RHSType = RHS.get()->getType();
11739 
11740   // C99 6.5.7p2: Each of the operands shall have integer type.
11741   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11742   if ((!LHSType->isFixedPointOrIntegerType() &&
11743        !LHSType->hasIntegerRepresentation()) ||
11744       !RHSType->hasIntegerRepresentation())
11745     return InvalidOperands(Loc, LHS, RHS);
11746 
11747   // C++0x: Don't allow scoped enums. FIXME: Use something better than
11748   // hasIntegerRepresentation() above instead of this.
11749   if (isScopedEnumerationType(LHSType) ||
11750       isScopedEnumerationType(RHSType)) {
11751     return InvalidOperands(Loc, LHS, RHS);
11752   }
11753   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11754 
11755   // "The type of the result is that of the promoted left operand."
11756   return LHSType;
11757 }
11758 
11759 /// Diagnose bad pointer comparisons.
11760 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11761                                               ExprResult &LHS, ExprResult &RHS,
11762                                               bool IsError) {
11763   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11764                       : diag::ext_typecheck_comparison_of_distinct_pointers)
11765     << LHS.get()->getType() << RHS.get()->getType()
11766     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11767 }
11768 
11769 /// Returns false if the pointers are converted to a composite type,
11770 /// true otherwise.
11771 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11772                                            ExprResult &LHS, ExprResult &RHS) {
11773   // C++ [expr.rel]p2:
11774   //   [...] Pointer conversions (4.10) and qualification
11775   //   conversions (4.4) are performed on pointer operands (or on
11776   //   a pointer operand and a null pointer constant) to bring
11777   //   them to their composite pointer type. [...]
11778   //
11779   // C++ [expr.eq]p1 uses the same notion for (in)equality
11780   // comparisons of pointers.
11781 
11782   QualType LHSType = LHS.get()->getType();
11783   QualType RHSType = RHS.get()->getType();
11784   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11785          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11786 
11787   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11788   if (T.isNull()) {
11789     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11790         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11791       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11792     else
11793       S.InvalidOperands(Loc, LHS, RHS);
11794     return true;
11795   }
11796 
11797   return false;
11798 }
11799 
11800 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11801                                                     ExprResult &LHS,
11802                                                     ExprResult &RHS,
11803                                                     bool IsError) {
11804   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11805                       : diag::ext_typecheck_comparison_of_fptr_to_void)
11806     << LHS.get()->getType() << RHS.get()->getType()
11807     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11808 }
11809 
11810 static bool isObjCObjectLiteral(ExprResult &E) {
11811   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11812   case Stmt::ObjCArrayLiteralClass:
11813   case Stmt::ObjCDictionaryLiteralClass:
11814   case Stmt::ObjCStringLiteralClass:
11815   case Stmt::ObjCBoxedExprClass:
11816     return true;
11817   default:
11818     // Note that ObjCBoolLiteral is NOT an object literal!
11819     return false;
11820   }
11821 }
11822 
11823 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11824   const ObjCObjectPointerType *Type =
11825     LHS->getType()->getAs<ObjCObjectPointerType>();
11826 
11827   // If this is not actually an Objective-C object, bail out.
11828   if (!Type)
11829     return false;
11830 
11831   // Get the LHS object's interface type.
11832   QualType InterfaceType = Type->getPointeeType();
11833 
11834   // If the RHS isn't an Objective-C object, bail out.
11835   if (!RHS->getType()->isObjCObjectPointerType())
11836     return false;
11837 
11838   // Try to find the -isEqual: method.
11839   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11840   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11841                                                       InterfaceType,
11842                                                       /*IsInstance=*/true);
11843   if (!Method) {
11844     if (Type->isObjCIdType()) {
11845       // For 'id', just check the global pool.
11846       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11847                                                   /*receiverId=*/true);
11848     } else {
11849       // Check protocols.
11850       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11851                                              /*IsInstance=*/true);
11852     }
11853   }
11854 
11855   if (!Method)
11856     return false;
11857 
11858   QualType T = Method->parameters()[0]->getType();
11859   if (!T->isObjCObjectPointerType())
11860     return false;
11861 
11862   QualType R = Method->getReturnType();
11863   if (!R->isScalarType())
11864     return false;
11865 
11866   return true;
11867 }
11868 
11869 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11870   FromE = FromE->IgnoreParenImpCasts();
11871   switch (FromE->getStmtClass()) {
11872     default:
11873       break;
11874     case Stmt::ObjCStringLiteralClass:
11875       // "string literal"
11876       return LK_String;
11877     case Stmt::ObjCArrayLiteralClass:
11878       // "array literal"
11879       return LK_Array;
11880     case Stmt::ObjCDictionaryLiteralClass:
11881       // "dictionary literal"
11882       return LK_Dictionary;
11883     case Stmt::BlockExprClass:
11884       return LK_Block;
11885     case Stmt::ObjCBoxedExprClass: {
11886       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11887       switch (Inner->getStmtClass()) {
11888         case Stmt::IntegerLiteralClass:
11889         case Stmt::FloatingLiteralClass:
11890         case Stmt::CharacterLiteralClass:
11891         case Stmt::ObjCBoolLiteralExprClass:
11892         case Stmt::CXXBoolLiteralExprClass:
11893           // "numeric literal"
11894           return LK_Numeric;
11895         case Stmt::ImplicitCastExprClass: {
11896           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11897           // Boolean literals can be represented by implicit casts.
11898           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11899             return LK_Numeric;
11900           break;
11901         }
11902         default:
11903           break;
11904       }
11905       return LK_Boxed;
11906     }
11907   }
11908   return LK_None;
11909 }
11910 
11911 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11912                                           ExprResult &LHS, ExprResult &RHS,
11913                                           BinaryOperator::Opcode Opc){
11914   Expr *Literal;
11915   Expr *Other;
11916   if (isObjCObjectLiteral(LHS)) {
11917     Literal = LHS.get();
11918     Other = RHS.get();
11919   } else {
11920     Literal = RHS.get();
11921     Other = LHS.get();
11922   }
11923 
11924   // Don't warn on comparisons against nil.
11925   Other = Other->IgnoreParenCasts();
11926   if (Other->isNullPointerConstant(S.getASTContext(),
11927                                    Expr::NPC_ValueDependentIsNotNull))
11928     return;
11929 
11930   // This should be kept in sync with warn_objc_literal_comparison.
11931   // LK_String should always be after the other literals, since it has its own
11932   // warning flag.
11933   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11934   assert(LiteralKind != Sema::LK_Block);
11935   if (LiteralKind == Sema::LK_None) {
11936     llvm_unreachable("Unknown Objective-C object literal kind");
11937   }
11938 
11939   if (LiteralKind == Sema::LK_String)
11940     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11941       << Literal->getSourceRange();
11942   else
11943     S.Diag(Loc, diag::warn_objc_literal_comparison)
11944       << LiteralKind << Literal->getSourceRange();
11945 
11946   if (BinaryOperator::isEqualityOp(Opc) &&
11947       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11948     SourceLocation Start = LHS.get()->getBeginLoc();
11949     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11950     CharSourceRange OpRange =
11951       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11952 
11953     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11954       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11955       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11956       << FixItHint::CreateInsertion(End, "]");
11957   }
11958 }
11959 
11960 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11961 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11962                                            ExprResult &RHS, SourceLocation Loc,
11963                                            BinaryOperatorKind Opc) {
11964   // Check that left hand side is !something.
11965   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11966   if (!UO || UO->getOpcode() != UO_LNot) return;
11967 
11968   // Only check if the right hand side is non-bool arithmetic type.
11969   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11970 
11971   // Make sure that the something in !something is not bool.
11972   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11973   if (SubExpr->isKnownToHaveBooleanValue()) return;
11974 
11975   // Emit warning.
11976   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11977   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11978       << Loc << IsBitwiseOp;
11979 
11980   // First note suggest !(x < y)
11981   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11982   SourceLocation FirstClose = RHS.get()->getEndLoc();
11983   FirstClose = S.getLocForEndOfToken(FirstClose);
11984   if (FirstClose.isInvalid())
11985     FirstOpen = SourceLocation();
11986   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11987       << IsBitwiseOp
11988       << FixItHint::CreateInsertion(FirstOpen, "(")
11989       << FixItHint::CreateInsertion(FirstClose, ")");
11990 
11991   // Second note suggests (!x) < y
11992   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11993   SourceLocation SecondClose = LHS.get()->getEndLoc();
11994   SecondClose = S.getLocForEndOfToken(SecondClose);
11995   if (SecondClose.isInvalid())
11996     SecondOpen = SourceLocation();
11997   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11998       << FixItHint::CreateInsertion(SecondOpen, "(")
11999       << FixItHint::CreateInsertion(SecondClose, ")");
12000 }
12001 
12002 // Returns true if E refers to a non-weak array.
12003 static bool checkForArray(const Expr *E) {
12004   const ValueDecl *D = nullptr;
12005   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12006     D = DR->getDecl();
12007   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12008     if (Mem->isImplicitAccess())
12009       D = Mem->getMemberDecl();
12010   }
12011   if (!D)
12012     return false;
12013   return D->getType()->isArrayType() && !D->isWeak();
12014 }
12015 
12016 /// Diagnose some forms of syntactically-obvious tautological comparison.
12017 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12018                                            Expr *LHS, Expr *RHS,
12019                                            BinaryOperatorKind Opc) {
12020   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12021   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12022 
12023   QualType LHSType = LHS->getType();
12024   QualType RHSType = RHS->getType();
12025   if (LHSType->hasFloatingRepresentation() ||
12026       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12027       S.inTemplateInstantiation())
12028     return;
12029 
12030   // Comparisons between two array types are ill-formed for operator<=>, so
12031   // we shouldn't emit any additional warnings about it.
12032   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12033     return;
12034 
12035   // For non-floating point types, check for self-comparisons of the form
12036   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12037   // often indicate logic errors in the program.
12038   //
12039   // NOTE: Don't warn about comparison expressions resulting from macro
12040   // expansion. Also don't warn about comparisons which are only self
12041   // comparisons within a template instantiation. The warnings should catch
12042   // obvious cases in the definition of the template anyways. The idea is to
12043   // warn when the typed comparison operator will always evaluate to the same
12044   // result.
12045 
12046   // Used for indexing into %select in warn_comparison_always
12047   enum {
12048     AlwaysConstant,
12049     AlwaysTrue,
12050     AlwaysFalse,
12051     AlwaysEqual, // std::strong_ordering::equal from operator<=>
12052   };
12053 
12054   // C++2a [depr.array.comp]:
12055   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12056   //   operands of array type are deprecated.
12057   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
12058       RHSStripped->getType()->isArrayType()) {
12059     S.Diag(Loc, diag::warn_depr_array_comparison)
12060         << LHS->getSourceRange() << RHS->getSourceRange()
12061         << LHSStripped->getType() << RHSStripped->getType();
12062     // Carry on to produce the tautological comparison warning, if this
12063     // expression is potentially-evaluated, we can resolve the array to a
12064     // non-weak declaration, and so on.
12065   }
12066 
12067   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12068     if (Expr::isSameComparisonOperand(LHS, RHS)) {
12069       unsigned Result;
12070       switch (Opc) {
12071       case BO_EQ:
12072       case BO_LE:
12073       case BO_GE:
12074         Result = AlwaysTrue;
12075         break;
12076       case BO_NE:
12077       case BO_LT:
12078       case BO_GT:
12079         Result = AlwaysFalse;
12080         break;
12081       case BO_Cmp:
12082         Result = AlwaysEqual;
12083         break;
12084       default:
12085         Result = AlwaysConstant;
12086         break;
12087       }
12088       S.DiagRuntimeBehavior(Loc, nullptr,
12089                             S.PDiag(diag::warn_comparison_always)
12090                                 << 0 /*self-comparison*/
12091                                 << Result);
12092     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12093       // What is it always going to evaluate to?
12094       unsigned Result;
12095       switch (Opc) {
12096       case BO_EQ: // e.g. array1 == array2
12097         Result = AlwaysFalse;
12098         break;
12099       case BO_NE: // e.g. array1 != array2
12100         Result = AlwaysTrue;
12101         break;
12102       default: // e.g. array1 <= array2
12103         // The best we can say is 'a constant'
12104         Result = AlwaysConstant;
12105         break;
12106       }
12107       S.DiagRuntimeBehavior(Loc, nullptr,
12108                             S.PDiag(diag::warn_comparison_always)
12109                                 << 1 /*array comparison*/
12110                                 << Result);
12111     }
12112   }
12113 
12114   if (isa<CastExpr>(LHSStripped))
12115     LHSStripped = LHSStripped->IgnoreParenCasts();
12116   if (isa<CastExpr>(RHSStripped))
12117     RHSStripped = RHSStripped->IgnoreParenCasts();
12118 
12119   // Warn about comparisons against a string constant (unless the other
12120   // operand is null); the user probably wants string comparison function.
12121   Expr *LiteralString = nullptr;
12122   Expr *LiteralStringStripped = nullptr;
12123   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12124       !RHSStripped->isNullPointerConstant(S.Context,
12125                                           Expr::NPC_ValueDependentIsNull)) {
12126     LiteralString = LHS;
12127     LiteralStringStripped = LHSStripped;
12128   } else if ((isa<StringLiteral>(RHSStripped) ||
12129               isa<ObjCEncodeExpr>(RHSStripped)) &&
12130              !LHSStripped->isNullPointerConstant(S.Context,
12131                                           Expr::NPC_ValueDependentIsNull)) {
12132     LiteralString = RHS;
12133     LiteralStringStripped = RHSStripped;
12134   }
12135 
12136   if (LiteralString) {
12137     S.DiagRuntimeBehavior(Loc, nullptr,
12138                           S.PDiag(diag::warn_stringcompare)
12139                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
12140                               << LiteralString->getSourceRange());
12141   }
12142 }
12143 
12144 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12145   switch (CK) {
12146   default: {
12147 #ifndef NDEBUG
12148     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12149                  << "\n";
12150 #endif
12151     llvm_unreachable("unhandled cast kind");
12152   }
12153   case CK_UserDefinedConversion:
12154     return ICK_Identity;
12155   case CK_LValueToRValue:
12156     return ICK_Lvalue_To_Rvalue;
12157   case CK_ArrayToPointerDecay:
12158     return ICK_Array_To_Pointer;
12159   case CK_FunctionToPointerDecay:
12160     return ICK_Function_To_Pointer;
12161   case CK_IntegralCast:
12162     return ICK_Integral_Conversion;
12163   case CK_FloatingCast:
12164     return ICK_Floating_Conversion;
12165   case CK_IntegralToFloating:
12166   case CK_FloatingToIntegral:
12167     return ICK_Floating_Integral;
12168   case CK_IntegralComplexCast:
12169   case CK_FloatingComplexCast:
12170   case CK_FloatingComplexToIntegralComplex:
12171   case CK_IntegralComplexToFloatingComplex:
12172     return ICK_Complex_Conversion;
12173   case CK_FloatingComplexToReal:
12174   case CK_FloatingRealToComplex:
12175   case CK_IntegralComplexToReal:
12176   case CK_IntegralRealToComplex:
12177     return ICK_Complex_Real;
12178   }
12179 }
12180 
12181 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12182                                              QualType FromType,
12183                                              SourceLocation Loc) {
12184   // Check for a narrowing implicit conversion.
12185   StandardConversionSequence SCS;
12186   SCS.setAsIdentityConversion();
12187   SCS.setToType(0, FromType);
12188   SCS.setToType(1, ToType);
12189   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12190     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12191 
12192   APValue PreNarrowingValue;
12193   QualType PreNarrowingType;
12194   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12195                                PreNarrowingType,
12196                                /*IgnoreFloatToIntegralConversion*/ true)) {
12197   case NK_Dependent_Narrowing:
12198     // Implicit conversion to a narrower type, but the expression is
12199     // value-dependent so we can't tell whether it's actually narrowing.
12200   case NK_Not_Narrowing:
12201     return false;
12202 
12203   case NK_Constant_Narrowing:
12204     // Implicit conversion to a narrower type, and the value is not a constant
12205     // expression.
12206     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12207         << /*Constant*/ 1
12208         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12209     return true;
12210 
12211   case NK_Variable_Narrowing:
12212     // Implicit conversion to a narrower type, and the value is not a constant
12213     // expression.
12214   case NK_Type_Narrowing:
12215     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12216         << /*Constant*/ 0 << FromType << ToType;
12217     // TODO: It's not a constant expression, but what if the user intended it
12218     // to be? Can we produce notes to help them figure out why it isn't?
12219     return true;
12220   }
12221   llvm_unreachable("unhandled case in switch");
12222 }
12223 
12224 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12225                                                          ExprResult &LHS,
12226                                                          ExprResult &RHS,
12227                                                          SourceLocation Loc) {
12228   QualType LHSType = LHS.get()->getType();
12229   QualType RHSType = RHS.get()->getType();
12230   // Dig out the original argument type and expression before implicit casts
12231   // were applied. These are the types/expressions we need to check the
12232   // [expr.spaceship] requirements against.
12233   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12234   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12235   QualType LHSStrippedType = LHSStripped.get()->getType();
12236   QualType RHSStrippedType = RHSStripped.get()->getType();
12237 
12238   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12239   // other is not, the program is ill-formed.
12240   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12241     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12242     return QualType();
12243   }
12244 
12245   // FIXME: Consider combining this with checkEnumArithmeticConversions.
12246   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12247                     RHSStrippedType->isEnumeralType();
12248   if (NumEnumArgs == 1) {
12249     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12250     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12251     if (OtherTy->hasFloatingRepresentation()) {
12252       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12253       return QualType();
12254     }
12255   }
12256   if (NumEnumArgs == 2) {
12257     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12258     // type E, the operator yields the result of converting the operands
12259     // to the underlying type of E and applying <=> to the converted operands.
12260     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12261       S.InvalidOperands(Loc, LHS, RHS);
12262       return QualType();
12263     }
12264     QualType IntType =
12265         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12266     assert(IntType->isArithmeticType());
12267 
12268     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12269     // promote the boolean type, and all other promotable integer types, to
12270     // avoid this.
12271     if (IntType->isPromotableIntegerType())
12272       IntType = S.Context.getPromotedIntegerType(IntType);
12273 
12274     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12275     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12276     LHSType = RHSType = IntType;
12277   }
12278 
12279   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12280   // usual arithmetic conversions are applied to the operands.
12281   QualType Type =
12282       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12283   if (LHS.isInvalid() || RHS.isInvalid())
12284     return QualType();
12285   if (Type.isNull())
12286     return S.InvalidOperands(Loc, LHS, RHS);
12287 
12288   Optional<ComparisonCategoryType> CCT =
12289       getComparisonCategoryForBuiltinCmp(Type);
12290   if (!CCT)
12291     return S.InvalidOperands(Loc, LHS, RHS);
12292 
12293   bool HasNarrowing = checkThreeWayNarrowingConversion(
12294       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12295   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12296                                                    RHS.get()->getBeginLoc());
12297   if (HasNarrowing)
12298     return QualType();
12299 
12300   assert(!Type.isNull() && "composite type for <=> has not been set");
12301 
12302   return S.CheckComparisonCategoryType(
12303       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
12304 }
12305 
12306 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12307                                                  ExprResult &RHS,
12308                                                  SourceLocation Loc,
12309                                                  BinaryOperatorKind Opc) {
12310   if (Opc == BO_Cmp)
12311     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12312 
12313   // C99 6.5.8p3 / C99 6.5.9p4
12314   QualType Type =
12315       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12316   if (LHS.isInvalid() || RHS.isInvalid())
12317     return QualType();
12318   if (Type.isNull())
12319     return S.InvalidOperands(Loc, LHS, RHS);
12320   assert(Type->isArithmeticType() || Type->isEnumeralType());
12321 
12322   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12323     return S.InvalidOperands(Loc, LHS, RHS);
12324 
12325   // Check for comparisons of floating point operands using != and ==.
12326   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
12327     S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12328 
12329   // The result of comparisons is 'bool' in C++, 'int' in C.
12330   return S.Context.getLogicalOperationType();
12331 }
12332 
12333 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12334   if (!NullE.get()->getType()->isAnyPointerType())
12335     return;
12336   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12337   if (!E.get()->getType()->isAnyPointerType() &&
12338       E.get()->isNullPointerConstant(Context,
12339                                      Expr::NPC_ValueDependentIsNotNull) ==
12340         Expr::NPCK_ZeroExpression) {
12341     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12342       if (CL->getValue() == 0)
12343         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12344             << NullValue
12345             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12346                                             NullValue ? "NULL" : "(void *)0");
12347     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12348         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12349         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12350         if (T == Context.CharTy)
12351           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12352               << NullValue
12353               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12354                                               NullValue ? "NULL" : "(void *)0");
12355       }
12356   }
12357 }
12358 
12359 // C99 6.5.8, C++ [expr.rel]
12360 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12361                                     SourceLocation Loc,
12362                                     BinaryOperatorKind Opc) {
12363   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12364   bool IsThreeWay = Opc == BO_Cmp;
12365   bool IsOrdered = IsRelational || IsThreeWay;
12366   auto IsAnyPointerType = [](ExprResult E) {
12367     QualType Ty = E.get()->getType();
12368     return Ty->isPointerType() || Ty->isMemberPointerType();
12369   };
12370 
12371   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12372   // type, array-to-pointer, ..., conversions are performed on both operands to
12373   // bring them to their composite type.
12374   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12375   // any type-related checks.
12376   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12377     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12378     if (LHS.isInvalid())
12379       return QualType();
12380     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12381     if (RHS.isInvalid())
12382       return QualType();
12383   } else {
12384     LHS = DefaultLvalueConversion(LHS.get());
12385     if (LHS.isInvalid())
12386       return QualType();
12387     RHS = DefaultLvalueConversion(RHS.get());
12388     if (RHS.isInvalid())
12389       return QualType();
12390   }
12391 
12392   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12393   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12394     CheckPtrComparisonWithNullChar(LHS, RHS);
12395     CheckPtrComparisonWithNullChar(RHS, LHS);
12396   }
12397 
12398   // Handle vector comparisons separately.
12399   if (LHS.get()->getType()->isVectorType() ||
12400       RHS.get()->getType()->isVectorType())
12401     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12402 
12403   if (LHS.get()->getType()->isVLSTBuiltinType() ||
12404       RHS.get()->getType()->isVLSTBuiltinType())
12405     return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12406 
12407   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12408   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12409 
12410   QualType LHSType = LHS.get()->getType();
12411   QualType RHSType = RHS.get()->getType();
12412   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12413       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12414     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12415 
12416   const Expr::NullPointerConstantKind LHSNullKind =
12417       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12418   const Expr::NullPointerConstantKind RHSNullKind =
12419       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12420   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12421   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12422 
12423   auto computeResultTy = [&]() {
12424     if (Opc != BO_Cmp)
12425       return Context.getLogicalOperationType();
12426     assert(getLangOpts().CPlusPlus);
12427     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12428 
12429     QualType CompositeTy = LHS.get()->getType();
12430     assert(!CompositeTy->isReferenceType());
12431 
12432     Optional<ComparisonCategoryType> CCT =
12433         getComparisonCategoryForBuiltinCmp(CompositeTy);
12434     if (!CCT)
12435       return InvalidOperands(Loc, LHS, RHS);
12436 
12437     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12438       // P0946R0: Comparisons between a null pointer constant and an object
12439       // pointer result in std::strong_equality, which is ill-formed under
12440       // P1959R0.
12441       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12442           << (LHSIsNull ? LHS.get()->getSourceRange()
12443                         : RHS.get()->getSourceRange());
12444       return QualType();
12445     }
12446 
12447     return CheckComparisonCategoryType(
12448         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12449   };
12450 
12451   if (!IsOrdered && LHSIsNull != RHSIsNull) {
12452     bool IsEquality = Opc == BO_EQ;
12453     if (RHSIsNull)
12454       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12455                                    RHS.get()->getSourceRange());
12456     else
12457       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12458                                    LHS.get()->getSourceRange());
12459   }
12460 
12461   if (IsOrdered && LHSType->isFunctionPointerType() &&
12462       RHSType->isFunctionPointerType()) {
12463     // Valid unless a relational comparison of function pointers
12464     bool IsError = Opc == BO_Cmp;
12465     auto DiagID =
12466         IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12467         : getLangOpts().CPlusPlus
12468             ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12469             : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12470     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12471                       << RHS.get()->getSourceRange();
12472     if (IsError)
12473       return QualType();
12474   }
12475 
12476   if ((LHSType->isIntegerType() && !LHSIsNull) ||
12477       (RHSType->isIntegerType() && !RHSIsNull)) {
12478     // Skip normal pointer conversion checks in this case; we have better
12479     // diagnostics for this below.
12480   } else if (getLangOpts().CPlusPlus) {
12481     // Equality comparison of a function pointer to a void pointer is invalid,
12482     // but we allow it as an extension.
12483     // FIXME: If we really want to allow this, should it be part of composite
12484     // pointer type computation so it works in conditionals too?
12485     if (!IsOrdered &&
12486         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12487          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12488       // This is a gcc extension compatibility comparison.
12489       // In a SFINAE context, we treat this as a hard error to maintain
12490       // conformance with the C++ standard.
12491       diagnoseFunctionPointerToVoidComparison(
12492           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12493 
12494       if (isSFINAEContext())
12495         return QualType();
12496 
12497       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12498       return computeResultTy();
12499     }
12500 
12501     // C++ [expr.eq]p2:
12502     //   If at least one operand is a pointer [...] bring them to their
12503     //   composite pointer type.
12504     // C++ [expr.spaceship]p6
12505     //  If at least one of the operands is of pointer type, [...] bring them
12506     //  to their composite pointer type.
12507     // C++ [expr.rel]p2:
12508     //   If both operands are pointers, [...] bring them to their composite
12509     //   pointer type.
12510     // For <=>, the only valid non-pointer types are arrays and functions, and
12511     // we already decayed those, so this is really the same as the relational
12512     // comparison rule.
12513     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12514             (IsOrdered ? 2 : 1) &&
12515         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12516                                          RHSType->isObjCObjectPointerType()))) {
12517       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12518         return QualType();
12519       return computeResultTy();
12520     }
12521   } else if (LHSType->isPointerType() &&
12522              RHSType->isPointerType()) { // C99 6.5.8p2
12523     // All of the following pointer-related warnings are GCC extensions, except
12524     // when handling null pointer constants.
12525     QualType LCanPointeeTy =
12526       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12527     QualType RCanPointeeTy =
12528       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12529 
12530     // C99 6.5.9p2 and C99 6.5.8p2
12531     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12532                                    RCanPointeeTy.getUnqualifiedType())) {
12533       if (IsRelational) {
12534         // Pointers both need to point to complete or incomplete types
12535         if ((LCanPointeeTy->isIncompleteType() !=
12536              RCanPointeeTy->isIncompleteType()) &&
12537             !getLangOpts().C11) {
12538           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12539               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12540               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12541               << RCanPointeeTy->isIncompleteType();
12542         }
12543       }
12544     } else if (!IsRelational &&
12545                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12546       // Valid unless comparison between non-null pointer and function pointer
12547       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12548           && !LHSIsNull && !RHSIsNull)
12549         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12550                                                 /*isError*/false);
12551     } else {
12552       // Invalid
12553       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12554     }
12555     if (LCanPointeeTy != RCanPointeeTy) {
12556       // Treat NULL constant as a special case in OpenCL.
12557       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12558         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12559           Diag(Loc,
12560                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12561               << LHSType << RHSType << 0 /* comparison */
12562               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12563         }
12564       }
12565       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12566       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12567       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12568                                                : CK_BitCast;
12569       if (LHSIsNull && !RHSIsNull)
12570         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12571       else
12572         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12573     }
12574     return computeResultTy();
12575   }
12576 
12577   if (getLangOpts().CPlusPlus) {
12578     // C++ [expr.eq]p4:
12579     //   Two operands of type std::nullptr_t or one operand of type
12580     //   std::nullptr_t and the other a null pointer constant compare equal.
12581     if (!IsOrdered && LHSIsNull && RHSIsNull) {
12582       if (LHSType->isNullPtrType()) {
12583         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12584         return computeResultTy();
12585       }
12586       if (RHSType->isNullPtrType()) {
12587         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12588         return computeResultTy();
12589       }
12590     }
12591 
12592     // Comparison of Objective-C pointers and block pointers against nullptr_t.
12593     // These aren't covered by the composite pointer type rules.
12594     if (!IsOrdered && RHSType->isNullPtrType() &&
12595         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12596       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12597       return computeResultTy();
12598     }
12599     if (!IsOrdered && LHSType->isNullPtrType() &&
12600         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12601       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12602       return computeResultTy();
12603     }
12604 
12605     if (IsRelational &&
12606         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12607          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12608       // HACK: Relational comparison of nullptr_t against a pointer type is
12609       // invalid per DR583, but we allow it within std::less<> and friends,
12610       // since otherwise common uses of it break.
12611       // FIXME: Consider removing this hack once LWG fixes std::less<> and
12612       // friends to have std::nullptr_t overload candidates.
12613       DeclContext *DC = CurContext;
12614       if (isa<FunctionDecl>(DC))
12615         DC = DC->getParent();
12616       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12617         if (CTSD->isInStdNamespace() &&
12618             llvm::StringSwitch<bool>(CTSD->getName())
12619                 .Cases("less", "less_equal", "greater", "greater_equal", true)
12620                 .Default(false)) {
12621           if (RHSType->isNullPtrType())
12622             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12623           else
12624             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12625           return computeResultTy();
12626         }
12627       }
12628     }
12629 
12630     // C++ [expr.eq]p2:
12631     //   If at least one operand is a pointer to member, [...] bring them to
12632     //   their composite pointer type.
12633     if (!IsOrdered &&
12634         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12635       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12636         return QualType();
12637       else
12638         return computeResultTy();
12639     }
12640   }
12641 
12642   // Handle block pointer types.
12643   if (!IsOrdered && LHSType->isBlockPointerType() &&
12644       RHSType->isBlockPointerType()) {
12645     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12646     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12647 
12648     if (!LHSIsNull && !RHSIsNull &&
12649         !Context.typesAreCompatible(lpointee, rpointee)) {
12650       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12651         << LHSType << RHSType << LHS.get()->getSourceRange()
12652         << RHS.get()->getSourceRange();
12653     }
12654     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12655     return computeResultTy();
12656   }
12657 
12658   // Allow block pointers to be compared with null pointer constants.
12659   if (!IsOrdered
12660       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12661           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12662     if (!LHSIsNull && !RHSIsNull) {
12663       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12664              ->getPointeeType()->isVoidType())
12665             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12666                 ->getPointeeType()->isVoidType())))
12667         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12668           << LHSType << RHSType << LHS.get()->getSourceRange()
12669           << RHS.get()->getSourceRange();
12670     }
12671     if (LHSIsNull && !RHSIsNull)
12672       LHS = ImpCastExprToType(LHS.get(), RHSType,
12673                               RHSType->isPointerType() ? CK_BitCast
12674                                 : CK_AnyPointerToBlockPointerCast);
12675     else
12676       RHS = ImpCastExprToType(RHS.get(), LHSType,
12677                               LHSType->isPointerType() ? CK_BitCast
12678                                 : CK_AnyPointerToBlockPointerCast);
12679     return computeResultTy();
12680   }
12681 
12682   if (LHSType->isObjCObjectPointerType() ||
12683       RHSType->isObjCObjectPointerType()) {
12684     const PointerType *LPT = LHSType->getAs<PointerType>();
12685     const PointerType *RPT = RHSType->getAs<PointerType>();
12686     if (LPT || RPT) {
12687       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12688       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12689 
12690       if (!LPtrToVoid && !RPtrToVoid &&
12691           !Context.typesAreCompatible(LHSType, RHSType)) {
12692         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12693                                           /*isError*/false);
12694       }
12695       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12696       // the RHS, but we have test coverage for this behavior.
12697       // FIXME: Consider using convertPointersToCompositeType in C++.
12698       if (LHSIsNull && !RHSIsNull) {
12699         Expr *E = LHS.get();
12700         if (getLangOpts().ObjCAutoRefCount)
12701           CheckObjCConversion(SourceRange(), RHSType, E,
12702                               CCK_ImplicitConversion);
12703         LHS = ImpCastExprToType(E, RHSType,
12704                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12705       }
12706       else {
12707         Expr *E = RHS.get();
12708         if (getLangOpts().ObjCAutoRefCount)
12709           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12710                               /*Diagnose=*/true,
12711                               /*DiagnoseCFAudited=*/false, Opc);
12712         RHS = ImpCastExprToType(E, LHSType,
12713                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12714       }
12715       return computeResultTy();
12716     }
12717     if (LHSType->isObjCObjectPointerType() &&
12718         RHSType->isObjCObjectPointerType()) {
12719       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12720         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12721                                           /*isError*/false);
12722       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12723         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12724 
12725       if (LHSIsNull && !RHSIsNull)
12726         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12727       else
12728         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12729       return computeResultTy();
12730     }
12731 
12732     if (!IsOrdered && LHSType->isBlockPointerType() &&
12733         RHSType->isBlockCompatibleObjCPointerType(Context)) {
12734       LHS = ImpCastExprToType(LHS.get(), RHSType,
12735                               CK_BlockPointerToObjCPointerCast);
12736       return computeResultTy();
12737     } else if (!IsOrdered &&
12738                LHSType->isBlockCompatibleObjCPointerType(Context) &&
12739                RHSType->isBlockPointerType()) {
12740       RHS = ImpCastExprToType(RHS.get(), LHSType,
12741                               CK_BlockPointerToObjCPointerCast);
12742       return computeResultTy();
12743     }
12744   }
12745   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12746       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12747     unsigned DiagID = 0;
12748     bool isError = false;
12749     if (LangOpts.DebuggerSupport) {
12750       // Under a debugger, allow the comparison of pointers to integers,
12751       // since users tend to want to compare addresses.
12752     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12753                (RHSIsNull && RHSType->isIntegerType())) {
12754       if (IsOrdered) {
12755         isError = getLangOpts().CPlusPlus;
12756         DiagID =
12757           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12758                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12759       }
12760     } else if (getLangOpts().CPlusPlus) {
12761       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12762       isError = true;
12763     } else if (IsOrdered)
12764       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12765     else
12766       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12767 
12768     if (DiagID) {
12769       Diag(Loc, DiagID)
12770         << LHSType << RHSType << LHS.get()->getSourceRange()
12771         << RHS.get()->getSourceRange();
12772       if (isError)
12773         return QualType();
12774     }
12775 
12776     if (LHSType->isIntegerType())
12777       LHS = ImpCastExprToType(LHS.get(), RHSType,
12778                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12779     else
12780       RHS = ImpCastExprToType(RHS.get(), LHSType,
12781                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12782     return computeResultTy();
12783   }
12784 
12785   // Handle block pointers.
12786   if (!IsOrdered && RHSIsNull
12787       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12788     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12789     return computeResultTy();
12790   }
12791   if (!IsOrdered && LHSIsNull
12792       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12793     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12794     return computeResultTy();
12795   }
12796 
12797   if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12798     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12799       return computeResultTy();
12800     }
12801 
12802     if (LHSType->isQueueT() && RHSType->isQueueT()) {
12803       return computeResultTy();
12804     }
12805 
12806     if (LHSIsNull && RHSType->isQueueT()) {
12807       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12808       return computeResultTy();
12809     }
12810 
12811     if (LHSType->isQueueT() && RHSIsNull) {
12812       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12813       return computeResultTy();
12814     }
12815   }
12816 
12817   return InvalidOperands(Loc, LHS, RHS);
12818 }
12819 
12820 // Return a signed ext_vector_type that is of identical size and number of
12821 // elements. For floating point vectors, return an integer type of identical
12822 // size and number of elements. In the non ext_vector_type case, search from
12823 // the largest type to the smallest type to avoid cases where long long == long,
12824 // where long gets picked over long long.
12825 QualType Sema::GetSignedVectorType(QualType V) {
12826   const VectorType *VTy = V->castAs<VectorType>();
12827   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12828 
12829   if (isa<ExtVectorType>(VTy)) {
12830     if (VTy->isExtVectorBoolType())
12831       return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
12832     if (TypeSize == Context.getTypeSize(Context.CharTy))
12833       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12834     if (TypeSize == Context.getTypeSize(Context.ShortTy))
12835       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12836     if (TypeSize == Context.getTypeSize(Context.IntTy))
12837       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12838     if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12839       return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
12840     if (TypeSize == Context.getTypeSize(Context.LongTy))
12841       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12842     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12843            "Unhandled vector element size in vector compare");
12844     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12845   }
12846 
12847   if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12848     return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
12849                                  VectorType::GenericVector);
12850   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12851     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12852                                  VectorType::GenericVector);
12853   if (TypeSize == Context.getTypeSize(Context.LongTy))
12854     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12855                                  VectorType::GenericVector);
12856   if (TypeSize == Context.getTypeSize(Context.IntTy))
12857     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12858                                  VectorType::GenericVector);
12859   if (TypeSize == Context.getTypeSize(Context.ShortTy))
12860     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12861                                  VectorType::GenericVector);
12862   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12863          "Unhandled vector element size in vector compare");
12864   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12865                                VectorType::GenericVector);
12866 }
12867 
12868 QualType Sema::GetSignedSizelessVectorType(QualType V) {
12869   const BuiltinType *VTy = V->castAs<BuiltinType>();
12870   assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
12871 
12872   const QualType ETy = V->getSveEltType(Context);
12873   const auto TypeSize = Context.getTypeSize(ETy);
12874 
12875   const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12876   const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12877   return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12878 }
12879 
12880 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12881 /// operates on extended vector types.  Instead of producing an IntTy result,
12882 /// like a scalar comparison, a vector comparison produces a vector of integer
12883 /// types.
12884 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12885                                           SourceLocation Loc,
12886                                           BinaryOperatorKind Opc) {
12887   if (Opc == BO_Cmp) {
12888     Diag(Loc, diag::err_three_way_vector_comparison);
12889     return QualType();
12890   }
12891 
12892   // Check to make sure we're operating on vectors of the same type and width,
12893   // Allowing one side to be a scalar of element type.
12894   QualType vType =
12895       CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12896                           /*AllowBothBool*/ true,
12897                           /*AllowBoolConversions*/ getLangOpts().ZVector,
12898                           /*AllowBooleanOperation*/ true,
12899                           /*ReportInvalid*/ true);
12900   if (vType.isNull())
12901     return vType;
12902 
12903   QualType LHSType = LHS.get()->getType();
12904 
12905   // Determine the return type of a vector compare. By default clang will return
12906   // a scalar for all vector compares except vector bool and vector pixel.
12907   // With the gcc compiler we will always return a vector type and with the xl
12908   // compiler we will always return a scalar type. This switch allows choosing
12909   // which behavior is prefered.
12910   if (getLangOpts().AltiVec) {
12911     switch (getLangOpts().getAltivecSrcCompat()) {
12912     case LangOptions::AltivecSrcCompatKind::Mixed:
12913       // If AltiVec, the comparison results in a numeric type, i.e.
12914       // bool for C++, int for C
12915       if (vType->castAs<VectorType>()->getVectorKind() ==
12916           VectorType::AltiVecVector)
12917         return Context.getLogicalOperationType();
12918       else
12919         Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12920       break;
12921     case LangOptions::AltivecSrcCompatKind::GCC:
12922       // For GCC we always return the vector type.
12923       break;
12924     case LangOptions::AltivecSrcCompatKind::XL:
12925       return Context.getLogicalOperationType();
12926       break;
12927     }
12928   }
12929 
12930   // For non-floating point types, check for self-comparisons of the form
12931   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12932   // often indicate logic errors in the program.
12933   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12934 
12935   // Check for comparisons of floating point operands using != and ==.
12936   if (BinaryOperator::isEqualityOp(Opc) &&
12937       LHSType->hasFloatingRepresentation()) {
12938     assert(RHS.get()->getType()->hasFloatingRepresentation());
12939     CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12940   }
12941 
12942   // Return a signed type for the vector.
12943   return GetSignedVectorType(vType);
12944 }
12945 
12946 QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
12947                                                   ExprResult &RHS,
12948                                                   SourceLocation Loc,
12949                                                   BinaryOperatorKind Opc) {
12950   if (Opc == BO_Cmp) {
12951     Diag(Loc, diag::err_three_way_vector_comparison);
12952     return QualType();
12953   }
12954 
12955   // Check to make sure we're operating on vectors of the same type and width,
12956   // Allowing one side to be a scalar of element type.
12957   QualType vType = CheckSizelessVectorOperands(
12958       LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12959 
12960   if (vType.isNull())
12961     return vType;
12962 
12963   QualType LHSType = LHS.get()->getType();
12964 
12965   // For non-floating point types, check for self-comparisons of the form
12966   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12967   // often indicate logic errors in the program.
12968   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12969 
12970   // Check for comparisons of floating point operands using != and ==.
12971   if (BinaryOperator::isEqualityOp(Opc) &&
12972       LHSType->hasFloatingRepresentation()) {
12973     assert(RHS.get()->getType()->hasFloatingRepresentation());
12974     CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12975   }
12976 
12977   const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12978   const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12979 
12980   if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12981       RHSBuiltinTy->isSVEBool())
12982     return LHSType;
12983 
12984   // Return a signed type for the vector.
12985   return GetSignedSizelessVectorType(vType);
12986 }
12987 
12988 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12989                                     const ExprResult &XorRHS,
12990                                     const SourceLocation Loc) {
12991   // Do not diagnose macros.
12992   if (Loc.isMacroID())
12993     return;
12994 
12995   // Do not diagnose if both LHS and RHS are macros.
12996   if (XorLHS.get()->getExprLoc().isMacroID() &&
12997       XorRHS.get()->getExprLoc().isMacroID())
12998     return;
12999 
13000   bool Negative = false;
13001   bool ExplicitPlus = false;
13002   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13003   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13004 
13005   if (!LHSInt)
13006     return;
13007   if (!RHSInt) {
13008     // Check negative literals.
13009     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13010       UnaryOperatorKind Opc = UO->getOpcode();
13011       if (Opc != UO_Minus && Opc != UO_Plus)
13012         return;
13013       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13014       if (!RHSInt)
13015         return;
13016       Negative = (Opc == UO_Minus);
13017       ExplicitPlus = !Negative;
13018     } else {
13019       return;
13020     }
13021   }
13022 
13023   const llvm::APInt &LeftSideValue = LHSInt->getValue();
13024   llvm::APInt RightSideValue = RHSInt->getValue();
13025   if (LeftSideValue != 2 && LeftSideValue != 10)
13026     return;
13027 
13028   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13029     return;
13030 
13031   CharSourceRange ExprRange = CharSourceRange::getCharRange(
13032       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13033   llvm::StringRef ExprStr =
13034       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
13035 
13036   CharSourceRange XorRange =
13037       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
13038   llvm::StringRef XorStr =
13039       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
13040   // Do not diagnose if xor keyword/macro is used.
13041   if (XorStr == "xor")
13042     return;
13043 
13044   std::string LHSStr = std::string(Lexer::getSourceText(
13045       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13046       S.getSourceManager(), S.getLangOpts()));
13047   std::string RHSStr = std::string(Lexer::getSourceText(
13048       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13049       S.getSourceManager(), S.getLangOpts()));
13050 
13051   if (Negative) {
13052     RightSideValue = -RightSideValue;
13053     RHSStr = "-" + RHSStr;
13054   } else if (ExplicitPlus) {
13055     RHSStr = "+" + RHSStr;
13056   }
13057 
13058   StringRef LHSStrRef = LHSStr;
13059   StringRef RHSStrRef = RHSStr;
13060   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13061   // literals.
13062   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
13063       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
13064       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
13065       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
13066       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
13067       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
13068       LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13069     return;
13070 
13071   bool SuggestXor =
13072       S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13073   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13074   int64_t RightSideIntValue = RightSideValue.getSExtValue();
13075   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13076     std::string SuggestedExpr = "1 << " + RHSStr;
13077     bool Overflow = false;
13078     llvm::APInt One = (LeftSideValue - 1);
13079     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13080     if (Overflow) {
13081       if (RightSideIntValue < 64)
13082         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13083             << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13084             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13085       else if (RightSideIntValue == 64)
13086         S.Diag(Loc, diag::warn_xor_used_as_pow)
13087             << ExprStr << toString(XorValue, 10, true);
13088       else
13089         return;
13090     } else {
13091       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13092           << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13093           << toString(PowValue, 10, true)
13094           << FixItHint::CreateReplacement(
13095                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13096     }
13097 
13098     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13099         << ("0x2 ^ " + RHSStr) << SuggestXor;
13100   } else if (LeftSideValue == 10) {
13101     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13102     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13103         << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13104         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13105     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13106         << ("0xA ^ " + RHSStr) << SuggestXor;
13107   }
13108 }
13109 
13110 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13111                                           SourceLocation Loc) {
13112   // Ensure that either both operands are of the same vector type, or
13113   // one operand is of a vector type and the other is of its element type.
13114   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13115                                        /*AllowBothBool*/ true,
13116                                        /*AllowBoolConversions*/ false,
13117                                        /*AllowBooleanOperation*/ false,
13118                                        /*ReportInvalid*/ false);
13119   if (vType.isNull())
13120     return InvalidOperands(Loc, LHS, RHS);
13121   if (getLangOpts().OpenCL &&
13122       getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13123       vType->hasFloatingRepresentation())
13124     return InvalidOperands(Loc, LHS, RHS);
13125   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13126   //        usage of the logical operators && and || with vectors in C. This
13127   //        check could be notionally dropped.
13128   if (!getLangOpts().CPlusPlus &&
13129       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13130     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13131 
13132   return GetSignedVectorType(LHS.get()->getType());
13133 }
13134 
13135 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13136                                               SourceLocation Loc,
13137                                               bool IsCompAssign) {
13138   if (!IsCompAssign) {
13139     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13140     if (LHS.isInvalid())
13141       return QualType();
13142   }
13143   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13144   if (RHS.isInvalid())
13145     return QualType();
13146 
13147   // For conversion purposes, we ignore any qualifiers.
13148   // For example, "const float" and "float" are equivalent.
13149   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13150   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13151 
13152   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13153   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13154   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13155 
13156   if (Context.hasSameType(LHSType, RHSType))
13157     return LHSType;
13158 
13159   // Type conversion may change LHS/RHS. Keep copies to the original results, in
13160   // case we have to return InvalidOperands.
13161   ExprResult OriginalLHS = LHS;
13162   ExprResult OriginalRHS = RHS;
13163   if (LHSMatType && !RHSMatType) {
13164     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13165     if (!RHS.isInvalid())
13166       return LHSType;
13167 
13168     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13169   }
13170 
13171   if (!LHSMatType && RHSMatType) {
13172     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13173     if (!LHS.isInvalid())
13174       return RHSType;
13175     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13176   }
13177 
13178   return InvalidOperands(Loc, LHS, RHS);
13179 }
13180 
13181 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13182                                            SourceLocation Loc,
13183                                            bool IsCompAssign) {
13184   if (!IsCompAssign) {
13185     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13186     if (LHS.isInvalid())
13187       return QualType();
13188   }
13189   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13190   if (RHS.isInvalid())
13191     return QualType();
13192 
13193   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13194   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13195   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13196 
13197   if (LHSMatType && RHSMatType) {
13198     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13199       return InvalidOperands(Loc, LHS, RHS);
13200 
13201     if (!Context.hasSameType(LHSMatType->getElementType(),
13202                              RHSMatType->getElementType()))
13203       return InvalidOperands(Loc, LHS, RHS);
13204 
13205     return Context.getConstantMatrixType(LHSMatType->getElementType(),
13206                                          LHSMatType->getNumRows(),
13207                                          RHSMatType->getNumColumns());
13208   }
13209   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13210 }
13211 
13212 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13213   switch (Opc) {
13214   default:
13215     return false;
13216   case BO_And:
13217   case BO_AndAssign:
13218   case BO_Or:
13219   case BO_OrAssign:
13220   case BO_Xor:
13221   case BO_XorAssign:
13222     return true;
13223   }
13224 }
13225 
13226 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13227                                            SourceLocation Loc,
13228                                            BinaryOperatorKind Opc) {
13229   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13230 
13231   bool IsCompAssign =
13232       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13233 
13234   bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13235 
13236   if (LHS.get()->getType()->isVectorType() ||
13237       RHS.get()->getType()->isVectorType()) {
13238     if (LHS.get()->getType()->hasIntegerRepresentation() &&
13239         RHS.get()->getType()->hasIntegerRepresentation())
13240       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13241                                  /*AllowBothBool*/ true,
13242                                  /*AllowBoolConversions*/ getLangOpts().ZVector,
13243                                  /*AllowBooleanOperation*/ LegalBoolVecOperator,
13244                                  /*ReportInvalid*/ true);
13245     return InvalidOperands(Loc, LHS, RHS);
13246   }
13247 
13248   if (LHS.get()->getType()->isVLSTBuiltinType() ||
13249       RHS.get()->getType()->isVLSTBuiltinType()) {
13250     if (LHS.get()->getType()->hasIntegerRepresentation() &&
13251         RHS.get()->getType()->hasIntegerRepresentation())
13252       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13253                                          ACK_BitwiseOp);
13254     return InvalidOperands(Loc, LHS, RHS);
13255   }
13256 
13257   if (LHS.get()->getType()->isVLSTBuiltinType() ||
13258       RHS.get()->getType()->isVLSTBuiltinType()) {
13259     if (LHS.get()->getType()->hasIntegerRepresentation() &&
13260         RHS.get()->getType()->hasIntegerRepresentation())
13261       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13262                                          ACK_BitwiseOp);
13263     return InvalidOperands(Loc, LHS, RHS);
13264   }
13265 
13266   if (Opc == BO_And)
13267     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13268 
13269   if (LHS.get()->getType()->hasFloatingRepresentation() ||
13270       RHS.get()->getType()->hasFloatingRepresentation())
13271     return InvalidOperands(Loc, LHS, RHS);
13272 
13273   ExprResult LHSResult = LHS, RHSResult = RHS;
13274   QualType compType = UsualArithmeticConversions(
13275       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13276   if (LHSResult.isInvalid() || RHSResult.isInvalid())
13277     return QualType();
13278   LHS = LHSResult.get();
13279   RHS = RHSResult.get();
13280 
13281   if (Opc == BO_Xor)
13282     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13283 
13284   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13285     return compType;
13286   return InvalidOperands(Loc, LHS, RHS);
13287 }
13288 
13289 // C99 6.5.[13,14]
13290 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13291                                            SourceLocation Loc,
13292                                            BinaryOperatorKind Opc) {
13293   // Check vector operands differently.
13294   if (LHS.get()->getType()->isVectorType() ||
13295       RHS.get()->getType()->isVectorType())
13296     return CheckVectorLogicalOperands(LHS, RHS, Loc);
13297 
13298   bool EnumConstantInBoolContext = false;
13299   for (const ExprResult &HS : {LHS, RHS}) {
13300     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13301       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13302       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13303         EnumConstantInBoolContext = true;
13304     }
13305   }
13306 
13307   if (EnumConstantInBoolContext)
13308     Diag(Loc, diag::warn_enum_constant_in_bool_context);
13309 
13310   // Diagnose cases where the user write a logical and/or but probably meant a
13311   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
13312   // is a constant.
13313   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13314       !LHS.get()->getType()->isBooleanType() &&
13315       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13316       // Don't warn in macros or template instantiations.
13317       !Loc.isMacroID() && !inTemplateInstantiation()) {
13318     // If the RHS can be constant folded, and if it constant folds to something
13319     // that isn't 0 or 1 (which indicate a potential logical operation that
13320     // happened to fold to true/false) then warn.
13321     // Parens on the RHS are ignored.
13322     Expr::EvalResult EVResult;
13323     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13324       llvm::APSInt Result = EVResult.Val.getInt();
13325       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
13326            !RHS.get()->getExprLoc().isMacroID()) ||
13327           (Result != 0 && Result != 1)) {
13328         Diag(Loc, diag::warn_logical_instead_of_bitwise)
13329             << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13330         // Suggest replacing the logical operator with the bitwise version
13331         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13332             << (Opc == BO_LAnd ? "&" : "|")
13333             << FixItHint::CreateReplacement(
13334                    SourceRange(Loc, getLocForEndOfToken(Loc)),
13335                    Opc == BO_LAnd ? "&" : "|");
13336         if (Opc == BO_LAnd)
13337           // Suggest replacing "Foo() && kNonZero" with "Foo()"
13338           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13339               << FixItHint::CreateRemoval(
13340                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
13341                                  RHS.get()->getEndLoc()));
13342       }
13343     }
13344   }
13345 
13346   if (!Context.getLangOpts().CPlusPlus) {
13347     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13348     // not operate on the built-in scalar and vector float types.
13349     if (Context.getLangOpts().OpenCL &&
13350         Context.getLangOpts().OpenCLVersion < 120) {
13351       if (LHS.get()->getType()->isFloatingType() ||
13352           RHS.get()->getType()->isFloatingType())
13353         return InvalidOperands(Loc, LHS, RHS);
13354     }
13355 
13356     LHS = UsualUnaryConversions(LHS.get());
13357     if (LHS.isInvalid())
13358       return QualType();
13359 
13360     RHS = UsualUnaryConversions(RHS.get());
13361     if (RHS.isInvalid())
13362       return QualType();
13363 
13364     if (!LHS.get()->getType()->isScalarType() ||
13365         !RHS.get()->getType()->isScalarType())
13366       return InvalidOperands(Loc, LHS, RHS);
13367 
13368     return Context.IntTy;
13369   }
13370 
13371   // The following is safe because we only use this method for
13372   // non-overloadable operands.
13373 
13374   // C++ [expr.log.and]p1
13375   // C++ [expr.log.or]p1
13376   // The operands are both contextually converted to type bool.
13377   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
13378   if (LHSRes.isInvalid())
13379     return InvalidOperands(Loc, LHS, RHS);
13380   LHS = LHSRes;
13381 
13382   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
13383   if (RHSRes.isInvalid())
13384     return InvalidOperands(Loc, LHS, RHS);
13385   RHS = RHSRes;
13386 
13387   // C++ [expr.log.and]p2
13388   // C++ [expr.log.or]p2
13389   // The result is a bool.
13390   return Context.BoolTy;
13391 }
13392 
13393 static bool IsReadonlyMessage(Expr *E, Sema &S) {
13394   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13395   if (!ME) return false;
13396   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13397   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13398       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13399   if (!Base) return false;
13400   return Base->getMethodDecl() != nullptr;
13401 }
13402 
13403 /// Is the given expression (which must be 'const') a reference to a
13404 /// variable which was originally non-const, but which has become
13405 /// 'const' due to being captured within a block?
13406 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13407 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13408   assert(E->isLValue() && E->getType().isConstQualified());
13409   E = E->IgnoreParens();
13410 
13411   // Must be a reference to a declaration from an enclosing scope.
13412   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13413   if (!DRE) return NCCK_None;
13414   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13415 
13416   // The declaration must be a variable which is not declared 'const'.
13417   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13418   if (!var) return NCCK_None;
13419   if (var->getType().isConstQualified()) return NCCK_None;
13420   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
13421 
13422   // Decide whether the first capture was for a block or a lambda.
13423   DeclContext *DC = S.CurContext, *Prev = nullptr;
13424   // Decide whether the first capture was for a block or a lambda.
13425   while (DC) {
13426     // For init-capture, it is possible that the variable belongs to the
13427     // template pattern of the current context.
13428     if (auto *FD = dyn_cast<FunctionDecl>(DC))
13429       if (var->isInitCapture() &&
13430           FD->getTemplateInstantiationPattern() == var->getDeclContext())
13431         break;
13432     if (DC == var->getDeclContext())
13433       break;
13434     Prev = DC;
13435     DC = DC->getParent();
13436   }
13437   // Unless we have an init-capture, we've gone one step too far.
13438   if (!var->isInitCapture())
13439     DC = Prev;
13440   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13441 }
13442 
13443 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13444   Ty = Ty.getNonReferenceType();
13445   if (IsDereference && Ty->isPointerType())
13446     Ty = Ty->getPointeeType();
13447   return !Ty.isConstQualified();
13448 }
13449 
13450 // Update err_typecheck_assign_const and note_typecheck_assign_const
13451 // when this enum is changed.
13452 enum {
13453   ConstFunction,
13454   ConstVariable,
13455   ConstMember,
13456   ConstMethod,
13457   NestedConstMember,
13458   ConstUnknown,  // Keep as last element
13459 };
13460 
13461 /// Emit the "read-only variable not assignable" error and print notes to give
13462 /// more information about why the variable is not assignable, such as pointing
13463 /// to the declaration of a const variable, showing that a method is const, or
13464 /// that the function is returning a const reference.
13465 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13466                                     SourceLocation Loc) {
13467   SourceRange ExprRange = E->getSourceRange();
13468 
13469   // Only emit one error on the first const found.  All other consts will emit
13470   // a note to the error.
13471   bool DiagnosticEmitted = false;
13472 
13473   // Track if the current expression is the result of a dereference, and if the
13474   // next checked expression is the result of a dereference.
13475   bool IsDereference = false;
13476   bool NextIsDereference = false;
13477 
13478   // Loop to process MemberExpr chains.
13479   while (true) {
13480     IsDereference = NextIsDereference;
13481 
13482     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13483     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13484       NextIsDereference = ME->isArrow();
13485       const ValueDecl *VD = ME->getMemberDecl();
13486       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13487         // Mutable fields can be modified even if the class is const.
13488         if (Field->isMutable()) {
13489           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13490           break;
13491         }
13492 
13493         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13494           if (!DiagnosticEmitted) {
13495             S.Diag(Loc, diag::err_typecheck_assign_const)
13496                 << ExprRange << ConstMember << false /*static*/ << Field
13497                 << Field->getType();
13498             DiagnosticEmitted = true;
13499           }
13500           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13501               << ConstMember << false /*static*/ << Field << Field->getType()
13502               << Field->getSourceRange();
13503         }
13504         E = ME->getBase();
13505         continue;
13506       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13507         if (VDecl->getType().isConstQualified()) {
13508           if (!DiagnosticEmitted) {
13509             S.Diag(Loc, diag::err_typecheck_assign_const)
13510                 << ExprRange << ConstMember << true /*static*/ << VDecl
13511                 << VDecl->getType();
13512             DiagnosticEmitted = true;
13513           }
13514           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13515               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13516               << VDecl->getSourceRange();
13517         }
13518         // Static fields do not inherit constness from parents.
13519         break;
13520       }
13521       break; // End MemberExpr
13522     } else if (const ArraySubscriptExpr *ASE =
13523                    dyn_cast<ArraySubscriptExpr>(E)) {
13524       E = ASE->getBase()->IgnoreParenImpCasts();
13525       continue;
13526     } else if (const ExtVectorElementExpr *EVE =
13527                    dyn_cast<ExtVectorElementExpr>(E)) {
13528       E = EVE->getBase()->IgnoreParenImpCasts();
13529       continue;
13530     }
13531     break;
13532   }
13533 
13534   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13535     // Function calls
13536     const FunctionDecl *FD = CE->getDirectCallee();
13537     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13538       if (!DiagnosticEmitted) {
13539         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13540                                                       << ConstFunction << FD;
13541         DiagnosticEmitted = true;
13542       }
13543       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13544              diag::note_typecheck_assign_const)
13545           << ConstFunction << FD << FD->getReturnType()
13546           << FD->getReturnTypeSourceRange();
13547     }
13548   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13549     // Point to variable declaration.
13550     if (const ValueDecl *VD = DRE->getDecl()) {
13551       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13552         if (!DiagnosticEmitted) {
13553           S.Diag(Loc, diag::err_typecheck_assign_const)
13554               << ExprRange << ConstVariable << VD << VD->getType();
13555           DiagnosticEmitted = true;
13556         }
13557         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13558             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13559       }
13560     }
13561   } else if (isa<CXXThisExpr>(E)) {
13562     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13563       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13564         if (MD->isConst()) {
13565           if (!DiagnosticEmitted) {
13566             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13567                                                           << ConstMethod << MD;
13568             DiagnosticEmitted = true;
13569           }
13570           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13571               << ConstMethod << MD << MD->getSourceRange();
13572         }
13573       }
13574     }
13575   }
13576 
13577   if (DiagnosticEmitted)
13578     return;
13579 
13580   // Can't determine a more specific message, so display the generic error.
13581   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13582 }
13583 
13584 enum OriginalExprKind {
13585   OEK_Variable,
13586   OEK_Member,
13587   OEK_LValue
13588 };
13589 
13590 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13591                                          const RecordType *Ty,
13592                                          SourceLocation Loc, SourceRange Range,
13593                                          OriginalExprKind OEK,
13594                                          bool &DiagnosticEmitted) {
13595   std::vector<const RecordType *> RecordTypeList;
13596   RecordTypeList.push_back(Ty);
13597   unsigned NextToCheckIndex = 0;
13598   // We walk the record hierarchy breadth-first to ensure that we print
13599   // diagnostics in field nesting order.
13600   while (RecordTypeList.size() > NextToCheckIndex) {
13601     bool IsNested = NextToCheckIndex > 0;
13602     for (const FieldDecl *Field :
13603          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13604       // First, check every field for constness.
13605       QualType FieldTy = Field->getType();
13606       if (FieldTy.isConstQualified()) {
13607         if (!DiagnosticEmitted) {
13608           S.Diag(Loc, diag::err_typecheck_assign_const)
13609               << Range << NestedConstMember << OEK << VD
13610               << IsNested << Field;
13611           DiagnosticEmitted = true;
13612         }
13613         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13614             << NestedConstMember << IsNested << Field
13615             << FieldTy << Field->getSourceRange();
13616       }
13617 
13618       // Then we append it to the list to check next in order.
13619       FieldTy = FieldTy.getCanonicalType();
13620       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13621         if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13622           RecordTypeList.push_back(FieldRecTy);
13623       }
13624     }
13625     ++NextToCheckIndex;
13626   }
13627 }
13628 
13629 /// Emit an error for the case where a record we are trying to assign to has a
13630 /// const-qualified field somewhere in its hierarchy.
13631 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13632                                          SourceLocation Loc) {
13633   QualType Ty = E->getType();
13634   assert(Ty->isRecordType() && "lvalue was not record?");
13635   SourceRange Range = E->getSourceRange();
13636   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13637   bool DiagEmitted = false;
13638 
13639   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13640     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13641             Range, OEK_Member, DiagEmitted);
13642   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13643     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13644             Range, OEK_Variable, DiagEmitted);
13645   else
13646     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13647             Range, OEK_LValue, DiagEmitted);
13648   if (!DiagEmitted)
13649     DiagnoseConstAssignment(S, E, Loc);
13650 }
13651 
13652 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
13653 /// emit an error and return true.  If so, return false.
13654 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
13655   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13656 
13657   S.CheckShadowingDeclModification(E, Loc);
13658 
13659   SourceLocation OrigLoc = Loc;
13660   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
13661                                                               &Loc);
13662   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13663     IsLV = Expr::MLV_InvalidMessageExpression;
13664   if (IsLV == Expr::MLV_Valid)
13665     return false;
13666 
13667   unsigned DiagID = 0;
13668   bool NeedType = false;
13669   switch (IsLV) { // C99 6.5.16p2
13670   case Expr::MLV_ConstQualified:
13671     // Use a specialized diagnostic when we're assigning to an object
13672     // from an enclosing function or block.
13673     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
13674       if (NCCK == NCCK_Block)
13675         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13676       else
13677         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13678       break;
13679     }
13680 
13681     // In ARC, use some specialized diagnostics for occasions where we
13682     // infer 'const'.  These are always pseudo-strong variables.
13683     if (S.getLangOpts().ObjCAutoRefCount) {
13684       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13685       if (declRef && isa<VarDecl>(declRef->getDecl())) {
13686         VarDecl *var = cast<VarDecl>(declRef->getDecl());
13687 
13688         // Use the normal diagnostic if it's pseudo-__strong but the
13689         // user actually wrote 'const'.
13690         if (var->isARCPseudoStrong() &&
13691             (!var->getTypeSourceInfo() ||
13692              !var->getTypeSourceInfo()->getType().isConstQualified())) {
13693           // There are three pseudo-strong cases:
13694           //  - self
13695           ObjCMethodDecl *method = S.getCurMethodDecl();
13696           if (method && var == method->getSelfDecl()) {
13697             DiagID = method->isClassMethod()
13698               ? diag::err_typecheck_arc_assign_self_class_method
13699               : diag::err_typecheck_arc_assign_self;
13700 
13701           //  - Objective-C externally_retained attribute.
13702           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13703                      isa<ParmVarDecl>(var)) {
13704             DiagID = diag::err_typecheck_arc_assign_externally_retained;
13705 
13706           //  - fast enumeration variables
13707           } else {
13708             DiagID = diag::err_typecheck_arr_assign_enumeration;
13709           }
13710 
13711           SourceRange Assign;
13712           if (Loc != OrigLoc)
13713             Assign = SourceRange(OrigLoc, OrigLoc);
13714           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13715           // We need to preserve the AST regardless, so migration tool
13716           // can do its job.
13717           return false;
13718         }
13719       }
13720     }
13721 
13722     // If none of the special cases above are triggered, then this is a
13723     // simple const assignment.
13724     if (DiagID == 0) {
13725       DiagnoseConstAssignment(S, E, Loc);
13726       return true;
13727     }
13728 
13729     break;
13730   case Expr::MLV_ConstAddrSpace:
13731     DiagnoseConstAssignment(S, E, Loc);
13732     return true;
13733   case Expr::MLV_ConstQualifiedField:
13734     DiagnoseRecursiveConstFields(S, E, Loc);
13735     return true;
13736   case Expr::MLV_ArrayType:
13737   case Expr::MLV_ArrayTemporary:
13738     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13739     NeedType = true;
13740     break;
13741   case Expr::MLV_NotObjectType:
13742     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13743     NeedType = true;
13744     break;
13745   case Expr::MLV_LValueCast:
13746     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13747     break;
13748   case Expr::MLV_Valid:
13749     llvm_unreachable("did not take early return for MLV_Valid");
13750   case Expr::MLV_InvalidExpression:
13751   case Expr::MLV_MemberFunction:
13752   case Expr::MLV_ClassTemporary:
13753     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13754     break;
13755   case Expr::MLV_IncompleteType:
13756   case Expr::MLV_IncompleteVoidType:
13757     return S.RequireCompleteType(Loc, E->getType(),
13758              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13759   case Expr::MLV_DuplicateVectorComponents:
13760     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13761     break;
13762   case Expr::MLV_NoSetterProperty:
13763     llvm_unreachable("readonly properties should be processed differently");
13764   case Expr::MLV_InvalidMessageExpression:
13765     DiagID = diag::err_readonly_message_assignment;
13766     break;
13767   case Expr::MLV_SubObjCPropertySetting:
13768     DiagID = diag::err_no_subobject_property_setting;
13769     break;
13770   }
13771 
13772   SourceRange Assign;
13773   if (Loc != OrigLoc)
13774     Assign = SourceRange(OrigLoc, OrigLoc);
13775   if (NeedType)
13776     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13777   else
13778     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13779   return true;
13780 }
13781 
13782 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13783                                          SourceLocation Loc,
13784                                          Sema &Sema) {
13785   if (Sema.inTemplateInstantiation())
13786     return;
13787   if (Sema.isUnevaluatedContext())
13788     return;
13789   if (Loc.isInvalid() || Loc.isMacroID())
13790     return;
13791   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13792     return;
13793 
13794   // C / C++ fields
13795   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13796   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13797   if (ML && MR) {
13798     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13799       return;
13800     const ValueDecl *LHSDecl =
13801         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13802     const ValueDecl *RHSDecl =
13803         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13804     if (LHSDecl != RHSDecl)
13805       return;
13806     if (LHSDecl->getType().isVolatileQualified())
13807       return;
13808     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13809       if (RefTy->getPointeeType().isVolatileQualified())
13810         return;
13811 
13812     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13813   }
13814 
13815   // Objective-C instance variables
13816   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13817   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13818   if (OL && OR && OL->getDecl() == OR->getDecl()) {
13819     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13820     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13821     if (RL && RR && RL->getDecl() == RR->getDecl())
13822       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13823   }
13824 }
13825 
13826 // C99 6.5.16.1
13827 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13828                                        SourceLocation Loc,
13829                                        QualType CompoundType) {
13830   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13831 
13832   // Verify that LHS is a modifiable lvalue, and emit error if not.
13833   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13834     return QualType();
13835 
13836   QualType LHSType = LHSExpr->getType();
13837   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13838                                              CompoundType;
13839   // OpenCL v1.2 s6.1.1.1 p2:
13840   // The half data type can only be used to declare a pointer to a buffer that
13841   // contains half values
13842   if (getLangOpts().OpenCL &&
13843       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13844       LHSType->isHalfType()) {
13845     Diag(Loc, diag::err_opencl_half_load_store) << 1
13846         << LHSType.getUnqualifiedType();
13847     return QualType();
13848   }
13849 
13850   AssignConvertType ConvTy;
13851   if (CompoundType.isNull()) {
13852     Expr *RHSCheck = RHS.get();
13853 
13854     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13855 
13856     QualType LHSTy(LHSType);
13857     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13858     if (RHS.isInvalid())
13859       return QualType();
13860     // Special case of NSObject attributes on c-style pointer types.
13861     if (ConvTy == IncompatiblePointer &&
13862         ((Context.isObjCNSObjectType(LHSType) &&
13863           RHSType->isObjCObjectPointerType()) ||
13864          (Context.isObjCNSObjectType(RHSType) &&
13865           LHSType->isObjCObjectPointerType())))
13866       ConvTy = Compatible;
13867 
13868     if (ConvTy == Compatible &&
13869         LHSType->isObjCObjectType())
13870         Diag(Loc, diag::err_objc_object_assignment)
13871           << LHSType;
13872 
13873     // If the RHS is a unary plus or minus, check to see if they = and + are
13874     // right next to each other.  If so, the user may have typo'd "x =+ 4"
13875     // instead of "x += 4".
13876     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13877       RHSCheck = ICE->getSubExpr();
13878     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13879       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13880           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13881           // Only if the two operators are exactly adjacent.
13882           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13883           // And there is a space or other character before the subexpr of the
13884           // unary +/-.  We don't want to warn on "x=-1".
13885           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13886           UO->getSubExpr()->getBeginLoc().isFileID()) {
13887         Diag(Loc, diag::warn_not_compound_assign)
13888           << (UO->getOpcode() == UO_Plus ? "+" : "-")
13889           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13890       }
13891     }
13892 
13893     if (ConvTy == Compatible) {
13894       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13895         // Warn about retain cycles where a block captures the LHS, but
13896         // not if the LHS is a simple variable into which the block is
13897         // being stored...unless that variable can be captured by reference!
13898         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13899         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13900         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13901           checkRetainCycles(LHSExpr, RHS.get());
13902       }
13903 
13904       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13905           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13906         // It is safe to assign a weak reference into a strong variable.
13907         // Although this code can still have problems:
13908         //   id x = self.weakProp;
13909         //   id y = self.weakProp;
13910         // we do not warn to warn spuriously when 'x' and 'y' are on separate
13911         // paths through the function. This should be revisited if
13912         // -Wrepeated-use-of-weak is made flow-sensitive.
13913         // For ObjCWeak only, we do not warn if the assign is to a non-weak
13914         // variable, which will be valid for the current autorelease scope.
13915         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13916                              RHS.get()->getBeginLoc()))
13917           getCurFunction()->markSafeWeakUse(RHS.get());
13918 
13919       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13920         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13921       }
13922     }
13923   } else {
13924     // Compound assignment "x += y"
13925     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13926   }
13927 
13928   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13929                                RHS.get(), AA_Assigning))
13930     return QualType();
13931 
13932   CheckForNullPointerDereference(*this, LHSExpr);
13933 
13934   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13935     if (CompoundType.isNull()) {
13936       // C++2a [expr.ass]p5:
13937       //   A simple-assignment whose left operand is of a volatile-qualified
13938       //   type is deprecated unless the assignment is either a discarded-value
13939       //   expression or an unevaluated operand
13940       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13941     } else {
13942       // C++2a [expr.ass]p6:
13943       //   [Compound-assignment] expressions are deprecated if E1 has
13944       //   volatile-qualified type
13945       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13946     }
13947   }
13948 
13949   // C11 6.5.16p3: The type of an assignment expression is the type of the
13950   // left operand would have after lvalue conversion.
13951   // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13952   // qualified type, the value has the unqualified version of the type of the
13953   // lvalue; additionally, if the lvalue has atomic type, the value has the
13954   // non-atomic version of the type of the lvalue.
13955   // C++ 5.17p1: the type of the assignment expression is that of its left
13956   // operand.
13957   return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13958 }
13959 
13960 // Only ignore explicit casts to void.
13961 static bool IgnoreCommaOperand(const Expr *E) {
13962   E = E->IgnoreParens();
13963 
13964   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13965     if (CE->getCastKind() == CK_ToVoid) {
13966       return true;
13967     }
13968 
13969     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13970     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13971         CE->getSubExpr()->getType()->isDependentType()) {
13972       return true;
13973     }
13974   }
13975 
13976   return false;
13977 }
13978 
13979 // Look for instances where it is likely the comma operator is confused with
13980 // another operator.  There is an explicit list of acceptable expressions for
13981 // the left hand side of the comma operator, otherwise emit a warning.
13982 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13983   // No warnings in macros
13984   if (Loc.isMacroID())
13985     return;
13986 
13987   // Don't warn in template instantiations.
13988   if (inTemplateInstantiation())
13989     return;
13990 
13991   // Scope isn't fine-grained enough to explicitly list the specific cases, so
13992   // instead, skip more than needed, then call back into here with the
13993   // CommaVisitor in SemaStmt.cpp.
13994   // The listed locations are the initialization and increment portions
13995   // of a for loop.  The additional checks are on the condition of
13996   // if statements, do/while loops, and for loops.
13997   // Differences in scope flags for C89 mode requires the extra logic.
13998   const unsigned ForIncrementFlags =
13999       getLangOpts().C99 || getLangOpts().CPlusPlus
14000           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
14001           : Scope::ContinueScope | Scope::BreakScope;
14002   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14003   const unsigned ScopeFlags = getCurScope()->getFlags();
14004   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14005       (ScopeFlags & ForInitFlags) == ForInitFlags)
14006     return;
14007 
14008   // If there are multiple comma operators used together, get the RHS of the
14009   // of the comma operator as the LHS.
14010   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14011     if (BO->getOpcode() != BO_Comma)
14012       break;
14013     LHS = BO->getRHS();
14014   }
14015 
14016   // Only allow some expressions on LHS to not warn.
14017   if (IgnoreCommaOperand(LHS))
14018     return;
14019 
14020   Diag(Loc, diag::warn_comma_operator);
14021   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14022       << LHS->getSourceRange()
14023       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
14024                                     LangOpts.CPlusPlus ? "static_cast<void>("
14025                                                        : "(void)(")
14026       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14027                                     ")");
14028 }
14029 
14030 // C99 6.5.17
14031 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14032                                    SourceLocation Loc) {
14033   LHS = S.CheckPlaceholderExpr(LHS.get());
14034   RHS = S.CheckPlaceholderExpr(RHS.get());
14035   if (LHS.isInvalid() || RHS.isInvalid())
14036     return QualType();
14037 
14038   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14039   // operands, but not unary promotions.
14040   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14041 
14042   // So we treat the LHS as a ignored value, and in C++ we allow the
14043   // containing site to determine what should be done with the RHS.
14044   LHS = S.IgnoredValueConversions(LHS.get());
14045   if (LHS.isInvalid())
14046     return QualType();
14047 
14048   S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14049 
14050   if (!S.getLangOpts().CPlusPlus) {
14051     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
14052     if (RHS.isInvalid())
14053       return QualType();
14054     if (!RHS.get()->getType()->isVoidType())
14055       S.RequireCompleteType(Loc, RHS.get()->getType(),
14056                             diag::err_incomplete_type);
14057   }
14058 
14059   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14060     S.DiagnoseCommaOperator(LHS.get(), Loc);
14061 
14062   return RHS.get()->getType();
14063 }
14064 
14065 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14066 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14067 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14068                                                ExprValueKind &VK,
14069                                                ExprObjectKind &OK,
14070                                                SourceLocation OpLoc,
14071                                                bool IsInc, bool IsPrefix) {
14072   if (Op->isTypeDependent())
14073     return S.Context.DependentTy;
14074 
14075   QualType ResType = Op->getType();
14076   // Atomic types can be used for increment / decrement where the non-atomic
14077   // versions can, so ignore the _Atomic() specifier for the purpose of
14078   // checking.
14079   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14080     ResType = ResAtomicType->getValueType();
14081 
14082   assert(!ResType.isNull() && "no type for increment/decrement expression");
14083 
14084   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14085     // Decrement of bool is not allowed.
14086     if (!IsInc) {
14087       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14088       return QualType();
14089     }
14090     // Increment of bool sets it to true, but is deprecated.
14091     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14092                                               : diag::warn_increment_bool)
14093       << Op->getSourceRange();
14094   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14095     // Error on enum increments and decrements in C++ mode
14096     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14097     return QualType();
14098   } else if (ResType->isRealType()) {
14099     // OK!
14100   } else if (ResType->isPointerType()) {
14101     // C99 6.5.2.4p2, 6.5.6p2
14102     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14103       return QualType();
14104   } else if (ResType->isObjCObjectPointerType()) {
14105     // On modern runtimes, ObjC pointer arithmetic is forbidden.
14106     // Otherwise, we just need a complete type.
14107     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14108         checkArithmeticOnObjCPointer(S, OpLoc, Op))
14109       return QualType();
14110   } else if (ResType->isAnyComplexType()) {
14111     // C99 does not support ++/-- on complex types, we allow as an extension.
14112     S.Diag(OpLoc, diag::ext_integer_increment_complex)
14113       << ResType << Op->getSourceRange();
14114   } else if (ResType->isPlaceholderType()) {
14115     ExprResult PR = S.CheckPlaceholderExpr(Op);
14116     if (PR.isInvalid()) return QualType();
14117     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14118                                           IsInc, IsPrefix);
14119   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14120     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14121   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14122              (ResType->castAs<VectorType>()->getVectorKind() !=
14123               VectorType::AltiVecBool)) {
14124     // The z vector extensions allow ++ and -- for non-bool vectors.
14125   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
14126             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14127     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14128   } else {
14129     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14130       << ResType << int(IsInc) << Op->getSourceRange();
14131     return QualType();
14132   }
14133   // At this point, we know we have a real, complex or pointer type.
14134   // Now make sure the operand is a modifiable lvalue.
14135   if (CheckForModifiableLvalue(Op, OpLoc, S))
14136     return QualType();
14137   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14138     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14139     //   An operand with volatile-qualified type is deprecated
14140     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14141         << IsInc << ResType;
14142   }
14143   // In C++, a prefix increment is the same type as the operand. Otherwise
14144   // (in C or with postfix), the increment is the unqualified type of the
14145   // operand.
14146   if (IsPrefix && S.getLangOpts().CPlusPlus) {
14147     VK = VK_LValue;
14148     OK = Op->getObjectKind();
14149     return ResType;
14150   } else {
14151     VK = VK_PRValue;
14152     return ResType.getUnqualifiedType();
14153   }
14154 }
14155 
14156 
14157 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14158 /// This routine allows us to typecheck complex/recursive expressions
14159 /// where the declaration is needed for type checking. We only need to
14160 /// handle cases when the expression references a function designator
14161 /// or is an lvalue. Here are some examples:
14162 ///  - &(x) => x
14163 ///  - &*****f => f for f a function designator.
14164 ///  - &s.xx => s
14165 ///  - &s.zz[1].yy -> s, if zz is an array
14166 ///  - *(x + 1) -> x, if x is an array
14167 ///  - &"123"[2] -> 0
14168 ///  - & __real__ x -> x
14169 ///
14170 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14171 /// members.
14172 static ValueDecl *getPrimaryDecl(Expr *E) {
14173   switch (E->getStmtClass()) {
14174   case Stmt::DeclRefExprClass:
14175     return cast<DeclRefExpr>(E)->getDecl();
14176   case Stmt::MemberExprClass:
14177     // If this is an arrow operator, the address is an offset from
14178     // the base's value, so the object the base refers to is
14179     // irrelevant.
14180     if (cast<MemberExpr>(E)->isArrow())
14181       return nullptr;
14182     // Otherwise, the expression refers to a part of the base
14183     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14184   case Stmt::ArraySubscriptExprClass: {
14185     // FIXME: This code shouldn't be necessary!  We should catch the implicit
14186     // promotion of register arrays earlier.
14187     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14188     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14189       if (ICE->getSubExpr()->getType()->isArrayType())
14190         return getPrimaryDecl(ICE->getSubExpr());
14191     }
14192     return nullptr;
14193   }
14194   case Stmt::UnaryOperatorClass: {
14195     UnaryOperator *UO = cast<UnaryOperator>(E);
14196 
14197     switch(UO->getOpcode()) {
14198     case UO_Real:
14199     case UO_Imag:
14200     case UO_Extension:
14201       return getPrimaryDecl(UO->getSubExpr());
14202     default:
14203       return nullptr;
14204     }
14205   }
14206   case Stmt::ParenExprClass:
14207     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14208   case Stmt::ImplicitCastExprClass:
14209     // If the result of an implicit cast is an l-value, we care about
14210     // the sub-expression; otherwise, the result here doesn't matter.
14211     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14212   case Stmt::CXXUuidofExprClass:
14213     return cast<CXXUuidofExpr>(E)->getGuidDecl();
14214   default:
14215     return nullptr;
14216   }
14217 }
14218 
14219 namespace {
14220 enum {
14221   AO_Bit_Field = 0,
14222   AO_Vector_Element = 1,
14223   AO_Property_Expansion = 2,
14224   AO_Register_Variable = 3,
14225   AO_Matrix_Element = 4,
14226   AO_No_Error = 5
14227 };
14228 }
14229 /// Diagnose invalid operand for address of operations.
14230 ///
14231 /// \param Type The type of operand which cannot have its address taken.
14232 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14233                                          Expr *E, unsigned Type) {
14234   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14235 }
14236 
14237 /// CheckAddressOfOperand - The operand of & must be either a function
14238 /// designator or an lvalue designating an object. If it is an lvalue, the
14239 /// object cannot be declared with storage class register or be a bit field.
14240 /// Note: The usual conversions are *not* applied to the operand of the &
14241 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14242 /// In C++, the operand might be an overloaded function name, in which case
14243 /// we allow the '&' but retain the overloaded-function type.
14244 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14245   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14246     if (PTy->getKind() == BuiltinType::Overload) {
14247       Expr *E = OrigOp.get()->IgnoreParens();
14248       if (!isa<OverloadExpr>(E)) {
14249         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14250         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14251           << OrigOp.get()->getSourceRange();
14252         return QualType();
14253       }
14254 
14255       OverloadExpr *Ovl = cast<OverloadExpr>(E);
14256       if (isa<UnresolvedMemberExpr>(Ovl))
14257         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
14258           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14259             << OrigOp.get()->getSourceRange();
14260           return QualType();
14261         }
14262 
14263       return Context.OverloadTy;
14264     }
14265 
14266     if (PTy->getKind() == BuiltinType::UnknownAny)
14267       return Context.UnknownAnyTy;
14268 
14269     if (PTy->getKind() == BuiltinType::BoundMember) {
14270       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14271         << OrigOp.get()->getSourceRange();
14272       return QualType();
14273     }
14274 
14275     OrigOp = CheckPlaceholderExpr(OrigOp.get());
14276     if (OrigOp.isInvalid()) return QualType();
14277   }
14278 
14279   if (OrigOp.get()->isTypeDependent())
14280     return Context.DependentTy;
14281 
14282   assert(!OrigOp.get()->hasPlaceholderType());
14283 
14284   // Make sure to ignore parentheses in subsequent checks
14285   Expr *op = OrigOp.get()->IgnoreParens();
14286 
14287   // In OpenCL captures for blocks called as lambda functions
14288   // are located in the private address space. Blocks used in
14289   // enqueue_kernel can be located in a different address space
14290   // depending on a vendor implementation. Thus preventing
14291   // taking an address of the capture to avoid invalid AS casts.
14292   if (LangOpts.OpenCL) {
14293     auto* VarRef = dyn_cast<DeclRefExpr>(op);
14294     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14295       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14296       return QualType();
14297     }
14298   }
14299 
14300   if (getLangOpts().C99) {
14301     // Implement C99-only parts of addressof rules.
14302     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14303       if (uOp->getOpcode() == UO_Deref)
14304         // Per C99 6.5.3.2, the address of a deref always returns a valid result
14305         // (assuming the deref expression is valid).
14306         return uOp->getSubExpr()->getType();
14307     }
14308     // Technically, there should be a check for array subscript
14309     // expressions here, but the result of one is always an lvalue anyway.
14310   }
14311   ValueDecl *dcl = getPrimaryDecl(op);
14312 
14313   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14314     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14315                                            op->getBeginLoc()))
14316       return QualType();
14317 
14318   Expr::LValueClassification lval = op->ClassifyLValue(Context);
14319   unsigned AddressOfError = AO_No_Error;
14320 
14321   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14322     bool sfinae = (bool)isSFINAEContext();
14323     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14324                                   : diag::ext_typecheck_addrof_temporary)
14325       << op->getType() << op->getSourceRange();
14326     if (sfinae)
14327       return QualType();
14328     // Materialize the temporary as an lvalue so that we can take its address.
14329     OrigOp = op =
14330         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14331   } else if (isa<ObjCSelectorExpr>(op)) {
14332     return Context.getPointerType(op->getType());
14333   } else if (lval == Expr::LV_MemberFunction) {
14334     // If it's an instance method, make a member pointer.
14335     // The expression must have exactly the form &A::foo.
14336 
14337     // If the underlying expression isn't a decl ref, give up.
14338     if (!isa<DeclRefExpr>(op)) {
14339       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14340         << OrigOp.get()->getSourceRange();
14341       return QualType();
14342     }
14343     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14344     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14345 
14346     // The id-expression was parenthesized.
14347     if (OrigOp.get() != DRE) {
14348       Diag(OpLoc, diag::err_parens_pointer_member_function)
14349         << OrigOp.get()->getSourceRange();
14350 
14351     // The method was named without a qualifier.
14352     } else if (!DRE->getQualifier()) {
14353       if (MD->getParent()->getName().empty())
14354         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14355           << op->getSourceRange();
14356       else {
14357         SmallString<32> Str;
14358         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14359         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14360           << op->getSourceRange()
14361           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
14362       }
14363     }
14364 
14365     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14366     if (isa<CXXDestructorDecl>(MD))
14367       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
14368 
14369     QualType MPTy = Context.getMemberPointerType(
14370         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
14371     // Under the MS ABI, lock down the inheritance model now.
14372     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14373       (void)isCompleteType(OpLoc, MPTy);
14374     return MPTy;
14375   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14376     // C99 6.5.3.2p1
14377     // The operand must be either an l-value or a function designator
14378     if (!op->getType()->isFunctionType()) {
14379       // Use a special diagnostic for loads from property references.
14380       if (isa<PseudoObjectExpr>(op)) {
14381         AddressOfError = AO_Property_Expansion;
14382       } else {
14383         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14384           << op->getType() << op->getSourceRange();
14385         return QualType();
14386       }
14387     }
14388   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14389     // The operand cannot be a bit-field
14390     AddressOfError = AO_Bit_Field;
14391   } else if (op->getObjectKind() == OK_VectorComponent) {
14392     // The operand cannot be an element of a vector
14393     AddressOfError = AO_Vector_Element;
14394   } else if (op->getObjectKind() == OK_MatrixComponent) {
14395     // The operand cannot be an element of a matrix.
14396     AddressOfError = AO_Matrix_Element;
14397   } else if (dcl) { // C99 6.5.3.2p1
14398     // We have an lvalue with a decl. Make sure the decl is not declared
14399     // with the register storage-class specifier.
14400     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14401       // in C++ it is not error to take address of a register
14402       // variable (c++03 7.1.1P3)
14403       if (vd->getStorageClass() == SC_Register &&
14404           !getLangOpts().CPlusPlus) {
14405         AddressOfError = AO_Register_Variable;
14406       }
14407     } else if (isa<MSPropertyDecl>(dcl)) {
14408       AddressOfError = AO_Property_Expansion;
14409     } else if (isa<FunctionTemplateDecl>(dcl)) {
14410       return Context.OverloadTy;
14411     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14412       // Okay: we can take the address of a field.
14413       // Could be a pointer to member, though, if there is an explicit
14414       // scope qualifier for the class.
14415       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14416         DeclContext *Ctx = dcl->getDeclContext();
14417         if (Ctx && Ctx->isRecord()) {
14418           if (dcl->getType()->isReferenceType()) {
14419             Diag(OpLoc,
14420                  diag::err_cannot_form_pointer_to_member_of_reference_type)
14421               << dcl->getDeclName() << dcl->getType();
14422             return QualType();
14423           }
14424 
14425           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14426             Ctx = Ctx->getParent();
14427 
14428           QualType MPTy = Context.getMemberPointerType(
14429               op->getType(),
14430               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14431           // Under the MS ABI, lock down the inheritance model now.
14432           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14433             (void)isCompleteType(OpLoc, MPTy);
14434           return MPTy;
14435         }
14436       }
14437     } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
14438                     MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))
14439       llvm_unreachable("Unknown/unexpected decl type");
14440   }
14441 
14442   if (AddressOfError != AO_No_Error) {
14443     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14444     return QualType();
14445   }
14446 
14447   if (lval == Expr::LV_IncompleteVoidType) {
14448     // Taking the address of a void variable is technically illegal, but we
14449     // allow it in cases which are otherwise valid.
14450     // Example: "extern void x; void* y = &x;".
14451     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14452   }
14453 
14454   // If the operand has type "type", the result has type "pointer to type".
14455   if (op->getType()->isObjCObjectType())
14456     return Context.getObjCObjectPointerType(op->getType());
14457 
14458   CheckAddressOfPackedMember(op);
14459 
14460   return Context.getPointerType(op->getType());
14461 }
14462 
14463 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14464   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14465   if (!DRE)
14466     return;
14467   const Decl *D = DRE->getDecl();
14468   if (!D)
14469     return;
14470   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14471   if (!Param)
14472     return;
14473   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14474     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14475       return;
14476   if (FunctionScopeInfo *FD = S.getCurFunction())
14477     FD->ModifiedNonNullParams.insert(Param);
14478 }
14479 
14480 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14481 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14482                                         SourceLocation OpLoc) {
14483   if (Op->isTypeDependent())
14484     return S.Context.DependentTy;
14485 
14486   ExprResult ConvResult = S.UsualUnaryConversions(Op);
14487   if (ConvResult.isInvalid())
14488     return QualType();
14489   Op = ConvResult.get();
14490   QualType OpTy = Op->getType();
14491   QualType Result;
14492 
14493   if (isa<CXXReinterpretCastExpr>(Op)) {
14494     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14495     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14496                                      Op->getSourceRange());
14497   }
14498 
14499   if (const PointerType *PT = OpTy->getAs<PointerType>())
14500   {
14501     Result = PT->getPointeeType();
14502   }
14503   else if (const ObjCObjectPointerType *OPT =
14504              OpTy->getAs<ObjCObjectPointerType>())
14505     Result = OPT->getPointeeType();
14506   else {
14507     ExprResult PR = S.CheckPlaceholderExpr(Op);
14508     if (PR.isInvalid()) return QualType();
14509     if (PR.get() != Op)
14510       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14511   }
14512 
14513   if (Result.isNull()) {
14514     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14515       << OpTy << Op->getSourceRange();
14516     return QualType();
14517   }
14518 
14519   // Note that per both C89 and C99, indirection is always legal, even if Result
14520   // is an incomplete type or void.  It would be possible to warn about
14521   // dereferencing a void pointer, but it's completely well-defined, and such a
14522   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
14523   // for pointers to 'void' but is fine for any other pointer type:
14524   //
14525   // C++ [expr.unary.op]p1:
14526   //   [...] the expression to which [the unary * operator] is applied shall
14527   //   be a pointer to an object type, or a pointer to a function type
14528   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
14529     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14530       << OpTy << Op->getSourceRange();
14531 
14532   // Dereferences are usually l-values...
14533   VK = VK_LValue;
14534 
14535   // ...except that certain expressions are never l-values in C.
14536   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14537     VK = VK_PRValue;
14538 
14539   return Result;
14540 }
14541 
14542 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14543   BinaryOperatorKind Opc;
14544   switch (Kind) {
14545   default: llvm_unreachable("Unknown binop!");
14546   case tok::periodstar:           Opc = BO_PtrMemD; break;
14547   case tok::arrowstar:            Opc = BO_PtrMemI; break;
14548   case tok::star:                 Opc = BO_Mul; break;
14549   case tok::slash:                Opc = BO_Div; break;
14550   case tok::percent:              Opc = BO_Rem; break;
14551   case tok::plus:                 Opc = BO_Add; break;
14552   case tok::minus:                Opc = BO_Sub; break;
14553   case tok::lessless:             Opc = BO_Shl; break;
14554   case tok::greatergreater:       Opc = BO_Shr; break;
14555   case tok::lessequal:            Opc = BO_LE; break;
14556   case tok::less:                 Opc = BO_LT; break;
14557   case tok::greaterequal:         Opc = BO_GE; break;
14558   case tok::greater:              Opc = BO_GT; break;
14559   case tok::exclaimequal:         Opc = BO_NE; break;
14560   case tok::equalequal:           Opc = BO_EQ; break;
14561   case tok::spaceship:            Opc = BO_Cmp; break;
14562   case tok::amp:                  Opc = BO_And; break;
14563   case tok::caret:                Opc = BO_Xor; break;
14564   case tok::pipe:                 Opc = BO_Or; break;
14565   case tok::ampamp:               Opc = BO_LAnd; break;
14566   case tok::pipepipe:             Opc = BO_LOr; break;
14567   case tok::equal:                Opc = BO_Assign; break;
14568   case tok::starequal:            Opc = BO_MulAssign; break;
14569   case tok::slashequal:           Opc = BO_DivAssign; break;
14570   case tok::percentequal:         Opc = BO_RemAssign; break;
14571   case tok::plusequal:            Opc = BO_AddAssign; break;
14572   case tok::minusequal:           Opc = BO_SubAssign; break;
14573   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
14574   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
14575   case tok::ampequal:             Opc = BO_AndAssign; break;
14576   case tok::caretequal:           Opc = BO_XorAssign; break;
14577   case tok::pipeequal:            Opc = BO_OrAssign; break;
14578   case tok::comma:                Opc = BO_Comma; break;
14579   }
14580   return Opc;
14581 }
14582 
14583 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
14584   tok::TokenKind Kind) {
14585   UnaryOperatorKind Opc;
14586   switch (Kind) {
14587   default: llvm_unreachable("Unknown unary op!");
14588   case tok::plusplus:     Opc = UO_PreInc; break;
14589   case tok::minusminus:   Opc = UO_PreDec; break;
14590   case tok::amp:          Opc = UO_AddrOf; break;
14591   case tok::star:         Opc = UO_Deref; break;
14592   case tok::plus:         Opc = UO_Plus; break;
14593   case tok::minus:        Opc = UO_Minus; break;
14594   case tok::tilde:        Opc = UO_Not; break;
14595   case tok::exclaim:      Opc = UO_LNot; break;
14596   case tok::kw___real:    Opc = UO_Real; break;
14597   case tok::kw___imag:    Opc = UO_Imag; break;
14598   case tok::kw___extension__: Opc = UO_Extension; break;
14599   }
14600   return Opc;
14601 }
14602 
14603 const FieldDecl *
14604 Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
14605   // Explore the case for adding 'this->' to the LHS of a self assignment, very
14606   // common for setters.
14607   // struct A {
14608   // int X;
14609   // -void setX(int X) { X = X; }
14610   // +void setX(int X) { this->X = X; }
14611   // };
14612 
14613   // Only consider parameters for self assignment fixes.
14614   if (!isa<ParmVarDecl>(SelfAssigned))
14615     return nullptr;
14616   const auto *Method =
14617       dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14618   if (!Method)
14619     return nullptr;
14620 
14621   const CXXRecordDecl *Parent = Method->getParent();
14622   // In theory this is fixable if the lambda explicitly captures this, but
14623   // that's added complexity that's rarely going to be used.
14624   if (Parent->isLambda())
14625     return nullptr;
14626 
14627   // FIXME: Use an actual Lookup operation instead of just traversing fields
14628   // in order to get base class fields.
14629   auto Field =
14630       llvm::find_if(Parent->fields(),
14631                     [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14632                       return F->getDeclName() == Name;
14633                     });
14634   return (Field != Parent->field_end()) ? *Field : nullptr;
14635 }
14636 
14637 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14638 /// This warning suppressed in the event of macro expansions.
14639 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14640                                    SourceLocation OpLoc, bool IsBuiltin) {
14641   if (S.inTemplateInstantiation())
14642     return;
14643   if (S.isUnevaluatedContext())
14644     return;
14645   if (OpLoc.isInvalid() || OpLoc.isMacroID())
14646     return;
14647   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14648   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14649   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14650   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14651   if (!LHSDeclRef || !RHSDeclRef ||
14652       LHSDeclRef->getLocation().isMacroID() ||
14653       RHSDeclRef->getLocation().isMacroID())
14654     return;
14655   const ValueDecl *LHSDecl =
14656     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14657   const ValueDecl *RHSDecl =
14658     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14659   if (LHSDecl != RHSDecl)
14660     return;
14661   if (LHSDecl->getType().isVolatileQualified())
14662     return;
14663   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14664     if (RefTy->getPointeeType().isVolatileQualified())
14665       return;
14666 
14667   auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14668                                       : diag::warn_self_assignment_overloaded)
14669               << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14670               << RHSExpr->getSourceRange();
14671   if (const FieldDecl *SelfAssignField =
14672           S.getSelfAssignmentClassMemberCandidate(RHSDecl))
14673     Diag << 1 << SelfAssignField
14674          << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14675   else
14676     Diag << 0;
14677 }
14678 
14679 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
14680 /// is usually indicative of introspection within the Objective-C pointer.
14681 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
14682                                           SourceLocation OpLoc) {
14683   if (!S.getLangOpts().ObjC)
14684     return;
14685 
14686   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14687   const Expr *LHS = L.get();
14688   const Expr *RHS = R.get();
14689 
14690   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14691     ObjCPointerExpr = LHS;
14692     OtherExpr = RHS;
14693   }
14694   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14695     ObjCPointerExpr = RHS;
14696     OtherExpr = LHS;
14697   }
14698 
14699   // This warning is deliberately made very specific to reduce false
14700   // positives with logic that uses '&' for hashing.  This logic mainly
14701   // looks for code trying to introspect into tagged pointers, which
14702   // code should generally never do.
14703   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14704     unsigned Diag = diag::warn_objc_pointer_masking;
14705     // Determine if we are introspecting the result of performSelectorXXX.
14706     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14707     // Special case messages to -performSelector and friends, which
14708     // can return non-pointer values boxed in a pointer value.
14709     // Some clients may wish to silence warnings in this subcase.
14710     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14711       Selector S = ME->getSelector();
14712       StringRef SelArg0 = S.getNameForSlot(0);
14713       if (SelArg0.startswith("performSelector"))
14714         Diag = diag::warn_objc_pointer_masking_performSelector;
14715     }
14716 
14717     S.Diag(OpLoc, Diag)
14718       << ObjCPointerExpr->getSourceRange();
14719   }
14720 }
14721 
14722 static NamedDecl *getDeclFromExpr(Expr *E) {
14723   if (!E)
14724     return nullptr;
14725   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14726     return DRE->getDecl();
14727   if (auto *ME = dyn_cast<MemberExpr>(E))
14728     return ME->getMemberDecl();
14729   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14730     return IRE->getDecl();
14731   return nullptr;
14732 }
14733 
14734 // This helper function promotes a binary operator's operands (which are of a
14735 // half vector type) to a vector of floats and then truncates the result to
14736 // a vector of either half or short.
14737 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
14738                                       BinaryOperatorKind Opc, QualType ResultTy,
14739                                       ExprValueKind VK, ExprObjectKind OK,
14740                                       bool IsCompAssign, SourceLocation OpLoc,
14741                                       FPOptionsOverride FPFeatures) {
14742   auto &Context = S.getASTContext();
14743   assert((isVector(ResultTy, Context.HalfTy) ||
14744           isVector(ResultTy, Context.ShortTy)) &&
14745          "Result must be a vector of half or short");
14746   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14747          isVector(RHS.get()->getType(), Context.HalfTy) &&
14748          "both operands expected to be a half vector");
14749 
14750   RHS = convertVector(RHS.get(), Context.FloatTy, S);
14751   QualType BinOpResTy = RHS.get()->getType();
14752 
14753   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14754   // change BinOpResTy to a vector of ints.
14755   if (isVector(ResultTy, Context.ShortTy))
14756     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14757 
14758   if (IsCompAssign)
14759     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14760                                           ResultTy, VK, OK, OpLoc, FPFeatures,
14761                                           BinOpResTy, BinOpResTy);
14762 
14763   LHS = convertVector(LHS.get(), Context.FloatTy, S);
14764   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14765                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
14766   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14767 }
14768 
14769 static std::pair<ExprResult, ExprResult>
14770 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14771                            Expr *RHSExpr) {
14772   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14773   if (!S.Context.isDependenceAllowed()) {
14774     // C cannot handle TypoExpr nodes on either side of a binop because it
14775     // doesn't handle dependent types properly, so make sure any TypoExprs have
14776     // been dealt with before checking the operands.
14777     LHS = S.CorrectDelayedTyposInExpr(LHS);
14778     RHS = S.CorrectDelayedTyposInExpr(
14779         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14780         [Opc, LHS](Expr *E) {
14781           if (Opc != BO_Assign)
14782             return ExprResult(E);
14783           // Avoid correcting the RHS to the same Expr as the LHS.
14784           Decl *D = getDeclFromExpr(E);
14785           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14786         });
14787   }
14788   return std::make_pair(LHS, RHS);
14789 }
14790 
14791 /// Returns true if conversion between vectors of halfs and vectors of floats
14792 /// is needed.
14793 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14794                                      Expr *E0, Expr *E1 = nullptr) {
14795   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14796       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14797     return false;
14798 
14799   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14800     QualType Ty = E->IgnoreImplicit()->getType();
14801 
14802     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14803     // to vectors of floats. Although the element type of the vectors is __fp16,
14804     // the vectors shouldn't be treated as storage-only types. See the
14805     // discussion here: https://reviews.llvm.org/rG825235c140e7
14806     if (const VectorType *VT = Ty->getAs<VectorType>()) {
14807       if (VT->getVectorKind() == VectorType::NeonVector)
14808         return false;
14809       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14810     }
14811     return false;
14812   };
14813 
14814   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14815 }
14816 
14817 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
14818 /// operator @p Opc at location @c TokLoc. This routine only supports
14819 /// built-in operations; ActOnBinOp handles overloaded operators.
14820 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14821                                     BinaryOperatorKind Opc,
14822                                     Expr *LHSExpr, Expr *RHSExpr) {
14823   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14824     // The syntax only allows initializer lists on the RHS of assignment,
14825     // so we don't need to worry about accepting invalid code for
14826     // non-assignment operators.
14827     // C++11 5.17p9:
14828     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14829     //   of x = {} is x = T().
14830     InitializationKind Kind = InitializationKind::CreateDirectList(
14831         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14832     InitializedEntity Entity =
14833         InitializedEntity::InitializeTemporary(LHSExpr->getType());
14834     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14835     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14836     if (Init.isInvalid())
14837       return Init;
14838     RHSExpr = Init.get();
14839   }
14840 
14841   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14842   QualType ResultTy;     // Result type of the binary operator.
14843   // The following two variables are used for compound assignment operators
14844   QualType CompLHSTy;    // Type of LHS after promotions for computation
14845   QualType CompResultTy; // Type of computation result
14846   ExprValueKind VK = VK_PRValue;
14847   ExprObjectKind OK = OK_Ordinary;
14848   bool ConvertHalfVec = false;
14849 
14850   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14851   if (!LHS.isUsable() || !RHS.isUsable())
14852     return ExprError();
14853 
14854   if (getLangOpts().OpenCL) {
14855     QualType LHSTy = LHSExpr->getType();
14856     QualType RHSTy = RHSExpr->getType();
14857     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14858     // the ATOMIC_VAR_INIT macro.
14859     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14860       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14861       if (BO_Assign == Opc)
14862         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14863       else
14864         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14865       return ExprError();
14866     }
14867 
14868     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14869     // only with a builtin functions and therefore should be disallowed here.
14870     if (LHSTy->isImageType() || RHSTy->isImageType() ||
14871         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14872         LHSTy->isPipeType() || RHSTy->isPipeType() ||
14873         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14874       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14875       return ExprError();
14876     }
14877   }
14878 
14879   checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14880   checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14881 
14882   switch (Opc) {
14883   case BO_Assign:
14884     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14885     if (getLangOpts().CPlusPlus &&
14886         LHS.get()->getObjectKind() != OK_ObjCProperty) {
14887       VK = LHS.get()->getValueKind();
14888       OK = LHS.get()->getObjectKind();
14889     }
14890     if (!ResultTy.isNull()) {
14891       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14892       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14893 
14894       // Avoid copying a block to the heap if the block is assigned to a local
14895       // auto variable that is declared in the same scope as the block. This
14896       // optimization is unsafe if the local variable is declared in an outer
14897       // scope. For example:
14898       //
14899       // BlockTy b;
14900       // {
14901       //   b = ^{...};
14902       // }
14903       // // It is unsafe to invoke the block here if it wasn't copied to the
14904       // // heap.
14905       // b();
14906 
14907       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14908         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14909           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14910             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14911               BE->getBlockDecl()->setCanAvoidCopyToHeap();
14912 
14913       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14914         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14915                               NTCUC_Assignment, NTCUK_Copy);
14916     }
14917     RecordModifiableNonNullParam(*this, LHS.get());
14918     break;
14919   case BO_PtrMemD:
14920   case BO_PtrMemI:
14921     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14922                                             Opc == BO_PtrMemI);
14923     break;
14924   case BO_Mul:
14925   case BO_Div:
14926     ConvertHalfVec = true;
14927     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14928                                            Opc == BO_Div);
14929     break;
14930   case BO_Rem:
14931     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14932     break;
14933   case BO_Add:
14934     ConvertHalfVec = true;
14935     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14936     break;
14937   case BO_Sub:
14938     ConvertHalfVec = true;
14939     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14940     break;
14941   case BO_Shl:
14942   case BO_Shr:
14943     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14944     break;
14945   case BO_LE:
14946   case BO_LT:
14947   case BO_GE:
14948   case BO_GT:
14949     ConvertHalfVec = true;
14950     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14951     break;
14952   case BO_EQ:
14953   case BO_NE:
14954     ConvertHalfVec = true;
14955     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14956     break;
14957   case BO_Cmp:
14958     ConvertHalfVec = true;
14959     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14960     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14961     break;
14962   case BO_And:
14963     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14964     LLVM_FALLTHROUGH;
14965   case BO_Xor:
14966   case BO_Or:
14967     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14968     break;
14969   case BO_LAnd:
14970   case BO_LOr:
14971     ConvertHalfVec = true;
14972     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14973     break;
14974   case BO_MulAssign:
14975   case BO_DivAssign:
14976     ConvertHalfVec = true;
14977     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14978                                                Opc == BO_DivAssign);
14979     CompLHSTy = CompResultTy;
14980     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14981       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14982     break;
14983   case BO_RemAssign:
14984     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14985     CompLHSTy = CompResultTy;
14986     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14987       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14988     break;
14989   case BO_AddAssign:
14990     ConvertHalfVec = true;
14991     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14992     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14993       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14994     break;
14995   case BO_SubAssign:
14996     ConvertHalfVec = true;
14997     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14998     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14999       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
15000     break;
15001   case BO_ShlAssign:
15002   case BO_ShrAssign:
15003     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15004     CompLHSTy = CompResultTy;
15005     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15006       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
15007     break;
15008   case BO_AndAssign:
15009   case BO_OrAssign: // fallthrough
15010     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15011     LLVM_FALLTHROUGH;
15012   case BO_XorAssign:
15013     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15014     CompLHSTy = CompResultTy;
15015     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15016       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
15017     break;
15018   case BO_Comma:
15019     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15020     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15021       VK = RHS.get()->getValueKind();
15022       OK = RHS.get()->getObjectKind();
15023     }
15024     break;
15025   }
15026   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15027     return ExprError();
15028 
15029   // Some of the binary operations require promoting operands of half vector to
15030   // float vectors and truncating the result back to half vector. For now, we do
15031   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15032   // arm64).
15033   assert(
15034       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15035                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
15036       "both sides are half vectors or neither sides are");
15037   ConvertHalfVec =
15038       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15039 
15040   // Check for array bounds violations for both sides of the BinaryOperator
15041   CheckArrayAccess(LHS.get());
15042   CheckArrayAccess(RHS.get());
15043 
15044   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15045     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15046                                                  &Context.Idents.get("object_setClass"),
15047                                                  SourceLocation(), LookupOrdinaryName);
15048     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15049       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15050       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15051           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
15052                                         "object_setClass(")
15053           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15054                                           ",")
15055           << FixItHint::CreateInsertion(RHSLocEnd, ")");
15056     }
15057     else
15058       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15059   }
15060   else if (const ObjCIvarRefExpr *OIRE =
15061            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15062     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15063 
15064   // Opc is not a compound assignment if CompResultTy is null.
15065   if (CompResultTy.isNull()) {
15066     if (ConvertHalfVec)
15067       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15068                                  OpLoc, CurFPFeatureOverrides());
15069     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15070                                   VK, OK, OpLoc, CurFPFeatureOverrides());
15071   }
15072 
15073   // Handle compound assignments.
15074   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15075       OK_ObjCProperty) {
15076     VK = VK_LValue;
15077     OK = LHS.get()->getObjectKind();
15078   }
15079 
15080   // The LHS is not converted to the result type for fixed-point compound
15081   // assignment as the common type is computed on demand. Reset the CompLHSTy
15082   // to the LHS type we would have gotten after unary conversions.
15083   if (CompResultTy->isFixedPointType())
15084     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15085 
15086   if (ConvertHalfVec)
15087     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15088                                OpLoc, CurFPFeatureOverrides());
15089 
15090   return CompoundAssignOperator::Create(
15091       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15092       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15093 }
15094 
15095 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15096 /// operators are mixed in a way that suggests that the programmer forgot that
15097 /// comparison operators have higher precedence. The most typical example of
15098 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15099 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15100                                       SourceLocation OpLoc, Expr *LHSExpr,
15101                                       Expr *RHSExpr) {
15102   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15103   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15104 
15105   // Check that one of the sides is a comparison operator and the other isn't.
15106   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15107   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15108   if (isLeftComp == isRightComp)
15109     return;
15110 
15111   // Bitwise operations are sometimes used as eager logical ops.
15112   // Don't diagnose this.
15113   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15114   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15115   if (isLeftBitwise || isRightBitwise)
15116     return;
15117 
15118   SourceRange DiagRange = isLeftComp
15119                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15120                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
15121   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15122   SourceRange ParensRange =
15123       isLeftComp
15124           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15125           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15126 
15127   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15128     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15129   SuggestParentheses(Self, OpLoc,
15130     Self.PDiag(diag::note_precedence_silence) << OpStr,
15131     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15132   SuggestParentheses(Self, OpLoc,
15133     Self.PDiag(diag::note_precedence_bitwise_first)
15134       << BinaryOperator::getOpcodeStr(Opc),
15135     ParensRange);
15136 }
15137 
15138 /// It accepts a '&&' expr that is inside a '||' one.
15139 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15140 /// in parentheses.
15141 static void
15142 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15143                                        BinaryOperator *Bop) {
15144   assert(Bop->getOpcode() == BO_LAnd);
15145   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15146       << Bop->getSourceRange() << OpLoc;
15147   SuggestParentheses(Self, Bop->getOperatorLoc(),
15148     Self.PDiag(diag::note_precedence_silence)
15149       << Bop->getOpcodeStr(),
15150     Bop->getSourceRange());
15151 }
15152 
15153 /// Returns true if the given expression can be evaluated as a constant
15154 /// 'true'.
15155 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
15156   bool Res;
15157   return !E->isValueDependent() &&
15158          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
15159 }
15160 
15161 /// Returns true if the given expression can be evaluated as a constant
15162 /// 'false'.
15163 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
15164   bool Res;
15165   return !E->isValueDependent() &&
15166          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
15167 }
15168 
15169 /// Look for '&&' in the left hand of a '||' expr.
15170 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15171                                              Expr *LHSExpr, Expr *RHSExpr) {
15172   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15173     if (Bop->getOpcode() == BO_LAnd) {
15174       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
15175       if (EvaluatesAsFalse(S, RHSExpr))
15176         return;
15177       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
15178       if (!EvaluatesAsTrue(S, Bop->getLHS()))
15179         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15180     } else if (Bop->getOpcode() == BO_LOr) {
15181       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15182         // If it's "a || b && 1 || c" we didn't warn earlier for
15183         // "a || b && 1", but warn now.
15184         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
15185           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15186       }
15187     }
15188   }
15189 }
15190 
15191 /// Look for '&&' in the right hand of a '||' expr.
15192 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15193                                              Expr *LHSExpr, Expr *RHSExpr) {
15194   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15195     if (Bop->getOpcode() == BO_LAnd) {
15196       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
15197       if (EvaluatesAsFalse(S, LHSExpr))
15198         return;
15199       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
15200       if (!EvaluatesAsTrue(S, Bop->getRHS()))
15201         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15202     }
15203   }
15204 }
15205 
15206 /// Look for bitwise op in the left or right hand of a bitwise op with
15207 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
15208 /// the '&' expression in parentheses.
15209 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15210                                          SourceLocation OpLoc, Expr *SubExpr) {
15211   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15212     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15213       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15214         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15215         << Bop->getSourceRange() << OpLoc;
15216       SuggestParentheses(S, Bop->getOperatorLoc(),
15217         S.PDiag(diag::note_precedence_silence)
15218           << Bop->getOpcodeStr(),
15219         Bop->getSourceRange());
15220     }
15221   }
15222 }
15223 
15224 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15225                                     Expr *SubExpr, StringRef Shift) {
15226   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15227     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15228       StringRef Op = Bop->getOpcodeStr();
15229       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15230           << Bop->getSourceRange() << OpLoc << Shift << Op;
15231       SuggestParentheses(S, Bop->getOperatorLoc(),
15232           S.PDiag(diag::note_precedence_silence) << Op,
15233           Bop->getSourceRange());
15234     }
15235   }
15236 }
15237 
15238 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15239                                  Expr *LHSExpr, Expr *RHSExpr) {
15240   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15241   if (!OCE)
15242     return;
15243 
15244   FunctionDecl *FD = OCE->getDirectCallee();
15245   if (!FD || !FD->isOverloadedOperator())
15246     return;
15247 
15248   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15249   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15250     return;
15251 
15252   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15253       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15254       << (Kind == OO_LessLess);
15255   SuggestParentheses(S, OCE->getOperatorLoc(),
15256                      S.PDiag(diag::note_precedence_silence)
15257                          << (Kind == OO_LessLess ? "<<" : ">>"),
15258                      OCE->getSourceRange());
15259   SuggestParentheses(
15260       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15261       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15262 }
15263 
15264 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15265 /// precedence.
15266 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15267                                     SourceLocation OpLoc, Expr *LHSExpr,
15268                                     Expr *RHSExpr){
15269   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15270   if (BinaryOperator::isBitwiseOp(Opc))
15271     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15272 
15273   // Diagnose "arg1 & arg2 | arg3"
15274   if ((Opc == BO_Or || Opc == BO_Xor) &&
15275       !OpLoc.isMacroID()/* Don't warn in macros. */) {
15276     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15277     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15278   }
15279 
15280   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15281   // We don't warn for 'assert(a || b && "bad")' since this is safe.
15282   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15283     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15284     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15285   }
15286 
15287   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15288       || Opc == BO_Shr) {
15289     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15290     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15291     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15292   }
15293 
15294   // Warn on overloaded shift operators and comparisons, such as:
15295   // cout << 5 == 4;
15296   if (BinaryOperator::isComparisonOp(Opc))
15297     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15298 }
15299 
15300 // Binary Operators.  'Tok' is the token for the operator.
15301 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15302                             tok::TokenKind Kind,
15303                             Expr *LHSExpr, Expr *RHSExpr) {
15304   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15305   assert(LHSExpr && "ActOnBinOp(): missing left expression");
15306   assert(RHSExpr && "ActOnBinOp(): missing right expression");
15307 
15308   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15309   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15310 
15311   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15312 }
15313 
15314 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15315                        UnresolvedSetImpl &Functions) {
15316   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15317   if (OverOp != OO_None && OverOp != OO_Equal)
15318     LookupOverloadedOperatorName(OverOp, S, Functions);
15319 
15320   // In C++20 onwards, we may have a second operator to look up.
15321   if (getLangOpts().CPlusPlus20) {
15322     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
15323       LookupOverloadedOperatorName(ExtraOp, S, Functions);
15324   }
15325 }
15326 
15327 /// Build an overloaded binary operator expression in the given scope.
15328 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15329                                        BinaryOperatorKind Opc,
15330                                        Expr *LHS, Expr *RHS) {
15331   switch (Opc) {
15332   case BO_Assign:
15333   case BO_DivAssign:
15334   case BO_RemAssign:
15335   case BO_SubAssign:
15336   case BO_AndAssign:
15337   case BO_OrAssign:
15338   case BO_XorAssign:
15339     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15340     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15341     break;
15342   default:
15343     break;
15344   }
15345 
15346   // Find all of the overloaded operators visible from this point.
15347   UnresolvedSet<16> Functions;
15348   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15349 
15350   // Build the (potentially-overloaded, potentially-dependent)
15351   // binary operation.
15352   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15353 }
15354 
15355 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15356                             BinaryOperatorKind Opc,
15357                             Expr *LHSExpr, Expr *RHSExpr) {
15358   ExprResult LHS, RHS;
15359   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15360   if (!LHS.isUsable() || !RHS.isUsable())
15361     return ExprError();
15362   LHSExpr = LHS.get();
15363   RHSExpr = RHS.get();
15364 
15365   // We want to end up calling one of checkPseudoObjectAssignment
15366   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15367   // both expressions are overloadable or either is type-dependent),
15368   // or CreateBuiltinBinOp (in any other case).  We also want to get
15369   // any placeholder types out of the way.
15370 
15371   // Handle pseudo-objects in the LHS.
15372   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15373     // Assignments with a pseudo-object l-value need special analysis.
15374     if (pty->getKind() == BuiltinType::PseudoObject &&
15375         BinaryOperator::isAssignmentOp(Opc))
15376       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15377 
15378     // Don't resolve overloads if the other type is overloadable.
15379     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15380       // We can't actually test that if we still have a placeholder,
15381       // though.  Fortunately, none of the exceptions we see in that
15382       // code below are valid when the LHS is an overload set.  Note
15383       // that an overload set can be dependently-typed, but it never
15384       // instantiates to having an overloadable type.
15385       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15386       if (resolvedRHS.isInvalid()) return ExprError();
15387       RHSExpr = resolvedRHS.get();
15388 
15389       if (RHSExpr->isTypeDependent() ||
15390           RHSExpr->getType()->isOverloadableType())
15391         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15392     }
15393 
15394     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15395     // template, diagnose the missing 'template' keyword instead of diagnosing
15396     // an invalid use of a bound member function.
15397     //
15398     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15399     // to C++1z [over.over]/1.4, but we already checked for that case above.
15400     if (Opc == BO_LT && inTemplateInstantiation() &&
15401         (pty->getKind() == BuiltinType::BoundMember ||
15402          pty->getKind() == BuiltinType::Overload)) {
15403       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15404       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15405           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
15406             return isa<FunctionTemplateDecl>(ND);
15407           })) {
15408         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15409                                 : OE->getNameLoc(),
15410              diag::err_template_kw_missing)
15411           << OE->getName().getAsString() << "";
15412         return ExprError();
15413       }
15414     }
15415 
15416     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15417     if (LHS.isInvalid()) return ExprError();
15418     LHSExpr = LHS.get();
15419   }
15420 
15421   // Handle pseudo-objects in the RHS.
15422   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15423     // An overload in the RHS can potentially be resolved by the type
15424     // being assigned to.
15425     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15426       if (getLangOpts().CPlusPlus &&
15427           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15428            LHSExpr->getType()->isOverloadableType()))
15429         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15430 
15431       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15432     }
15433 
15434     // Don't resolve overloads if the other type is overloadable.
15435     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15436         LHSExpr->getType()->isOverloadableType())
15437       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15438 
15439     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15440     if (!resolvedRHS.isUsable()) return ExprError();
15441     RHSExpr = resolvedRHS.get();
15442   }
15443 
15444   if (getLangOpts().CPlusPlus) {
15445     // If either expression is type-dependent, always build an
15446     // overloaded op.
15447     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
15448       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15449 
15450     // Otherwise, build an overloaded op if either expression has an
15451     // overloadable type.
15452     if (LHSExpr->getType()->isOverloadableType() ||
15453         RHSExpr->getType()->isOverloadableType())
15454       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15455   }
15456 
15457   if (getLangOpts().RecoveryAST &&
15458       (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15459     assert(!getLangOpts().CPlusPlus);
15460     assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15461            "Should only occur in error-recovery path.");
15462     if (BinaryOperator::isCompoundAssignmentOp(Opc))
15463       // C [6.15.16] p3:
15464       // An assignment expression has the value of the left operand after the
15465       // assignment, but is not an lvalue.
15466       return CompoundAssignOperator::Create(
15467           Context, LHSExpr, RHSExpr, Opc,
15468           LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
15469           OpLoc, CurFPFeatureOverrides());
15470     QualType ResultType;
15471     switch (Opc) {
15472     case BO_Assign:
15473       ResultType = LHSExpr->getType().getUnqualifiedType();
15474       break;
15475     case BO_LT:
15476     case BO_GT:
15477     case BO_LE:
15478     case BO_GE:
15479     case BO_EQ:
15480     case BO_NE:
15481     case BO_LAnd:
15482     case BO_LOr:
15483       // These operators have a fixed result type regardless of operands.
15484       ResultType = Context.IntTy;
15485       break;
15486     case BO_Comma:
15487       ResultType = RHSExpr->getType();
15488       break;
15489     default:
15490       ResultType = Context.DependentTy;
15491       break;
15492     }
15493     return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15494                                   VK_PRValue, OK_Ordinary, OpLoc,
15495                                   CurFPFeatureOverrides());
15496   }
15497 
15498   // Build a built-in binary operation.
15499   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15500 }
15501 
15502 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
15503   if (T.isNull() || T->isDependentType())
15504     return false;
15505 
15506   if (!T->isPromotableIntegerType())
15507     return true;
15508 
15509   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15510 }
15511 
15512 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
15513                                       UnaryOperatorKind Opc,
15514                                       Expr *InputExpr) {
15515   ExprResult Input = InputExpr;
15516   ExprValueKind VK = VK_PRValue;
15517   ExprObjectKind OK = OK_Ordinary;
15518   QualType resultType;
15519   bool CanOverflow = false;
15520 
15521   bool ConvertHalfVec = false;
15522   if (getLangOpts().OpenCL) {
15523     QualType Ty = InputExpr->getType();
15524     // The only legal unary operation for atomics is '&'.
15525     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15526     // OpenCL special types - image, sampler, pipe, and blocks are to be used
15527     // only with a builtin functions and therefore should be disallowed here.
15528         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15529         || Ty->isBlockPointerType())) {
15530       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15531                        << InputExpr->getType()
15532                        << Input.get()->getSourceRange());
15533     }
15534   }
15535 
15536   if (getLangOpts().HLSL) {
15537     if (Opc == UO_AddrOf)
15538       return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15539     if (Opc == UO_Deref)
15540       return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15541   }
15542 
15543   switch (Opc) {
15544   case UO_PreInc:
15545   case UO_PreDec:
15546   case UO_PostInc:
15547   case UO_PostDec:
15548     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
15549                                                 OpLoc,
15550                                                 Opc == UO_PreInc ||
15551                                                 Opc == UO_PostInc,
15552                                                 Opc == UO_PreInc ||
15553                                                 Opc == UO_PreDec);
15554     CanOverflow = isOverflowingIntegerType(Context, resultType);
15555     break;
15556   case UO_AddrOf:
15557     resultType = CheckAddressOfOperand(Input, OpLoc);
15558     CheckAddressOfNoDeref(InputExpr);
15559     RecordModifiableNonNullParam(*this, InputExpr);
15560     break;
15561   case UO_Deref: {
15562     Input = DefaultFunctionArrayLvalueConversion(Input.get());
15563     if (Input.isInvalid()) return ExprError();
15564     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
15565     break;
15566   }
15567   case UO_Plus:
15568   case UO_Minus:
15569     CanOverflow = Opc == UO_Minus &&
15570                   isOverflowingIntegerType(Context, Input.get()->getType());
15571     Input = UsualUnaryConversions(Input.get());
15572     if (Input.isInvalid()) return ExprError();
15573     // Unary plus and minus require promoting an operand of half vector to a
15574     // float vector and truncating the result back to a half vector. For now, we
15575     // do this only when HalfArgsAndReturns is set (that is, when the target is
15576     // arm or arm64).
15577     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15578 
15579     // If the operand is a half vector, promote it to a float vector.
15580     if (ConvertHalfVec)
15581       Input = convertVector(Input.get(), Context.FloatTy, *this);
15582     resultType = Input.get()->getType();
15583     if (resultType->isDependentType())
15584       break;
15585     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15586       break;
15587     else if (resultType->isVectorType() &&
15588              // The z vector extensions don't allow + or - with bool vectors.
15589              (!Context.getLangOpts().ZVector ||
15590               resultType->castAs<VectorType>()->getVectorKind() !=
15591               VectorType::AltiVecBool))
15592       break;
15593     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15594              Opc == UO_Plus &&
15595              resultType->isPointerType())
15596       break;
15597 
15598     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15599       << resultType << Input.get()->getSourceRange());
15600 
15601   case UO_Not: // bitwise complement
15602     Input = UsualUnaryConversions(Input.get());
15603     if (Input.isInvalid())
15604       return ExprError();
15605     resultType = Input.get()->getType();
15606     if (resultType->isDependentType())
15607       break;
15608     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15609     if (resultType->isComplexType() || resultType->isComplexIntegerType())
15610       // C99 does not support '~' for complex conjugation.
15611       Diag(OpLoc, diag::ext_integer_complement_complex)
15612           << resultType << Input.get()->getSourceRange();
15613     else if (resultType->hasIntegerRepresentation())
15614       break;
15615     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15616       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15617       // on vector float types.
15618       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15619       if (!T->isIntegerType())
15620         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15621                           << resultType << Input.get()->getSourceRange());
15622     } else {
15623       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15624                        << resultType << Input.get()->getSourceRange());
15625     }
15626     break;
15627 
15628   case UO_LNot: // logical negation
15629     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15630     Input = DefaultFunctionArrayLvalueConversion(Input.get());
15631     if (Input.isInvalid()) return ExprError();
15632     resultType = Input.get()->getType();
15633 
15634     // Though we still have to promote half FP to float...
15635     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15636       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
15637       resultType = Context.FloatTy;
15638     }
15639 
15640     if (resultType->isDependentType())
15641       break;
15642     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15643       // C99 6.5.3.3p1: ok, fallthrough;
15644       if (Context.getLangOpts().CPlusPlus) {
15645         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15646         // operand contextually converted to bool.
15647         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15648                                   ScalarTypeToBooleanCastKind(resultType));
15649       } else if (Context.getLangOpts().OpenCL &&
15650                  Context.getLangOpts().OpenCLVersion < 120) {
15651         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15652         // operate on scalar float types.
15653         if (!resultType->isIntegerType() && !resultType->isPointerType())
15654           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15655                            << resultType << Input.get()->getSourceRange());
15656       }
15657     } else if (resultType->isExtVectorType()) {
15658       if (Context.getLangOpts().OpenCL &&
15659           Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15660         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15661         // operate on vector float types.
15662         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15663         if (!T->isIntegerType())
15664           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15665                            << resultType << Input.get()->getSourceRange());
15666       }
15667       // Vector logical not returns the signed variant of the operand type.
15668       resultType = GetSignedVectorType(resultType);
15669       break;
15670     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
15671       const VectorType *VTy = resultType->castAs<VectorType>();
15672       if (VTy->getVectorKind() != VectorType::GenericVector)
15673         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15674                          << resultType << Input.get()->getSourceRange());
15675 
15676       // Vector logical not returns the signed variant of the operand type.
15677       resultType = GetSignedVectorType(resultType);
15678       break;
15679     } else {
15680       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15681         << resultType << Input.get()->getSourceRange());
15682     }
15683 
15684     // LNot always has type int. C99 6.5.3.3p5.
15685     // In C++, it's bool. C++ 5.3.1p8
15686     resultType = Context.getLogicalOperationType();
15687     break;
15688   case UO_Real:
15689   case UO_Imag:
15690     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15691     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
15692     // complex l-values to ordinary l-values and all other values to r-values.
15693     if (Input.isInvalid()) return ExprError();
15694     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15695       if (Input.get()->isGLValue() &&
15696           Input.get()->getObjectKind() == OK_Ordinary)
15697         VK = Input.get()->getValueKind();
15698     } else if (!getLangOpts().CPlusPlus) {
15699       // In C, a volatile scalar is read by __imag. In C++, it is not.
15700       Input = DefaultLvalueConversion(Input.get());
15701     }
15702     break;
15703   case UO_Extension:
15704     resultType = Input.get()->getType();
15705     VK = Input.get()->getValueKind();
15706     OK = Input.get()->getObjectKind();
15707     break;
15708   case UO_Coawait:
15709     // It's unnecessary to represent the pass-through operator co_await in the
15710     // AST; just return the input expression instead.
15711     assert(!Input.get()->getType()->isDependentType() &&
15712                    "the co_await expression must be non-dependant before "
15713                    "building operator co_await");
15714     return Input;
15715   }
15716   if (resultType.isNull() || Input.isInvalid())
15717     return ExprError();
15718 
15719   // Check for array bounds violations in the operand of the UnaryOperator,
15720   // except for the '*' and '&' operators that have to be handled specially
15721   // by CheckArrayAccess (as there are special cases like &array[arraysize]
15722   // that are explicitly defined as valid by the standard).
15723   if (Opc != UO_AddrOf && Opc != UO_Deref)
15724     CheckArrayAccess(Input.get());
15725 
15726   auto *UO =
15727       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15728                             OpLoc, CanOverflow, CurFPFeatureOverrides());
15729 
15730   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15731       !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15732       !isUnevaluatedContext())
15733     ExprEvalContexts.back().PossibleDerefs.insert(UO);
15734 
15735   // Convert the result back to a half vector.
15736   if (ConvertHalfVec)
15737     return convertVector(UO, Context.HalfTy, *this);
15738   return UO;
15739 }
15740 
15741 /// Determine whether the given expression is a qualified member
15742 /// access expression, of a form that could be turned into a pointer to member
15743 /// with the address-of operator.
15744 bool Sema::isQualifiedMemberAccess(Expr *E) {
15745   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15746     if (!DRE->getQualifier())
15747       return false;
15748 
15749     ValueDecl *VD = DRE->getDecl();
15750     if (!VD->isCXXClassMember())
15751       return false;
15752 
15753     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15754       return true;
15755     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15756       return Method->isInstance();
15757 
15758     return false;
15759   }
15760 
15761   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15762     if (!ULE->getQualifier())
15763       return false;
15764 
15765     for (NamedDecl *D : ULE->decls()) {
15766       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15767         if (Method->isInstance())
15768           return true;
15769       } else {
15770         // Overload set does not contain methods.
15771         break;
15772       }
15773     }
15774 
15775     return false;
15776   }
15777 
15778   return false;
15779 }
15780 
15781 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15782                               UnaryOperatorKind Opc, Expr *Input) {
15783   // First things first: handle placeholders so that the
15784   // overloaded-operator check considers the right type.
15785   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15786     // Increment and decrement of pseudo-object references.
15787     if (pty->getKind() == BuiltinType::PseudoObject &&
15788         UnaryOperator::isIncrementDecrementOp(Opc))
15789       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15790 
15791     // extension is always a builtin operator.
15792     if (Opc == UO_Extension)
15793       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15794 
15795     // & gets special logic for several kinds of placeholder.
15796     // The builtin code knows what to do.
15797     if (Opc == UO_AddrOf &&
15798         (pty->getKind() == BuiltinType::Overload ||
15799          pty->getKind() == BuiltinType::UnknownAny ||
15800          pty->getKind() == BuiltinType::BoundMember))
15801       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15802 
15803     // Anything else needs to be handled now.
15804     ExprResult Result = CheckPlaceholderExpr(Input);
15805     if (Result.isInvalid()) return ExprError();
15806     Input = Result.get();
15807   }
15808 
15809   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15810       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15811       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15812     // Find all of the overloaded operators visible from this point.
15813     UnresolvedSet<16> Functions;
15814     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15815     if (S && OverOp != OO_None)
15816       LookupOverloadedOperatorName(OverOp, S, Functions);
15817 
15818     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15819   }
15820 
15821   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15822 }
15823 
15824 // Unary Operators.  'Tok' is the token for the operator.
15825 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
15826                               tok::TokenKind Op, Expr *Input) {
15827   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
15828 }
15829 
15830 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15831 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15832                                 LabelDecl *TheDecl) {
15833   TheDecl->markUsed(Context);
15834   // Create the AST node.  The address of a label always has type 'void*'.
15835   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
15836                                      Context.getPointerType(Context.VoidTy));
15837 }
15838 
15839 void Sema::ActOnStartStmtExpr() {
15840   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15841 }
15842 
15843 void Sema::ActOnStmtExprError() {
15844   // Note that function is also called by TreeTransform when leaving a
15845   // StmtExpr scope without rebuilding anything.
15846 
15847   DiscardCleanupsInEvaluationContext();
15848   PopExpressionEvaluationContext();
15849 }
15850 
15851 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15852                                SourceLocation RPLoc) {
15853   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15854 }
15855 
15856 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15857                                SourceLocation RPLoc, unsigned TemplateDepth) {
15858   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15859   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15860 
15861   if (hasAnyUnrecoverableErrorsInThisFunction())
15862     DiscardCleanupsInEvaluationContext();
15863   assert(!Cleanup.exprNeedsCleanups() &&
15864          "cleanups within StmtExpr not correctly bound!");
15865   PopExpressionEvaluationContext();
15866 
15867   // FIXME: there are a variety of strange constraints to enforce here, for
15868   // example, it is not possible to goto into a stmt expression apparently.
15869   // More semantic analysis is needed.
15870 
15871   // If there are sub-stmts in the compound stmt, take the type of the last one
15872   // as the type of the stmtexpr.
15873   QualType Ty = Context.VoidTy;
15874   bool StmtExprMayBindToTemp = false;
15875   if (!Compound->body_empty()) {
15876     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15877     if (const auto *LastStmt =
15878             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15879       if (const Expr *Value = LastStmt->getExprStmt()) {
15880         StmtExprMayBindToTemp = true;
15881         Ty = Value->getType();
15882       }
15883     }
15884   }
15885 
15886   // FIXME: Check that expression type is complete/non-abstract; statement
15887   // expressions are not lvalues.
15888   Expr *ResStmtExpr =
15889       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15890   if (StmtExprMayBindToTemp)
15891     return MaybeBindToTemporary(ResStmtExpr);
15892   return ResStmtExpr;
15893 }
15894 
15895 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15896   if (ER.isInvalid())
15897     return ExprError();
15898 
15899   // Do function/array conversion on the last expression, but not
15900   // lvalue-to-rvalue.  However, initialize an unqualified type.
15901   ER = DefaultFunctionArrayConversion(ER.get());
15902   if (ER.isInvalid())
15903     return ExprError();
15904   Expr *E = ER.get();
15905 
15906   if (E->isTypeDependent())
15907     return E;
15908 
15909   // In ARC, if the final expression ends in a consume, splice
15910   // the consume out and bind it later.  In the alternate case
15911   // (when dealing with a retainable type), the result
15912   // initialization will create a produce.  In both cases the
15913   // result will be +1, and we'll need to balance that out with
15914   // a bind.
15915   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15916   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15917     return Cast->getSubExpr();
15918 
15919   // FIXME: Provide a better location for the initialization.
15920   return PerformCopyInitialization(
15921       InitializedEntity::InitializeStmtExprResult(
15922           E->getBeginLoc(), E->getType().getUnqualifiedType()),
15923       SourceLocation(), E);
15924 }
15925 
15926 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15927                                       TypeSourceInfo *TInfo,
15928                                       ArrayRef<OffsetOfComponent> Components,
15929                                       SourceLocation RParenLoc) {
15930   QualType ArgTy = TInfo->getType();
15931   bool Dependent = ArgTy->isDependentType();
15932   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15933 
15934   // We must have at least one component that refers to the type, and the first
15935   // one is known to be a field designator.  Verify that the ArgTy represents
15936   // a struct/union/class.
15937   if (!Dependent && !ArgTy->isRecordType())
15938     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15939                        << ArgTy << TypeRange);
15940 
15941   // Type must be complete per C99 7.17p3 because a declaring a variable
15942   // with an incomplete type would be ill-formed.
15943   if (!Dependent
15944       && RequireCompleteType(BuiltinLoc, ArgTy,
15945                              diag::err_offsetof_incomplete_type, TypeRange))
15946     return ExprError();
15947 
15948   bool DidWarnAboutNonPOD = false;
15949   QualType CurrentType = ArgTy;
15950   SmallVector<OffsetOfNode, 4> Comps;
15951   SmallVector<Expr*, 4> Exprs;
15952   for (const OffsetOfComponent &OC : Components) {
15953     if (OC.isBrackets) {
15954       // Offset of an array sub-field.  TODO: Should we allow vector elements?
15955       if (!CurrentType->isDependentType()) {
15956         const ArrayType *AT = Context.getAsArrayType(CurrentType);
15957         if(!AT)
15958           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15959                            << CurrentType);
15960         CurrentType = AT->getElementType();
15961       } else
15962         CurrentType = Context.DependentTy;
15963 
15964       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15965       if (IdxRval.isInvalid())
15966         return ExprError();
15967       Expr *Idx = IdxRval.get();
15968 
15969       // The expression must be an integral expression.
15970       // FIXME: An integral constant expression?
15971       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15972           !Idx->getType()->isIntegerType())
15973         return ExprError(
15974             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15975             << Idx->getSourceRange());
15976 
15977       // Record this array index.
15978       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15979       Exprs.push_back(Idx);
15980       continue;
15981     }
15982 
15983     // Offset of a field.
15984     if (CurrentType->isDependentType()) {
15985       // We have the offset of a field, but we can't look into the dependent
15986       // type. Just record the identifier of the field.
15987       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15988       CurrentType = Context.DependentTy;
15989       continue;
15990     }
15991 
15992     // We need to have a complete type to look into.
15993     if (RequireCompleteType(OC.LocStart, CurrentType,
15994                             diag::err_offsetof_incomplete_type))
15995       return ExprError();
15996 
15997     // Look for the designated field.
15998     const RecordType *RC = CurrentType->getAs<RecordType>();
15999     if (!RC)
16000       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16001                        << CurrentType);
16002     RecordDecl *RD = RC->getDecl();
16003 
16004     // C++ [lib.support.types]p5:
16005     //   The macro offsetof accepts a restricted set of type arguments in this
16006     //   International Standard. type shall be a POD structure or a POD union
16007     //   (clause 9).
16008     // C++11 [support.types]p4:
16009     //   If type is not a standard-layout class (Clause 9), the results are
16010     //   undefined.
16011     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16012       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16013       unsigned DiagID =
16014         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16015                             : diag::ext_offsetof_non_pod_type;
16016 
16017       if (!IsSafe && !DidWarnAboutNonPOD &&
16018           DiagRuntimeBehavior(BuiltinLoc, nullptr,
16019                               PDiag(DiagID)
16020                               << SourceRange(Components[0].LocStart, OC.LocEnd)
16021                               << CurrentType))
16022         DidWarnAboutNonPOD = true;
16023     }
16024 
16025     // Look for the field.
16026     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16027     LookupQualifiedName(R, RD);
16028     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16029     IndirectFieldDecl *IndirectMemberDecl = nullptr;
16030     if (!MemberDecl) {
16031       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16032         MemberDecl = IndirectMemberDecl->getAnonField();
16033     }
16034 
16035     if (!MemberDecl)
16036       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
16037                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
16038                                                               OC.LocEnd));
16039 
16040     // C99 7.17p3:
16041     //   (If the specified member is a bit-field, the behavior is undefined.)
16042     //
16043     // We diagnose this as an error.
16044     if (MemberDecl->isBitField()) {
16045       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16046         << MemberDecl->getDeclName()
16047         << SourceRange(BuiltinLoc, RParenLoc);
16048       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16049       return ExprError();
16050     }
16051 
16052     RecordDecl *Parent = MemberDecl->getParent();
16053     if (IndirectMemberDecl)
16054       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16055 
16056     // If the member was found in a base class, introduce OffsetOfNodes for
16057     // the base class indirections.
16058     CXXBasePaths Paths;
16059     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16060                       Paths)) {
16061       if (Paths.getDetectedVirtual()) {
16062         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16063           << MemberDecl->getDeclName()
16064           << SourceRange(BuiltinLoc, RParenLoc);
16065         return ExprError();
16066       }
16067 
16068       CXXBasePath &Path = Paths.front();
16069       for (const CXXBasePathElement &B : Path)
16070         Comps.push_back(OffsetOfNode(B.Base));
16071     }
16072 
16073     if (IndirectMemberDecl) {
16074       for (auto *FI : IndirectMemberDecl->chain()) {
16075         assert(isa<FieldDecl>(FI));
16076         Comps.push_back(OffsetOfNode(OC.LocStart,
16077                                      cast<FieldDecl>(FI), OC.LocEnd));
16078       }
16079     } else
16080       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16081 
16082     CurrentType = MemberDecl->getType().getNonReferenceType();
16083   }
16084 
16085   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16086                               Comps, Exprs, RParenLoc);
16087 }
16088 
16089 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
16090                                       SourceLocation BuiltinLoc,
16091                                       SourceLocation TypeLoc,
16092                                       ParsedType ParsedArgTy,
16093                                       ArrayRef<OffsetOfComponent> Components,
16094                                       SourceLocation RParenLoc) {
16095 
16096   TypeSourceInfo *ArgTInfo;
16097   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16098   if (ArgTy.isNull())
16099     return ExprError();
16100 
16101   if (!ArgTInfo)
16102     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16103 
16104   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16105 }
16106 
16107 
16108 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16109                                  Expr *CondExpr,
16110                                  Expr *LHSExpr, Expr *RHSExpr,
16111                                  SourceLocation RPLoc) {
16112   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16113 
16114   ExprValueKind VK = VK_PRValue;
16115   ExprObjectKind OK = OK_Ordinary;
16116   QualType resType;
16117   bool CondIsTrue = false;
16118   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16119     resType = Context.DependentTy;
16120   } else {
16121     // The conditional expression is required to be a constant expression.
16122     llvm::APSInt condEval(32);
16123     ExprResult CondICE = VerifyIntegerConstantExpression(
16124         CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16125     if (CondICE.isInvalid())
16126       return ExprError();
16127     CondExpr = CondICE.get();
16128     CondIsTrue = condEval.getZExtValue();
16129 
16130     // If the condition is > zero, then the AST type is the same as the LHSExpr.
16131     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16132 
16133     resType = ActiveExpr->getType();
16134     VK = ActiveExpr->getValueKind();
16135     OK = ActiveExpr->getObjectKind();
16136   }
16137 
16138   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16139                                   resType, VK, OK, RPLoc, CondIsTrue);
16140 }
16141 
16142 //===----------------------------------------------------------------------===//
16143 // Clang Extensions.
16144 //===----------------------------------------------------------------------===//
16145 
16146 /// ActOnBlockStart - This callback is invoked when a block literal is started.
16147 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16148   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
16149 
16150   if (LangOpts.CPlusPlus) {
16151     MangleNumberingContext *MCtx;
16152     Decl *ManglingContextDecl;
16153     std::tie(MCtx, ManglingContextDecl) =
16154         getCurrentMangleNumberContext(Block->getDeclContext());
16155     if (MCtx) {
16156       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16157       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16158     }
16159   }
16160 
16161   PushBlockScope(CurScope, Block);
16162   CurContext->addDecl(Block);
16163   if (CurScope)
16164     PushDeclContext(CurScope, Block);
16165   else
16166     CurContext = Block;
16167 
16168   getCurBlock()->HasImplicitReturnType = true;
16169 
16170   // Enter a new evaluation context to insulate the block from any
16171   // cleanups from the enclosing full-expression.
16172   PushExpressionEvaluationContext(
16173       ExpressionEvaluationContext::PotentiallyEvaluated);
16174 }
16175 
16176 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16177                                Scope *CurScope) {
16178   assert(ParamInfo.getIdentifier() == nullptr &&
16179          "block-id should have no identifier!");
16180   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16181   BlockScopeInfo *CurBlock = getCurBlock();
16182 
16183   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
16184   QualType T = Sig->getType();
16185 
16186   // FIXME: We should allow unexpanded parameter packs here, but that would,
16187   // in turn, make the block expression contain unexpanded parameter packs.
16188   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16189     // Drop the parameters.
16190     FunctionProtoType::ExtProtoInfo EPI;
16191     EPI.HasTrailingReturn = false;
16192     EPI.TypeQuals.addConst();
16193     T = Context.getFunctionType(Context.DependentTy, None, EPI);
16194     Sig = Context.getTrivialTypeSourceInfo(T);
16195   }
16196 
16197   // GetTypeForDeclarator always produces a function type for a block
16198   // literal signature.  Furthermore, it is always a FunctionProtoType
16199   // unless the function was written with a typedef.
16200   assert(T->isFunctionType() &&
16201          "GetTypeForDeclarator made a non-function block signature");
16202 
16203   // Look for an explicit signature in that function type.
16204   FunctionProtoTypeLoc ExplicitSignature;
16205 
16206   if ((ExplicitSignature = Sig->getTypeLoc()
16207                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
16208 
16209     // Check whether that explicit signature was synthesized by
16210     // GetTypeForDeclarator.  If so, don't save that as part of the
16211     // written signature.
16212     if (ExplicitSignature.getLocalRangeBegin() ==
16213         ExplicitSignature.getLocalRangeEnd()) {
16214       // This would be much cheaper if we stored TypeLocs instead of
16215       // TypeSourceInfos.
16216       TypeLoc Result = ExplicitSignature.getReturnLoc();
16217       unsigned Size = Result.getFullDataSize();
16218       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16219       Sig->getTypeLoc().initializeFullCopy(Result, Size);
16220 
16221       ExplicitSignature = FunctionProtoTypeLoc();
16222     }
16223   }
16224 
16225   CurBlock->TheDecl->setSignatureAsWritten(Sig);
16226   CurBlock->FunctionType = T;
16227 
16228   const auto *Fn = T->castAs<FunctionType>();
16229   QualType RetTy = Fn->getReturnType();
16230   bool isVariadic =
16231       (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16232 
16233   CurBlock->TheDecl->setIsVariadic(isVariadic);
16234 
16235   // Context.DependentTy is used as a placeholder for a missing block
16236   // return type.  TODO:  what should we do with declarators like:
16237   //   ^ * { ... }
16238   // If the answer is "apply template argument deduction"....
16239   if (RetTy != Context.DependentTy) {
16240     CurBlock->ReturnType = RetTy;
16241     CurBlock->TheDecl->setBlockMissingReturnType(false);
16242     CurBlock->HasImplicitReturnType = false;
16243   }
16244 
16245   // Push block parameters from the declarator if we had them.
16246   SmallVector<ParmVarDecl*, 8> Params;
16247   if (ExplicitSignature) {
16248     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16249       ParmVarDecl *Param = ExplicitSignature.getParam(I);
16250       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16251           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16252         // Diagnose this as an extension in C17 and earlier.
16253         if (!getLangOpts().C2x)
16254           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
16255       }
16256       Params.push_back(Param);
16257     }
16258 
16259   // Fake up parameter variables if we have a typedef, like
16260   //   ^ fntype { ... }
16261   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16262     for (const auto &I : Fn->param_types()) {
16263       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16264           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16265       Params.push_back(Param);
16266     }
16267   }
16268 
16269   // Set the parameters on the block decl.
16270   if (!Params.empty()) {
16271     CurBlock->TheDecl->setParams(Params);
16272     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
16273                              /*CheckParameterNames=*/false);
16274   }
16275 
16276   // Finally we can process decl attributes.
16277   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16278 
16279   // Put the parameter variables in scope.
16280   for (auto AI : CurBlock->TheDecl->parameters()) {
16281     AI->setOwningFunction(CurBlock->TheDecl);
16282 
16283     // If this has an identifier, add it to the scope stack.
16284     if (AI->getIdentifier()) {
16285       CheckShadow(CurBlock->TheScope, AI);
16286 
16287       PushOnScopeChains(AI, CurBlock->TheScope);
16288     }
16289   }
16290 }
16291 
16292 /// ActOnBlockError - If there is an error parsing a block, this callback
16293 /// is invoked to pop the information about the block from the action impl.
16294 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16295   // Leave the expression-evaluation context.
16296   DiscardCleanupsInEvaluationContext();
16297   PopExpressionEvaluationContext();
16298 
16299   // Pop off CurBlock, handle nested blocks.
16300   PopDeclContext();
16301   PopFunctionScopeInfo();
16302 }
16303 
16304 /// ActOnBlockStmtExpr - This is called when the body of a block statement
16305 /// literal was successfully completed.  ^(int x){...}
16306 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16307                                     Stmt *Body, Scope *CurScope) {
16308   // If blocks are disabled, emit an error.
16309   if (!LangOpts.Blocks)
16310     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16311 
16312   // Leave the expression-evaluation context.
16313   if (hasAnyUnrecoverableErrorsInThisFunction())
16314     DiscardCleanupsInEvaluationContext();
16315   assert(!Cleanup.exprNeedsCleanups() &&
16316          "cleanups within block not correctly bound!");
16317   PopExpressionEvaluationContext();
16318 
16319   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16320   BlockDecl *BD = BSI->TheDecl;
16321 
16322   if (BSI->HasImplicitReturnType)
16323     deduceClosureReturnType(*BSI);
16324 
16325   QualType RetTy = Context.VoidTy;
16326   if (!BSI->ReturnType.isNull())
16327     RetTy = BSI->ReturnType;
16328 
16329   bool NoReturn = BD->hasAttr<NoReturnAttr>();
16330   QualType BlockTy;
16331 
16332   // If the user wrote a function type in some form, try to use that.
16333   if (!BSI->FunctionType.isNull()) {
16334     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16335 
16336     FunctionType::ExtInfo Ext = FTy->getExtInfo();
16337     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16338 
16339     // Turn protoless block types into nullary block types.
16340     if (isa<FunctionNoProtoType>(FTy)) {
16341       FunctionProtoType::ExtProtoInfo EPI;
16342       EPI.ExtInfo = Ext;
16343       BlockTy = Context.getFunctionType(RetTy, None, EPI);
16344 
16345     // Otherwise, if we don't need to change anything about the function type,
16346     // preserve its sugar structure.
16347     } else if (FTy->getReturnType() == RetTy &&
16348                (!NoReturn || FTy->getNoReturnAttr())) {
16349       BlockTy = BSI->FunctionType;
16350 
16351     // Otherwise, make the minimal modifications to the function type.
16352     } else {
16353       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16354       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16355       EPI.TypeQuals = Qualifiers();
16356       EPI.ExtInfo = Ext;
16357       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16358     }
16359 
16360   // If we don't have a function type, just build one from nothing.
16361   } else {
16362     FunctionProtoType::ExtProtoInfo EPI;
16363     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16364     BlockTy = Context.getFunctionType(RetTy, None, EPI);
16365   }
16366 
16367   DiagnoseUnusedParameters(BD->parameters());
16368   BlockTy = Context.getBlockPointerType(BlockTy);
16369 
16370   // If needed, diagnose invalid gotos and switches in the block.
16371   if (getCurFunction()->NeedsScopeChecking() &&
16372       !PP.isCodeCompletionEnabled())
16373     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16374 
16375   BD->setBody(cast<CompoundStmt>(Body));
16376 
16377   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16378     DiagnoseUnguardedAvailabilityViolations(BD);
16379 
16380   // Try to apply the named return value optimization. We have to check again
16381   // if we can do this, though, because blocks keep return statements around
16382   // to deduce an implicit return type.
16383   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16384       !BD->isDependentContext())
16385     computeNRVO(Body, BSI);
16386 
16387   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
16388       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
16389     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
16390                           NTCUK_Destruct|NTCUK_Copy);
16391 
16392   PopDeclContext();
16393 
16394   // Set the captured variables on the block.
16395   SmallVector<BlockDecl::Capture, 4> Captures;
16396   for (Capture &Cap : BSI->Captures) {
16397     if (Cap.isInvalid() || Cap.isThisCapture())
16398       continue;
16399 
16400     VarDecl *Var = Cap.getVariable();
16401     Expr *CopyExpr = nullptr;
16402     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16403       if (const RecordType *Record =
16404               Cap.getCaptureType()->getAs<RecordType>()) {
16405         // The capture logic needs the destructor, so make sure we mark it.
16406         // Usually this is unnecessary because most local variables have
16407         // their destructors marked at declaration time, but parameters are
16408         // an exception because it's technically only the call site that
16409         // actually requires the destructor.
16410         if (isa<ParmVarDecl>(Var))
16411           FinalizeVarWithDestructor(Var, Record);
16412 
16413         // Enter a separate potentially-evaluated context while building block
16414         // initializers to isolate their cleanups from those of the block
16415         // itself.
16416         // FIXME: Is this appropriate even when the block itself occurs in an
16417         // unevaluated operand?
16418         EnterExpressionEvaluationContext EvalContext(
16419             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16420 
16421         SourceLocation Loc = Cap.getLocation();
16422 
16423         ExprResult Result = BuildDeclarationNameExpr(
16424             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16425 
16426         // According to the blocks spec, the capture of a variable from
16427         // the stack requires a const copy constructor.  This is not true
16428         // of the copy/move done to move a __block variable to the heap.
16429         if (!Result.isInvalid() &&
16430             !Result.get()->getType().isConstQualified()) {
16431           Result = ImpCastExprToType(Result.get(),
16432                                      Result.get()->getType().withConst(),
16433                                      CK_NoOp, VK_LValue);
16434         }
16435 
16436         if (!Result.isInvalid()) {
16437           Result = PerformCopyInitialization(
16438               InitializedEntity::InitializeBlock(Var->getLocation(),
16439                                                  Cap.getCaptureType()),
16440               Loc, Result.get());
16441         }
16442 
16443         // Build a full-expression copy expression if initialization
16444         // succeeded and used a non-trivial constructor.  Recover from
16445         // errors by pretending that the copy isn't necessary.
16446         if (!Result.isInvalid() &&
16447             !cast<CXXConstructExpr>(Result.get())->getConstructor()
16448                 ->isTrivial()) {
16449           Result = MaybeCreateExprWithCleanups(Result);
16450           CopyExpr = Result.get();
16451         }
16452       }
16453     }
16454 
16455     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16456                               CopyExpr);
16457     Captures.push_back(NewCap);
16458   }
16459   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16460 
16461   // Pop the block scope now but keep it alive to the end of this function.
16462   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
16463   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16464 
16465   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16466 
16467   // If the block isn't obviously global, i.e. it captures anything at
16468   // all, then we need to do a few things in the surrounding context:
16469   if (Result->getBlockDecl()->hasCaptures()) {
16470     // First, this expression has a new cleanup object.
16471     ExprCleanupObjects.push_back(Result->getBlockDecl());
16472     Cleanup.setExprNeedsCleanups(true);
16473 
16474     // It also gets a branch-protected scope if any of the captured
16475     // variables needs destruction.
16476     for (const auto &CI : Result->getBlockDecl()->captures()) {
16477       const VarDecl *var = CI.getVariable();
16478       if (var->getType().isDestructedType() != QualType::DK_none) {
16479         setFunctionHasBranchProtectedScope();
16480         break;
16481       }
16482     }
16483   }
16484 
16485   if (getCurFunction())
16486     getCurFunction()->addBlock(BD);
16487 
16488   return Result;
16489 }
16490 
16491 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
16492                             SourceLocation RPLoc) {
16493   TypeSourceInfo *TInfo;
16494   GetTypeFromParser(Ty, &TInfo);
16495   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16496 }
16497 
16498 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
16499                                 Expr *E, TypeSourceInfo *TInfo,
16500                                 SourceLocation RPLoc) {
16501   Expr *OrigExpr = E;
16502   bool IsMS = false;
16503 
16504   // CUDA device code does not support varargs.
16505   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16506     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16507       CUDAFunctionTarget T = IdentifyCUDATarget(F);
16508       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
16509         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16510     }
16511   }
16512 
16513   // NVPTX does not support va_arg expression.
16514   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
16515       Context.getTargetInfo().getTriple().isNVPTX())
16516     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16517 
16518   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16519   // as Microsoft ABI on an actual Microsoft platform, where
16520   // __builtin_ms_va_list and __builtin_va_list are the same.)
16521   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16522       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16523     QualType MSVaListType = Context.getBuiltinMSVaListType();
16524     if (Context.hasSameType(MSVaListType, E->getType())) {
16525       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16526         return ExprError();
16527       IsMS = true;
16528     }
16529   }
16530 
16531   // Get the va_list type
16532   QualType VaListType = Context.getBuiltinVaListType();
16533   if (!IsMS) {
16534     if (VaListType->isArrayType()) {
16535       // Deal with implicit array decay; for example, on x86-64,
16536       // va_list is an array, but it's supposed to decay to
16537       // a pointer for va_arg.
16538       VaListType = Context.getArrayDecayedType(VaListType);
16539       // Make sure the input expression also decays appropriately.
16540       ExprResult Result = UsualUnaryConversions(E);
16541       if (Result.isInvalid())
16542         return ExprError();
16543       E = Result.get();
16544     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16545       // If va_list is a record type and we are compiling in C++ mode,
16546       // check the argument using reference binding.
16547       InitializedEntity Entity = InitializedEntity::InitializeParameter(
16548           Context, Context.getLValueReferenceType(VaListType), false);
16549       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
16550       if (Init.isInvalid())
16551         return ExprError();
16552       E = Init.getAs<Expr>();
16553     } else {
16554       // Otherwise, the va_list argument must be an l-value because
16555       // it is modified by va_arg.
16556       if (!E->isTypeDependent() &&
16557           CheckForModifiableLvalue(E, BuiltinLoc, *this))
16558         return ExprError();
16559     }
16560   }
16561 
16562   if (!IsMS && !E->isTypeDependent() &&
16563       !Context.hasSameType(VaListType, E->getType()))
16564     return ExprError(
16565         Diag(E->getBeginLoc(),
16566              diag::err_first_argument_to_va_arg_not_of_type_va_list)
16567         << OrigExpr->getType() << E->getSourceRange());
16568 
16569   if (!TInfo->getType()->isDependentType()) {
16570     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16571                             diag::err_second_parameter_to_va_arg_incomplete,
16572                             TInfo->getTypeLoc()))
16573       return ExprError();
16574 
16575     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
16576                                TInfo->getType(),
16577                                diag::err_second_parameter_to_va_arg_abstract,
16578                                TInfo->getTypeLoc()))
16579       return ExprError();
16580 
16581     if (!TInfo->getType().isPODType(Context)) {
16582       Diag(TInfo->getTypeLoc().getBeginLoc(),
16583            TInfo->getType()->isObjCLifetimeType()
16584              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16585              : diag::warn_second_parameter_to_va_arg_not_pod)
16586         << TInfo->getType()
16587         << TInfo->getTypeLoc().getSourceRange();
16588     }
16589 
16590     // Check for va_arg where arguments of the given type will be promoted
16591     // (i.e. this va_arg is guaranteed to have undefined behavior).
16592     QualType PromoteType;
16593     if (TInfo->getType()->isPromotableIntegerType()) {
16594       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16595       // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16596       // and C2x 7.16.1.1p2 says, in part:
16597       //   If type is not compatible with the type of the actual next argument
16598       //   (as promoted according to the default argument promotions), the
16599       //   behavior is undefined, except for the following cases:
16600       //     - both types are pointers to qualified or unqualified versions of
16601       //       compatible types;
16602       //     - one type is a signed integer type, the other type is the
16603       //       corresponding unsigned integer type, and the value is
16604       //       representable in both types;
16605       //     - one type is pointer to qualified or unqualified void and the
16606       //       other is a pointer to a qualified or unqualified character type.
16607       // Given that type compatibility is the primary requirement (ignoring
16608       // qualifications), you would think we could call typesAreCompatible()
16609       // directly to test this. However, in C++, that checks for *same type*,
16610       // which causes false positives when passing an enumeration type to
16611       // va_arg. Instead, get the underlying type of the enumeration and pass
16612       // that.
16613       QualType UnderlyingType = TInfo->getType();
16614       if (const auto *ET = UnderlyingType->getAs<EnumType>())
16615         UnderlyingType = ET->getDecl()->getIntegerType();
16616       if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16617                                      /*CompareUnqualified*/ true))
16618         PromoteType = QualType();
16619 
16620       // If the types are still not compatible, we need to test whether the
16621       // promoted type and the underlying type are the same except for
16622       // signedness. Ask the AST for the correctly corresponding type and see
16623       // if that's compatible.
16624       if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16625           PromoteType->isUnsignedIntegerType() !=
16626               UnderlyingType->isUnsignedIntegerType()) {
16627         UnderlyingType =
16628             UnderlyingType->isUnsignedIntegerType()
16629                 ? Context.getCorrespondingSignedType(UnderlyingType)
16630                 : Context.getCorrespondingUnsignedType(UnderlyingType);
16631         if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16632                                        /*CompareUnqualified*/ true))
16633           PromoteType = QualType();
16634       }
16635     }
16636     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16637       PromoteType = Context.DoubleTy;
16638     if (!PromoteType.isNull())
16639       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
16640                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16641                           << TInfo->getType()
16642                           << PromoteType
16643                           << TInfo->getTypeLoc().getSourceRange());
16644   }
16645 
16646   QualType T = TInfo->getType().getNonLValueExprType(Context);
16647   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16648 }
16649 
16650 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
16651   // The type of __null will be int or long, depending on the size of
16652   // pointers on the target.
16653   QualType Ty;
16654   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
16655   if (pw == Context.getTargetInfo().getIntWidth())
16656     Ty = Context.IntTy;
16657   else if (pw == Context.getTargetInfo().getLongWidth())
16658     Ty = Context.LongTy;
16659   else if (pw == Context.getTargetInfo().getLongLongWidth())
16660     Ty = Context.LongLongTy;
16661   else {
16662     llvm_unreachable("I don't know size of pointer!");
16663   }
16664 
16665   return new (Context) GNUNullExpr(Ty, TokenLoc);
16666 }
16667 
16668 static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
16669   CXXRecordDecl *ImplDecl = nullptr;
16670 
16671   // Fetch the std::source_location::__impl decl.
16672   if (NamespaceDecl *Std = S.getStdNamespace()) {
16673     LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16674                           Loc, Sema::LookupOrdinaryName);
16675     if (S.LookupQualifiedName(ResultSL, Std)) {
16676       if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16677         LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16678                                 Loc, Sema::LookupOrdinaryName);
16679         if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16680             S.LookupQualifiedName(ResultImpl, SLDecl)) {
16681           ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16682         }
16683       }
16684     }
16685   }
16686 
16687   if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16688     S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16689     return nullptr;
16690   }
16691 
16692   // Verify that __impl is a trivial struct type, with no base classes, and with
16693   // only the four expected fields.
16694   if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16695       ImplDecl->getNumBases() != 0) {
16696     S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16697     return nullptr;
16698   }
16699 
16700   unsigned Count = 0;
16701   for (FieldDecl *F : ImplDecl->fields()) {
16702     StringRef Name = F->getName();
16703 
16704     if (Name == "_M_file_name") {
16705       if (F->getType() !=
16706           S.Context.getPointerType(S.Context.CharTy.withConst()))
16707         break;
16708       Count++;
16709     } else if (Name == "_M_function_name") {
16710       if (F->getType() !=
16711           S.Context.getPointerType(S.Context.CharTy.withConst()))
16712         break;
16713       Count++;
16714     } else if (Name == "_M_line") {
16715       if (!F->getType()->isIntegerType())
16716         break;
16717       Count++;
16718     } else if (Name == "_M_column") {
16719       if (!F->getType()->isIntegerType())
16720         break;
16721       Count++;
16722     } else {
16723       Count = 100; // invalid
16724       break;
16725     }
16726   }
16727   if (Count != 4) {
16728     S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16729     return nullptr;
16730   }
16731 
16732   return ImplDecl;
16733 }
16734 
16735 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
16736                                     SourceLocation BuiltinLoc,
16737                                     SourceLocation RPLoc) {
16738   QualType ResultTy;
16739   switch (Kind) {
16740   case SourceLocExpr::File:
16741   case SourceLocExpr::Function: {
16742     QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
16743     ResultTy =
16744         Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
16745     break;
16746   }
16747   case SourceLocExpr::Line:
16748   case SourceLocExpr::Column:
16749     ResultTy = Context.UnsignedIntTy;
16750     break;
16751   case SourceLocExpr::SourceLocStruct:
16752     if (!StdSourceLocationImplDecl) {
16753       StdSourceLocationImplDecl =
16754           LookupStdSourceLocationImpl(*this, BuiltinLoc);
16755       if (!StdSourceLocationImplDecl)
16756         return ExprError();
16757     }
16758     ResultTy = Context.getPointerType(
16759         Context.getRecordType(StdSourceLocationImplDecl).withConst());
16760     break;
16761   }
16762 
16763   return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16764 }
16765 
16766 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
16767                                     QualType ResultTy,
16768                                     SourceLocation BuiltinLoc,
16769                                     SourceLocation RPLoc,
16770                                     DeclContext *ParentContext) {
16771   return new (Context)
16772       SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16773 }
16774 
16775 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
16776                                         bool Diagnose) {
16777   if (!getLangOpts().ObjC)
16778     return false;
16779 
16780   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
16781   if (!PT)
16782     return false;
16783   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
16784 
16785   // Ignore any parens, implicit casts (should only be
16786   // array-to-pointer decays), and not-so-opaque values.  The last is
16787   // important for making this trigger for property assignments.
16788   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
16789   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
16790     if (OV->getSourceExpr())
16791       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
16792 
16793   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
16794     if (!PT->isObjCIdType() &&
16795         !(ID && ID->getIdentifier()->isStr("NSString")))
16796       return false;
16797     if (!SL->isOrdinary())
16798       return false;
16799 
16800     if (Diagnose) {
16801       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
16802           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
16803       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
16804     }
16805     return true;
16806   }
16807 
16808   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
16809       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
16810       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
16811       !SrcExpr->isNullPointerConstant(
16812           getASTContext(), Expr::NPC_NeverValueDependent)) {
16813     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
16814       return false;
16815     if (Diagnose) {
16816       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
16817           << /*number*/1
16818           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
16819       Expr *NumLit =
16820           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
16821       if (NumLit)
16822         Exp = NumLit;
16823     }
16824     return true;
16825   }
16826 
16827   return false;
16828 }
16829 
16830 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
16831                                               const Expr *SrcExpr) {
16832   if (!DstType->isFunctionPointerType() ||
16833       !SrcExpr->getType()->isFunctionType())
16834     return false;
16835 
16836   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16837   if (!DRE)
16838     return false;
16839 
16840   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16841   if (!FD)
16842     return false;
16843 
16844   return !S.checkAddressOfFunctionIsAvailable(FD,
16845                                               /*Complain=*/true,
16846                                               SrcExpr->getBeginLoc());
16847 }
16848 
16849 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16850                                     SourceLocation Loc,
16851                                     QualType DstType, QualType SrcType,
16852                                     Expr *SrcExpr, AssignmentAction Action,
16853                                     bool *Complained) {
16854   if (Complained)
16855     *Complained = false;
16856 
16857   // Decode the result (notice that AST's are still created for extensions).
16858   bool CheckInferredResultType = false;
16859   bool isInvalid = false;
16860   unsigned DiagKind = 0;
16861   ConversionFixItGenerator ConvHints;
16862   bool MayHaveConvFixit = false;
16863   bool MayHaveFunctionDiff = false;
16864   const ObjCInterfaceDecl *IFace = nullptr;
16865   const ObjCProtocolDecl *PDecl = nullptr;
16866 
16867   switch (ConvTy) {
16868   case Compatible:
16869       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16870       return false;
16871 
16872   case PointerToInt:
16873     if (getLangOpts().CPlusPlus) {
16874       DiagKind = diag::err_typecheck_convert_pointer_int;
16875       isInvalid = true;
16876     } else {
16877       DiagKind = diag::ext_typecheck_convert_pointer_int;
16878     }
16879     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16880     MayHaveConvFixit = true;
16881     break;
16882   case IntToPointer:
16883     if (getLangOpts().CPlusPlus) {
16884       DiagKind = diag::err_typecheck_convert_int_pointer;
16885       isInvalid = true;
16886     } else {
16887       DiagKind = diag::ext_typecheck_convert_int_pointer;
16888     }
16889     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16890     MayHaveConvFixit = true;
16891     break;
16892   case IncompatibleFunctionPointer:
16893     if (getLangOpts().CPlusPlus) {
16894       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16895       isInvalid = true;
16896     } else {
16897       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16898     }
16899     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16900     MayHaveConvFixit = true;
16901     break;
16902   case IncompatiblePointer:
16903     if (Action == AA_Passing_CFAudited) {
16904       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16905     } else if (getLangOpts().CPlusPlus) {
16906       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16907       isInvalid = true;
16908     } else {
16909       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16910     }
16911     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16912       SrcType->isObjCObjectPointerType();
16913     if (!CheckInferredResultType) {
16914       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16915     } else if (CheckInferredResultType) {
16916       SrcType = SrcType.getUnqualifiedType();
16917       DstType = DstType.getUnqualifiedType();
16918     }
16919     MayHaveConvFixit = true;
16920     break;
16921   case IncompatiblePointerSign:
16922     if (getLangOpts().CPlusPlus) {
16923       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16924       isInvalid = true;
16925     } else {
16926       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16927     }
16928     break;
16929   case FunctionVoidPointer:
16930     if (getLangOpts().CPlusPlus) {
16931       DiagKind = diag::err_typecheck_convert_pointer_void_func;
16932       isInvalid = true;
16933     } else {
16934       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16935     }
16936     break;
16937   case IncompatiblePointerDiscardsQualifiers: {
16938     // Perform array-to-pointer decay if necessary.
16939     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16940 
16941     isInvalid = true;
16942 
16943     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16944     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16945     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16946       DiagKind = diag::err_typecheck_incompatible_address_space;
16947       break;
16948 
16949     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16950       DiagKind = diag::err_typecheck_incompatible_ownership;
16951       break;
16952     }
16953 
16954     llvm_unreachable("unknown error case for discarding qualifiers!");
16955     // fallthrough
16956   }
16957   case CompatiblePointerDiscardsQualifiers:
16958     // If the qualifiers lost were because we were applying the
16959     // (deprecated) C++ conversion from a string literal to a char*
16960     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
16961     // Ideally, this check would be performed in
16962     // checkPointerTypesForAssignment. However, that would require a
16963     // bit of refactoring (so that the second argument is an
16964     // expression, rather than a type), which should be done as part
16965     // of a larger effort to fix checkPointerTypesForAssignment for
16966     // C++ semantics.
16967     if (getLangOpts().CPlusPlus &&
16968         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16969       return false;
16970     if (getLangOpts().CPlusPlus) {
16971       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
16972       isInvalid = true;
16973     } else {
16974       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
16975     }
16976 
16977     break;
16978   case IncompatibleNestedPointerQualifiers:
16979     if (getLangOpts().CPlusPlus) {
16980       isInvalid = true;
16981       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16982     } else {
16983       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16984     }
16985     break;
16986   case IncompatibleNestedPointerAddressSpaceMismatch:
16987     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16988     isInvalid = true;
16989     break;
16990   case IntToBlockPointer:
16991     DiagKind = diag::err_int_to_block_pointer;
16992     isInvalid = true;
16993     break;
16994   case IncompatibleBlockPointer:
16995     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16996     isInvalid = true;
16997     break;
16998   case IncompatibleObjCQualifiedId: {
16999     if (SrcType->isObjCQualifiedIdType()) {
17000       const ObjCObjectPointerType *srcOPT =
17001                 SrcType->castAs<ObjCObjectPointerType>();
17002       for (auto *srcProto : srcOPT->quals()) {
17003         PDecl = srcProto;
17004         break;
17005       }
17006       if (const ObjCInterfaceType *IFaceT =
17007             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17008         IFace = IFaceT->getDecl();
17009     }
17010     else if (DstType->isObjCQualifiedIdType()) {
17011       const ObjCObjectPointerType *dstOPT =
17012         DstType->castAs<ObjCObjectPointerType>();
17013       for (auto *dstProto : dstOPT->quals()) {
17014         PDecl = dstProto;
17015         break;
17016       }
17017       if (const ObjCInterfaceType *IFaceT =
17018             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17019         IFace = IFaceT->getDecl();
17020     }
17021     if (getLangOpts().CPlusPlus) {
17022       DiagKind = diag::err_incompatible_qualified_id;
17023       isInvalid = true;
17024     } else {
17025       DiagKind = diag::warn_incompatible_qualified_id;
17026     }
17027     break;
17028   }
17029   case IncompatibleVectors:
17030     if (getLangOpts().CPlusPlus) {
17031       DiagKind = diag::err_incompatible_vectors;
17032       isInvalid = true;
17033     } else {
17034       DiagKind = diag::warn_incompatible_vectors;
17035     }
17036     break;
17037   case IncompatibleObjCWeakRef:
17038     DiagKind = diag::err_arc_weak_unavailable_assign;
17039     isInvalid = true;
17040     break;
17041   case Incompatible:
17042     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17043       if (Complained)
17044         *Complained = true;
17045       return true;
17046     }
17047 
17048     DiagKind = diag::err_typecheck_convert_incompatible;
17049     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17050     MayHaveConvFixit = true;
17051     isInvalid = true;
17052     MayHaveFunctionDiff = true;
17053     break;
17054   }
17055 
17056   QualType FirstType, SecondType;
17057   switch (Action) {
17058   case AA_Assigning:
17059   case AA_Initializing:
17060     // The destination type comes first.
17061     FirstType = DstType;
17062     SecondType = SrcType;
17063     break;
17064 
17065   case AA_Returning:
17066   case AA_Passing:
17067   case AA_Passing_CFAudited:
17068   case AA_Converting:
17069   case AA_Sending:
17070   case AA_Casting:
17071     // The source type comes first.
17072     FirstType = SrcType;
17073     SecondType = DstType;
17074     break;
17075   }
17076 
17077   PartialDiagnostic FDiag = PDiag(DiagKind);
17078   AssignmentAction ActionForDiag = Action;
17079   if (Action == AA_Passing_CFAudited)
17080     ActionForDiag = AA_Passing;
17081 
17082   FDiag << FirstType << SecondType << ActionForDiag
17083         << SrcExpr->getSourceRange();
17084 
17085   if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17086       DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17087     auto isPlainChar = [](const clang::Type *Type) {
17088       return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17089              Type->isSpecificBuiltinType(BuiltinType::Char_U);
17090     };
17091     FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17092               isPlainChar(SecondType->getPointeeOrArrayElementType()));
17093   }
17094 
17095   // If we can fix the conversion, suggest the FixIts.
17096   if (!ConvHints.isNull()) {
17097     for (FixItHint &H : ConvHints.Hints)
17098       FDiag << H;
17099   }
17100 
17101   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17102 
17103   if (MayHaveFunctionDiff)
17104     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17105 
17106   Diag(Loc, FDiag);
17107   if ((DiagKind == diag::warn_incompatible_qualified_id ||
17108        DiagKind == diag::err_incompatible_qualified_id) &&
17109       PDecl && IFace && !IFace->hasDefinition())
17110     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17111         << IFace << PDecl;
17112 
17113   if (SecondType == Context.OverloadTy)
17114     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
17115                               FirstType, /*TakingAddress=*/true);
17116 
17117   if (CheckInferredResultType)
17118     EmitRelatedResultTypeNote(SrcExpr);
17119 
17120   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17121     EmitRelatedResultTypeNoteForReturn(DstType);
17122 
17123   if (Complained)
17124     *Complained = true;
17125   return isInvalid;
17126 }
17127 
17128 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17129                                                  llvm::APSInt *Result,
17130                                                  AllowFoldKind CanFold) {
17131   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17132   public:
17133     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17134                                              QualType T) override {
17135       return S.Diag(Loc, diag::err_ice_not_integral)
17136              << T << S.LangOpts.CPlusPlus;
17137     }
17138     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17139       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17140     }
17141   } Diagnoser;
17142 
17143   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17144 }
17145 
17146 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17147                                                  llvm::APSInt *Result,
17148                                                  unsigned DiagID,
17149                                                  AllowFoldKind CanFold) {
17150   class IDDiagnoser : public VerifyICEDiagnoser {
17151     unsigned DiagID;
17152 
17153   public:
17154     IDDiagnoser(unsigned DiagID)
17155       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17156 
17157     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17158       return S.Diag(Loc, DiagID);
17159     }
17160   } Diagnoser(DiagID);
17161 
17162   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17163 }
17164 
17165 Sema::SemaDiagnosticBuilder
17166 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17167                                              QualType T) {
17168   return diagnoseNotICE(S, Loc);
17169 }
17170 
17171 Sema::SemaDiagnosticBuilder
17172 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17173   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17174 }
17175 
17176 ExprResult
17177 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17178                                       VerifyICEDiagnoser &Diagnoser,
17179                                       AllowFoldKind CanFold) {
17180   SourceLocation DiagLoc = E->getBeginLoc();
17181 
17182   if (getLangOpts().CPlusPlus11) {
17183     // C++11 [expr.const]p5:
17184     //   If an expression of literal class type is used in a context where an
17185     //   integral constant expression is required, then that class type shall
17186     //   have a single non-explicit conversion function to an integral or
17187     //   unscoped enumeration type
17188     ExprResult Converted;
17189     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17190       VerifyICEDiagnoser &BaseDiagnoser;
17191     public:
17192       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17193           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17194                                 BaseDiagnoser.Suppress, true),
17195             BaseDiagnoser(BaseDiagnoser) {}
17196 
17197       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17198                                            QualType T) override {
17199         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17200       }
17201 
17202       SemaDiagnosticBuilder diagnoseIncomplete(
17203           Sema &S, SourceLocation Loc, QualType T) override {
17204         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17205       }
17206 
17207       SemaDiagnosticBuilder diagnoseExplicitConv(
17208           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17209         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17210       }
17211 
17212       SemaDiagnosticBuilder noteExplicitConv(
17213           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17214         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17215                  << ConvTy->isEnumeralType() << ConvTy;
17216       }
17217 
17218       SemaDiagnosticBuilder diagnoseAmbiguous(
17219           Sema &S, SourceLocation Loc, QualType T) override {
17220         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17221       }
17222 
17223       SemaDiagnosticBuilder noteAmbiguous(
17224           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17225         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17226                  << ConvTy->isEnumeralType() << ConvTy;
17227       }
17228 
17229       SemaDiagnosticBuilder diagnoseConversion(
17230           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17231         llvm_unreachable("conversion functions are permitted");
17232       }
17233     } ConvertDiagnoser(Diagnoser);
17234 
17235     Converted = PerformContextualImplicitConversion(DiagLoc, E,
17236                                                     ConvertDiagnoser);
17237     if (Converted.isInvalid())
17238       return Converted;
17239     E = Converted.get();
17240     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
17241       return ExprError();
17242   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17243     // An ICE must be of integral or unscoped enumeration type.
17244     if (!Diagnoser.Suppress)
17245       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17246           << E->getSourceRange();
17247     return ExprError();
17248   }
17249 
17250   ExprResult RValueExpr = DefaultLvalueConversion(E);
17251   if (RValueExpr.isInvalid())
17252     return ExprError();
17253 
17254   E = RValueExpr.get();
17255 
17256   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17257   // in the non-ICE case.
17258   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
17259     if (Result)
17260       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
17261     if (!isa<ConstantExpr>(E))
17262       E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
17263                  : ConstantExpr::Create(Context, E);
17264     return E;
17265   }
17266 
17267   Expr::EvalResult EvalResult;
17268   SmallVector<PartialDiagnosticAt, 8> Notes;
17269   EvalResult.Diag = &Notes;
17270 
17271   // Try to evaluate the expression, and produce diagnostics explaining why it's
17272   // not a constant expression as a side-effect.
17273   bool Folded =
17274       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17275       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
17276 
17277   if (!isa<ConstantExpr>(E))
17278     E = ConstantExpr::Create(Context, E, EvalResult.Val);
17279 
17280   // In C++11, we can rely on diagnostics being produced for any expression
17281   // which is not a constant expression. If no diagnostics were produced, then
17282   // this is a constant expression.
17283   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17284     if (Result)
17285       *Result = EvalResult.Val.getInt();
17286     return E;
17287   }
17288 
17289   // If our only note is the usual "invalid subexpression" note, just point
17290   // the caret at its location rather than producing an essentially
17291   // redundant note.
17292   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17293         diag::note_invalid_subexpr_in_const_expr) {
17294     DiagLoc = Notes[0].first;
17295     Notes.clear();
17296   }
17297 
17298   if (!Folded || !CanFold) {
17299     if (!Diagnoser.Suppress) {
17300       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17301       for (const PartialDiagnosticAt &Note : Notes)
17302         Diag(Note.first, Note.second);
17303     }
17304 
17305     return ExprError();
17306   }
17307 
17308   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17309   for (const PartialDiagnosticAt &Note : Notes)
17310     Diag(Note.first, Note.second);
17311 
17312   if (Result)
17313     *Result = EvalResult.Val.getInt();
17314   return E;
17315 }
17316 
17317 namespace {
17318   // Handle the case where we conclude a expression which we speculatively
17319   // considered to be unevaluated is actually evaluated.
17320   class TransformToPE : public TreeTransform<TransformToPE> {
17321     typedef TreeTransform<TransformToPE> BaseTransform;
17322 
17323   public:
17324     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17325 
17326     // Make sure we redo semantic analysis
17327     bool AlwaysRebuild() { return true; }
17328     bool ReplacingOriginal() { return true; }
17329 
17330     // We need to special-case DeclRefExprs referring to FieldDecls which
17331     // are not part of a member pointer formation; normal TreeTransforming
17332     // doesn't catch this case because of the way we represent them in the AST.
17333     // FIXME: This is a bit ugly; is it really the best way to handle this
17334     // case?
17335     //
17336     // Error on DeclRefExprs referring to FieldDecls.
17337     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17338       if (isa<FieldDecl>(E->getDecl()) &&
17339           !SemaRef.isUnevaluatedContext())
17340         return SemaRef.Diag(E->getLocation(),
17341                             diag::err_invalid_non_static_member_use)
17342             << E->getDecl() << E->getSourceRange();
17343 
17344       return BaseTransform::TransformDeclRefExpr(E);
17345     }
17346 
17347     // Exception: filter out member pointer formation
17348     ExprResult TransformUnaryOperator(UnaryOperator *E) {
17349       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17350         return E;
17351 
17352       return BaseTransform::TransformUnaryOperator(E);
17353     }
17354 
17355     // The body of a lambda-expression is in a separate expression evaluation
17356     // context so never needs to be transformed.
17357     // FIXME: Ideally we wouldn't transform the closure type either, and would
17358     // just recreate the capture expressions and lambda expression.
17359     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17360       return SkipLambdaBody(E, Body);
17361     }
17362   };
17363 }
17364 
17365 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
17366   assert(isUnevaluatedContext() &&
17367          "Should only transform unevaluated expressions");
17368   ExprEvalContexts.back().Context =
17369       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17370   if (isUnevaluatedContext())
17371     return E;
17372   return TransformToPE(*this).TransformExpr(E);
17373 }
17374 
17375 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
17376   assert(isUnevaluatedContext() &&
17377          "Should only transform unevaluated expressions");
17378   ExprEvalContexts.back().Context =
17379       ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
17380   if (isUnevaluatedContext())
17381     return TInfo;
17382   return TransformToPE(*this).TransformType(TInfo);
17383 }
17384 
17385 void
17386 Sema::PushExpressionEvaluationContext(
17387     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17388     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17389   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17390                                 LambdaContextDecl, ExprContext);
17391 
17392   // Discarded statements and immediate contexts nested in other
17393   // discarded statements or immediate context are themselves
17394   // a discarded statement or an immediate context, respectively.
17395   ExprEvalContexts.back().InDiscardedStatement =
17396       ExprEvalContexts[ExprEvalContexts.size() - 2]
17397           .isDiscardedStatementContext();
17398   ExprEvalContexts.back().InImmediateFunctionContext =
17399       ExprEvalContexts[ExprEvalContexts.size() - 2]
17400           .isImmediateFunctionContext();
17401 
17402   Cleanup.reset();
17403   if (!MaybeODRUseExprs.empty())
17404     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17405 }
17406 
17407 void
17408 Sema::PushExpressionEvaluationContext(
17409     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
17410     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17411   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17412   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17413 }
17414 
17415 namespace {
17416 
17417 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17418   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17419   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17420     if (E->getOpcode() == UO_Deref)
17421       return CheckPossibleDeref(S, E->getSubExpr());
17422   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17423     return CheckPossibleDeref(S, E->getBase());
17424   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17425     return CheckPossibleDeref(S, E->getBase());
17426   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17427     QualType Inner;
17428     QualType Ty = E->getType();
17429     if (const auto *Ptr = Ty->getAs<PointerType>())
17430       Inner = Ptr->getPointeeType();
17431     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17432       Inner = Arr->getElementType();
17433     else
17434       return nullptr;
17435 
17436     if (Inner->hasAttr(attr::NoDeref))
17437       return E;
17438   }
17439   return nullptr;
17440 }
17441 
17442 } // namespace
17443 
17444 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
17445   for (const Expr *E : Rec.PossibleDerefs) {
17446     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17447     if (DeclRef) {
17448       const ValueDecl *Decl = DeclRef->getDecl();
17449       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17450           << Decl->getName() << E->getSourceRange();
17451       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17452     } else {
17453       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17454           << E->getSourceRange();
17455     }
17456   }
17457   Rec.PossibleDerefs.clear();
17458 }
17459 
17460 /// Check whether E, which is either a discarded-value expression or an
17461 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17462 /// and if so, remove it from the list of volatile-qualified assignments that
17463 /// we are going to warn are deprecated.
17464 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
17465   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
17466     return;
17467 
17468   // Note: ignoring parens here is not justified by the standard rules, but
17469   // ignoring parentheses seems like a more reasonable approach, and this only
17470   // drives a deprecation warning so doesn't affect conformance.
17471   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17472     if (BO->getOpcode() == BO_Assign) {
17473       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17474       llvm::erase_value(LHSs, BO->getLHS());
17475     }
17476   }
17477 }
17478 
17479 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
17480   if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17481       !Decl->isConsteval() || isConstantEvaluated() ||
17482       RebuildingImmediateInvocation || isImmediateFunctionContext())
17483     return E;
17484 
17485   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17486   /// It's OK if this fails; we'll also remove this in
17487   /// HandleImmediateInvocations, but catching it here allows us to avoid
17488   /// walking the AST looking for it in simple cases.
17489   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17490     if (auto *DeclRef =
17491             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17492       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17493 
17494   E = MaybeCreateExprWithCleanups(E);
17495 
17496   ConstantExpr *Res = ConstantExpr::Create(
17497       getASTContext(), E.get(),
17498       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17499                                    getASTContext()),
17500       /*IsImmediateInvocation*/ true);
17501   /// Value-dependent constant expressions should not be immediately
17502   /// evaluated until they are instantiated.
17503   if (!Res->isValueDependent())
17504     ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17505   return Res;
17506 }
17507 
17508 static void EvaluateAndDiagnoseImmediateInvocation(
17509     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
17510   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
17511   Expr::EvalResult Eval;
17512   Eval.Diag = &Notes;
17513   ConstantExpr *CE = Candidate.getPointer();
17514   bool Result = CE->EvaluateAsConstantExpr(
17515       Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17516   if (!Result || !Notes.empty()) {
17517     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17518     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17519       InnerExpr = FunctionalCast->getSubExpr();
17520     FunctionDecl *FD = nullptr;
17521     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17522       FD = cast<FunctionDecl>(Call->getCalleeDecl());
17523     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17524       FD = Call->getConstructor();
17525     else
17526       llvm_unreachable("unhandled decl kind");
17527     assert(FD->isConsteval());
17528     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
17529     for (auto &Note : Notes)
17530       SemaRef.Diag(Note.first, Note.second);
17531     return;
17532   }
17533   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
17534 }
17535 
17536 static void RemoveNestedImmediateInvocation(
17537     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
17538     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
17539   struct ComplexRemove : TreeTransform<ComplexRemove> {
17540     using Base = TreeTransform<ComplexRemove>;
17541     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17542     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
17543     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
17544         CurrentII;
17545     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17546                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
17547                   SmallVector<Sema::ImmediateInvocationCandidate,
17548                               4>::reverse_iterator Current)
17549         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17550     void RemoveImmediateInvocation(ConstantExpr* E) {
17551       auto It = std::find_if(CurrentII, IISet.rend(),
17552                              [E](Sema::ImmediateInvocationCandidate Elem) {
17553                                return Elem.getPointer() == E;
17554                              });
17555       assert(It != IISet.rend() &&
17556              "ConstantExpr marked IsImmediateInvocation should "
17557              "be present");
17558       It->setInt(1); // Mark as deleted
17559     }
17560     ExprResult TransformConstantExpr(ConstantExpr *E) {
17561       if (!E->isImmediateInvocation())
17562         return Base::TransformConstantExpr(E);
17563       RemoveImmediateInvocation(E);
17564       return Base::TransformExpr(E->getSubExpr());
17565     }
17566     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17567     /// we need to remove its DeclRefExpr from the DRSet.
17568     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17569       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17570       return Base::TransformCXXOperatorCallExpr(E);
17571     }
17572     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
17573     /// here.
17574     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17575       if (!Init)
17576         return Init;
17577       /// ConstantExpr are the first layer of implicit node to be removed so if
17578       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17579       if (auto *CE = dyn_cast<ConstantExpr>(Init))
17580         if (CE->isImmediateInvocation())
17581           RemoveImmediateInvocation(CE);
17582       return Base::TransformInitializer(Init, NotCopyInit);
17583     }
17584     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17585       DRSet.erase(E);
17586       return E;
17587     }
17588     bool AlwaysRebuild() { return false; }
17589     bool ReplacingOriginal() { return true; }
17590     bool AllowSkippingCXXConstructExpr() {
17591       bool Res = AllowSkippingFirstCXXConstructExpr;
17592       AllowSkippingFirstCXXConstructExpr = true;
17593       return Res;
17594     }
17595     bool AllowSkippingFirstCXXConstructExpr = true;
17596   } Transformer(SemaRef, Rec.ReferenceToConsteval,
17597                 Rec.ImmediateInvocationCandidates, It);
17598 
17599   /// CXXConstructExpr with a single argument are getting skipped by
17600   /// TreeTransform in some situtation because they could be implicit. This
17601   /// can only occur for the top-level CXXConstructExpr because it is used
17602   /// nowhere in the expression being transformed therefore will not be rebuilt.
17603   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17604   /// skipping the first CXXConstructExpr.
17605   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17606     Transformer.AllowSkippingFirstCXXConstructExpr = false;
17607 
17608   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17609   assert(Res.isUsable());
17610   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
17611   It->getPointer()->setSubExpr(Res.get());
17612 }
17613 
17614 static void
17615 HandleImmediateInvocations(Sema &SemaRef,
17616                            Sema::ExpressionEvaluationContextRecord &Rec) {
17617   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17618        Rec.ReferenceToConsteval.size() == 0) ||
17619       SemaRef.RebuildingImmediateInvocation)
17620     return;
17621 
17622   /// When we have more then 1 ImmediateInvocationCandidates we need to check
17623   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
17624   /// need to remove ReferenceToConsteval in the immediate invocation.
17625   if (Rec.ImmediateInvocationCandidates.size() > 1) {
17626 
17627     /// Prevent sema calls during the tree transform from adding pointers that
17628     /// are already in the sets.
17629     llvm::SaveAndRestore<bool> DisableIITracking(
17630         SemaRef.RebuildingImmediateInvocation, true);
17631 
17632     /// Prevent diagnostic during tree transfrom as they are duplicates
17633     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
17634 
17635     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17636          It != Rec.ImmediateInvocationCandidates.rend(); It++)
17637       if (!It->getInt())
17638         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
17639   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17640              Rec.ReferenceToConsteval.size()) {
17641     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17642       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17643       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17644       bool VisitDeclRefExpr(DeclRefExpr *E) {
17645         DRSet.erase(E);
17646         return DRSet.size();
17647       }
17648     } Visitor(Rec.ReferenceToConsteval);
17649     Visitor.TraverseStmt(
17650         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17651   }
17652   for (auto CE : Rec.ImmediateInvocationCandidates)
17653     if (!CE.getInt())
17654       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
17655   for (auto DR : Rec.ReferenceToConsteval) {
17656     auto *FD = cast<FunctionDecl>(DR->getDecl());
17657     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17658         << FD;
17659     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
17660   }
17661 }
17662 
17663 void Sema::PopExpressionEvaluationContext() {
17664   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
17665   unsigned NumTypos = Rec.NumTypos;
17666 
17667   if (!Rec.Lambdas.empty()) {
17668     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
17669     if (!getLangOpts().CPlusPlus20 &&
17670         (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17671          Rec.isUnevaluated() ||
17672          (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
17673       unsigned D;
17674       if (Rec.isUnevaluated()) {
17675         // C++11 [expr.prim.lambda]p2:
17676         //   A lambda-expression shall not appear in an unevaluated operand
17677         //   (Clause 5).
17678         D = diag::err_lambda_unevaluated_operand;
17679       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17680         // C++1y [expr.const]p2:
17681         //   A conditional-expression e is a core constant expression unless the
17682         //   evaluation of e, following the rules of the abstract machine, would
17683         //   evaluate [...] a lambda-expression.
17684         D = diag::err_lambda_in_constant_expression;
17685       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17686         // C++17 [expr.prim.lamda]p2:
17687         // A lambda-expression shall not appear [...] in a template-argument.
17688         D = diag::err_lambda_in_invalid_context;
17689       } else
17690         llvm_unreachable("Couldn't infer lambda error message.");
17691 
17692       for (const auto *L : Rec.Lambdas)
17693         Diag(L->getBeginLoc(), D);
17694     }
17695   }
17696 
17697   WarnOnPendingNoDerefs(Rec);
17698   HandleImmediateInvocations(*this, Rec);
17699 
17700   // Warn on any volatile-qualified simple-assignments that are not discarded-
17701   // value expressions nor unevaluated operands (those cases get removed from
17702   // this list by CheckUnusedVolatileAssignment).
17703   for (auto *BO : Rec.VolatileAssignmentLHSs)
17704     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17705         << BO->getType();
17706 
17707   // When are coming out of an unevaluated context, clear out any
17708   // temporaries that we may have created as part of the evaluation of
17709   // the expression in that context: they aren't relevant because they
17710   // will never be constructed.
17711   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17712     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
17713                              ExprCleanupObjects.end());
17714     Cleanup = Rec.ParentCleanup;
17715     CleanupVarDeclMarking();
17716     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
17717   // Otherwise, merge the contexts together.
17718   } else {
17719     Cleanup.mergeFrom(Rec.ParentCleanup);
17720     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17721                             Rec.SavedMaybeODRUseExprs.end());
17722   }
17723 
17724   // Pop the current expression evaluation context off the stack.
17725   ExprEvalContexts.pop_back();
17726 
17727   // The global expression evaluation context record is never popped.
17728   ExprEvalContexts.back().NumTypos += NumTypos;
17729 }
17730 
17731 void Sema::DiscardCleanupsInEvaluationContext() {
17732   ExprCleanupObjects.erase(
17733          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17734          ExprCleanupObjects.end());
17735   Cleanup.reset();
17736   MaybeODRUseExprs.clear();
17737 }
17738 
17739 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
17740   ExprResult Result = CheckPlaceholderExpr(E);
17741   if (Result.isInvalid())
17742     return ExprError();
17743   E = Result.get();
17744   if (!E->getType()->isVariablyModifiedType())
17745     return E;
17746   return TransformToPotentiallyEvaluated(E);
17747 }
17748 
17749 /// Are we in a context that is potentially constant evaluated per C++20
17750 /// [expr.const]p12?
17751 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
17752   /// C++2a [expr.const]p12:
17753   //   An expression or conversion is potentially constant evaluated if it is
17754   switch (SemaRef.ExprEvalContexts.back().Context) {
17755     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17756     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17757 
17758       // -- a manifestly constant-evaluated expression,
17759     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17760     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17761     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17762       // -- a potentially-evaluated expression,
17763     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17764       // -- an immediate subexpression of a braced-init-list,
17765 
17766       // -- [FIXME] an expression of the form & cast-expression that occurs
17767       //    within a templated entity
17768       // -- a subexpression of one of the above that is not a subexpression of
17769       // a nested unevaluated operand.
17770       return true;
17771 
17772     case Sema::ExpressionEvaluationContext::Unevaluated:
17773     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17774       // Expressions in this context are never evaluated.
17775       return false;
17776   }
17777   llvm_unreachable("Invalid context");
17778 }
17779 
17780 /// Return true if this function has a calling convention that requires mangling
17781 /// in the size of the parameter pack.
17782 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
17783   // These manglings don't do anything on non-Windows or non-x86 platforms, so
17784   // we don't need parameter type sizes.
17785   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17786   if (!TT.isOSWindows() || !TT.isX86())
17787     return false;
17788 
17789   // If this is C++ and this isn't an extern "C" function, parameters do not
17790   // need to be complete. In this case, C++ mangling will apply, which doesn't
17791   // use the size of the parameters.
17792   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17793     return false;
17794 
17795   // Stdcall, fastcall, and vectorcall need this special treatment.
17796   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17797   switch (CC) {
17798   case CC_X86StdCall:
17799   case CC_X86FastCall:
17800   case CC_X86VectorCall:
17801     return true;
17802   default:
17803     break;
17804   }
17805   return false;
17806 }
17807 
17808 /// Require that all of the parameter types of function be complete. Normally,
17809 /// parameter types are only required to be complete when a function is called
17810 /// or defined, but to mangle functions with certain calling conventions, the
17811 /// mangler needs to know the size of the parameter list. In this situation,
17812 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17813 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17814 /// result in a linker error. Clang doesn't implement this behavior, and instead
17815 /// attempts to error at compile time.
17816 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
17817                                                   SourceLocation Loc) {
17818   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17819     FunctionDecl *FD;
17820     ParmVarDecl *Param;
17821 
17822   public:
17823     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17824         : FD(FD), Param(Param) {}
17825 
17826     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17827       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17828       StringRef CCName;
17829       switch (CC) {
17830       case CC_X86StdCall:
17831         CCName = "stdcall";
17832         break;
17833       case CC_X86FastCall:
17834         CCName = "fastcall";
17835         break;
17836       case CC_X86VectorCall:
17837         CCName = "vectorcall";
17838         break;
17839       default:
17840         llvm_unreachable("CC does not need mangling");
17841       }
17842 
17843       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17844           << Param->getDeclName() << FD->getDeclName() << CCName;
17845     }
17846   };
17847 
17848   for (ParmVarDecl *Param : FD->parameters()) {
17849     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17850     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17851   }
17852 }
17853 
17854 namespace {
17855 enum class OdrUseContext {
17856   /// Declarations in this context are not odr-used.
17857   None,
17858   /// Declarations in this context are formally odr-used, but this is a
17859   /// dependent context.
17860   Dependent,
17861   /// Declarations in this context are odr-used but not actually used (yet).
17862   FormallyOdrUsed,
17863   /// Declarations in this context are used.
17864   Used
17865 };
17866 }
17867 
17868 /// Are we within a context in which references to resolved functions or to
17869 /// variables result in odr-use?
17870 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17871   OdrUseContext Result;
17872 
17873   switch (SemaRef.ExprEvalContexts.back().Context) {
17874     case Sema::ExpressionEvaluationContext::Unevaluated:
17875     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17876     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17877       return OdrUseContext::None;
17878 
17879     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17880     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17881     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17882       Result = OdrUseContext::Used;
17883       break;
17884 
17885     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17886       Result = OdrUseContext::FormallyOdrUsed;
17887       break;
17888 
17889     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17890       // A default argument formally results in odr-use, but doesn't actually
17891       // result in a use in any real sense until it itself is used.
17892       Result = OdrUseContext::FormallyOdrUsed;
17893       break;
17894   }
17895 
17896   if (SemaRef.CurContext->isDependentContext())
17897     return OdrUseContext::Dependent;
17898 
17899   return Result;
17900 }
17901 
17902 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17903   if (!Func->isConstexpr())
17904     return false;
17905 
17906   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17907     return true;
17908   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17909   return CCD && CCD->getInheritedConstructor();
17910 }
17911 
17912 /// Mark a function referenced, and check whether it is odr-used
17913 /// (C++ [basic.def.odr]p2, C99 6.9p3)
17914 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17915                                   bool MightBeOdrUse) {
17916   assert(Func && "No function?");
17917 
17918   Func->setReferenced();
17919 
17920   // Recursive functions aren't really used until they're used from some other
17921   // context.
17922   bool IsRecursiveCall = CurContext == Func;
17923 
17924   // C++11 [basic.def.odr]p3:
17925   //   A function whose name appears as a potentially-evaluated expression is
17926   //   odr-used if it is the unique lookup result or the selected member of a
17927   //   set of overloaded functions [...].
17928   //
17929   // We (incorrectly) mark overload resolution as an unevaluated context, so we
17930   // can just check that here.
17931   OdrUseContext OdrUse =
17932       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17933   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17934     OdrUse = OdrUseContext::FormallyOdrUsed;
17935 
17936   // Trivial default constructors and destructors are never actually used.
17937   // FIXME: What about other special members?
17938   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17939       OdrUse == OdrUseContext::Used) {
17940     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17941       if (Constructor->isDefaultConstructor())
17942         OdrUse = OdrUseContext::FormallyOdrUsed;
17943     if (isa<CXXDestructorDecl>(Func))
17944       OdrUse = OdrUseContext::FormallyOdrUsed;
17945   }
17946 
17947   // C++20 [expr.const]p12:
17948   //   A function [...] is needed for constant evaluation if it is [...] a
17949   //   constexpr function that is named by an expression that is potentially
17950   //   constant evaluated
17951   bool NeededForConstantEvaluation =
17952       isPotentiallyConstantEvaluatedContext(*this) &&
17953       isImplicitlyDefinableConstexprFunction(Func);
17954 
17955   // Determine whether we require a function definition to exist, per
17956   // C++11 [temp.inst]p3:
17957   //   Unless a function template specialization has been explicitly
17958   //   instantiated or explicitly specialized, the function template
17959   //   specialization is implicitly instantiated when the specialization is
17960   //   referenced in a context that requires a function definition to exist.
17961   // C++20 [temp.inst]p7:
17962   //   The existence of a definition of a [...] function is considered to
17963   //   affect the semantics of the program if the [...] function is needed for
17964   //   constant evaluation by an expression
17965   // C++20 [basic.def.odr]p10:
17966   //   Every program shall contain exactly one definition of every non-inline
17967   //   function or variable that is odr-used in that program outside of a
17968   //   discarded statement
17969   // C++20 [special]p1:
17970   //   The implementation will implicitly define [defaulted special members]
17971   //   if they are odr-used or needed for constant evaluation.
17972   //
17973   // Note that we skip the implicit instantiation of templates that are only
17974   // used in unused default arguments or by recursive calls to themselves.
17975   // This is formally non-conforming, but seems reasonable in practice.
17976   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
17977                                              NeededForConstantEvaluation);
17978 
17979   // C++14 [temp.expl.spec]p6:
17980   //   If a template [...] is explicitly specialized then that specialization
17981   //   shall be declared before the first use of that specialization that would
17982   //   cause an implicit instantiation to take place, in every translation unit
17983   //   in which such a use occurs
17984   if (NeedDefinition &&
17985       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17986        Func->getMemberSpecializationInfo()))
17987     checkSpecializationReachability(Loc, Func);
17988 
17989   if (getLangOpts().CUDA)
17990     CheckCUDACall(Loc, Func);
17991 
17992   if (getLangOpts().SYCLIsDevice)
17993     checkSYCLDeviceFunction(Loc, Func);
17994 
17995   // If we need a definition, try to create one.
17996   if (NeedDefinition && !Func->getBody()) {
17997     runWithSufficientStackSpace(Loc, [&] {
17998       if (CXXConstructorDecl *Constructor =
17999               dyn_cast<CXXConstructorDecl>(Func)) {
18000         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18001         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18002           if (Constructor->isDefaultConstructor()) {
18003             if (Constructor->isTrivial() &&
18004                 !Constructor->hasAttr<DLLExportAttr>())
18005               return;
18006             DefineImplicitDefaultConstructor(Loc, Constructor);
18007           } else if (Constructor->isCopyConstructor()) {
18008             DefineImplicitCopyConstructor(Loc, Constructor);
18009           } else if (Constructor->isMoveConstructor()) {
18010             DefineImplicitMoveConstructor(Loc, Constructor);
18011           }
18012         } else if (Constructor->getInheritedConstructor()) {
18013           DefineInheritingConstructor(Loc, Constructor);
18014         }
18015       } else if (CXXDestructorDecl *Destructor =
18016                      dyn_cast<CXXDestructorDecl>(Func)) {
18017         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18018         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18019           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18020             return;
18021           DefineImplicitDestructor(Loc, Destructor);
18022         }
18023         if (Destructor->isVirtual() && getLangOpts().AppleKext)
18024           MarkVTableUsed(Loc, Destructor->getParent());
18025       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18026         if (MethodDecl->isOverloadedOperator() &&
18027             MethodDecl->getOverloadedOperator() == OO_Equal) {
18028           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18029           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18030             if (MethodDecl->isCopyAssignmentOperator())
18031               DefineImplicitCopyAssignment(Loc, MethodDecl);
18032             else if (MethodDecl->isMoveAssignmentOperator())
18033               DefineImplicitMoveAssignment(Loc, MethodDecl);
18034           }
18035         } else if (isa<CXXConversionDecl>(MethodDecl) &&
18036                    MethodDecl->getParent()->isLambda()) {
18037           CXXConversionDecl *Conversion =
18038               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18039           if (Conversion->isLambdaToBlockPointerConversion())
18040             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
18041           else
18042             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
18043         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18044           MarkVTableUsed(Loc, MethodDecl->getParent());
18045       }
18046 
18047       if (Func->isDefaulted() && !Func->isDeleted()) {
18048         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
18049         if (DCK != DefaultedComparisonKind::None)
18050           DefineDefaultedComparison(Loc, Func, DCK);
18051       }
18052 
18053       // Implicit instantiation of function templates and member functions of
18054       // class templates.
18055       if (Func->isImplicitlyInstantiable()) {
18056         TemplateSpecializationKind TSK =
18057             Func->getTemplateSpecializationKindForInstantiation();
18058         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18059         bool FirstInstantiation = PointOfInstantiation.isInvalid();
18060         if (FirstInstantiation) {
18061           PointOfInstantiation = Loc;
18062           if (auto *MSI = Func->getMemberSpecializationInfo())
18063             MSI->setPointOfInstantiation(Loc);
18064             // FIXME: Notify listener.
18065           else
18066             Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18067         } else if (TSK != TSK_ImplicitInstantiation) {
18068           // Use the point of use as the point of instantiation, instead of the
18069           // point of explicit instantiation (which we track as the actual point
18070           // of instantiation). This gives better backtraces in diagnostics.
18071           PointOfInstantiation = Loc;
18072         }
18073 
18074         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18075             Func->isConstexpr()) {
18076           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18077               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18078               CodeSynthesisContexts.size())
18079             PendingLocalImplicitInstantiations.push_back(
18080                 std::make_pair(Func, PointOfInstantiation));
18081           else if (Func->isConstexpr())
18082             // Do not defer instantiations of constexpr functions, to avoid the
18083             // expression evaluator needing to call back into Sema if it sees a
18084             // call to such a function.
18085             InstantiateFunctionDefinition(PointOfInstantiation, Func);
18086           else {
18087             Func->setInstantiationIsPending(true);
18088             PendingInstantiations.push_back(
18089                 std::make_pair(Func, PointOfInstantiation));
18090             // Notify the consumer that a function was implicitly instantiated.
18091             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
18092           }
18093         }
18094       } else {
18095         // Walk redefinitions, as some of them may be instantiable.
18096         for (auto i : Func->redecls()) {
18097           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18098             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18099         }
18100       }
18101     });
18102   }
18103 
18104   // C++14 [except.spec]p17:
18105   //   An exception-specification is considered to be needed when:
18106   //   - the function is odr-used or, if it appears in an unevaluated operand,
18107   //     would be odr-used if the expression were potentially-evaluated;
18108   //
18109   // Note, we do this even if MightBeOdrUse is false. That indicates that the
18110   // function is a pure virtual function we're calling, and in that case the
18111   // function was selected by overload resolution and we need to resolve its
18112   // exception specification for a different reason.
18113   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18114   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
18115     ResolveExceptionSpec(Loc, FPT);
18116 
18117   // If this is the first "real" use, act on that.
18118   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18119     // Keep track of used but undefined functions.
18120     if (!Func->isDefined()) {
18121       if (mightHaveNonExternalLinkage(Func))
18122         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18123       else if (Func->getMostRecentDecl()->isInlined() &&
18124                !LangOpts.GNUInline &&
18125                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18126         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18127       else if (isExternalWithNoLinkageType(Func))
18128         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18129     }
18130 
18131     // Some x86 Windows calling conventions mangle the size of the parameter
18132     // pack into the name. Computing the size of the parameters requires the
18133     // parameter types to be complete. Check that now.
18134     if (funcHasParameterSizeMangling(*this, Func))
18135       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
18136 
18137     // In the MS C++ ABI, the compiler emits destructor variants where they are
18138     // used. If the destructor is used here but defined elsewhere, mark the
18139     // virtual base destructors referenced. If those virtual base destructors
18140     // are inline, this will ensure they are defined when emitting the complete
18141     // destructor variant. This checking may be redundant if the destructor is
18142     // provided later in this TU.
18143     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18144       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18145         CXXRecordDecl *Parent = Dtor->getParent();
18146         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18147           CheckCompleteDestructorVariant(Loc, Dtor);
18148       }
18149     }
18150 
18151     Func->markUsed(Context);
18152   }
18153 }
18154 
18155 /// Directly mark a variable odr-used. Given a choice, prefer to use
18156 /// MarkVariableReferenced since it does additional checks and then
18157 /// calls MarkVarDeclODRUsed.
18158 /// If the variable must be captured:
18159 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18160 ///  - else capture it in the DeclContext that maps to the
18161 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18162 static void
18163 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
18164                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18165   // Keep track of used but undefined variables.
18166   // FIXME: We shouldn't suppress this warning for static data members.
18167   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
18168       (!Var->isExternallyVisible() || Var->isInline() ||
18169        SemaRef.isExternalWithNoLinkageType(Var)) &&
18170       !(Var->isStaticDataMember() && Var->hasInit())) {
18171     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
18172     if (old.isInvalid())
18173       old = Loc;
18174   }
18175   QualType CaptureType, DeclRefType;
18176   if (SemaRef.LangOpts.OpenMP)
18177     SemaRef.tryCaptureOpenMPLambdas(Var);
18178   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
18179     /*EllipsisLoc*/ SourceLocation(),
18180     /*BuildAndDiagnose*/ true,
18181     CaptureType, DeclRefType,
18182     FunctionScopeIndexToStopAt);
18183 
18184   if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18185     auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18186     auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
18187     auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
18188     if (VarTarget == Sema::CVT_Host &&
18189         (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
18190          UserTarget == Sema::CFT_Global)) {
18191       // Diagnose ODR-use of host global variables in device functions.
18192       // Reference of device global variables in host functions is allowed
18193       // through shadow variables therefore it is not diagnosed.
18194       if (SemaRef.LangOpts.CUDAIsDevice) {
18195         SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18196             << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
18197         SemaRef.targetDiag(Var->getLocation(),
18198                            Var->getType().isConstQualified()
18199                                ? diag::note_cuda_const_var_unpromoted
18200                                : diag::note_cuda_host_var);
18201       }
18202     } else if (VarTarget == Sema::CVT_Device &&
18203                (UserTarget == Sema::CFT_Host ||
18204                 UserTarget == Sema::CFT_HostDevice)) {
18205       // Record a CUDA/HIP device side variable if it is ODR-used
18206       // by host code. This is done conservatively, when the variable is
18207       // referenced in any of the following contexts:
18208       //   - a non-function context
18209       //   - a host function
18210       //   - a host device function
18211       // This makes the ODR-use of the device side variable by host code to
18212       // be visible in the device compilation for the compiler to be able to
18213       // emit template variables instantiated by host code only and to
18214       // externalize the static device side variable ODR-used by host code.
18215       if (!Var->hasExternalStorage())
18216         SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
18217       else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
18218         SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
18219     }
18220   }
18221 
18222   Var->markUsed(SemaRef.Context);
18223 }
18224 
18225 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
18226                                              SourceLocation Loc,
18227                                              unsigned CapturingScopeIndex) {
18228   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18229 }
18230 
18231 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
18232                                                ValueDecl *var) {
18233   DeclContext *VarDC = var->getDeclContext();
18234 
18235   //  If the parameter still belongs to the translation unit, then
18236   //  we're actually just using one parameter in the declaration of
18237   //  the next.
18238   if (isa<ParmVarDecl>(var) &&
18239       isa<TranslationUnitDecl>(VarDC))
18240     return;
18241 
18242   // For C code, don't diagnose about capture if we're not actually in code
18243   // right now; it's impossible to write a non-constant expression outside of
18244   // function context, so we'll get other (more useful) diagnostics later.
18245   //
18246   // For C++, things get a bit more nasty... it would be nice to suppress this
18247   // diagnostic for certain cases like using a local variable in an array bound
18248   // for a member of a local class, but the correct predicate is not obvious.
18249   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18250     return;
18251 
18252   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18253   unsigned ContextKind = 3; // unknown
18254   if (isa<CXXMethodDecl>(VarDC) &&
18255       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18256     ContextKind = 2;
18257   } else if (isa<FunctionDecl>(VarDC)) {
18258     ContextKind = 0;
18259   } else if (isa<BlockDecl>(VarDC)) {
18260     ContextKind = 1;
18261   }
18262 
18263   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18264     << var << ValueKind << ContextKind << VarDC;
18265   S.Diag(var->getLocation(), diag::note_entity_declared_at)
18266       << var;
18267 
18268   // FIXME: Add additional diagnostic info about class etc. which prevents
18269   // capture.
18270 }
18271 
18272 
18273 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
18274                                       bool &SubCapturesAreNested,
18275                                       QualType &CaptureType,
18276                                       QualType &DeclRefType) {
18277    // Check whether we've already captured it.
18278   if (CSI->CaptureMap.count(Var)) {
18279     // If we found a capture, any subcaptures are nested.
18280     SubCapturesAreNested = true;
18281 
18282     // Retrieve the capture type for this variable.
18283     CaptureType = CSI->getCapture(Var).getCaptureType();
18284 
18285     // Compute the type of an expression that refers to this variable.
18286     DeclRefType = CaptureType.getNonReferenceType();
18287 
18288     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18289     // are mutable in the sense that user can change their value - they are
18290     // private instances of the captured declarations.
18291     const Capture &Cap = CSI->getCapture(Var);
18292     if (Cap.isCopyCapture() &&
18293         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
18294         !(isa<CapturedRegionScopeInfo>(CSI) &&
18295           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18296       DeclRefType.addConst();
18297     return true;
18298   }
18299   return false;
18300 }
18301 
18302 // Only block literals, captured statements, and lambda expressions can
18303 // capture; other scopes don't work.
18304 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
18305                                  SourceLocation Loc,
18306                                  const bool Diagnose, Sema &S) {
18307   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18308     return getLambdaAwareParentOfDeclContext(DC);
18309   else if (Var->hasLocalStorage()) {
18310     if (Diagnose)
18311        diagnoseUncapturableValueReference(S, Loc, Var);
18312   }
18313   return nullptr;
18314 }
18315 
18316 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18317 // certain types of variables (unnamed, variably modified types etc.)
18318 // so check for eligibility.
18319 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
18320                                  SourceLocation Loc,
18321                                  const bool Diagnose, Sema &S) {
18322 
18323   bool IsBlock = isa<BlockScopeInfo>(CSI);
18324   bool IsLambda = isa<LambdaScopeInfo>(CSI);
18325 
18326   // Lambdas are not allowed to capture unnamed variables
18327   // (e.g. anonymous unions).
18328   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18329   // assuming that's the intent.
18330   if (IsLambda && !Var->getDeclName()) {
18331     if (Diagnose) {
18332       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18333       S.Diag(Var->getLocation(), diag::note_declared_at);
18334     }
18335     return false;
18336   }
18337 
18338   // Prohibit variably-modified types in blocks; they're difficult to deal with.
18339   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18340     if (Diagnose) {
18341       S.Diag(Loc, diag::err_ref_vm_type);
18342       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18343     }
18344     return false;
18345   }
18346   // Prohibit structs with flexible array members too.
18347   // We cannot capture what is in the tail end of the struct.
18348   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18349     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18350       if (Diagnose) {
18351         if (IsBlock)
18352           S.Diag(Loc, diag::err_ref_flexarray_type);
18353         else
18354           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18355         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18356       }
18357       return false;
18358     }
18359   }
18360   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18361   // Lambdas and captured statements are not allowed to capture __block
18362   // variables; they don't support the expected semantics.
18363   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18364     if (Diagnose) {
18365       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18366       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18367     }
18368     return false;
18369   }
18370   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18371   if (S.getLangOpts().OpenCL && IsBlock &&
18372       Var->getType()->isBlockPointerType()) {
18373     if (Diagnose)
18374       S.Diag(Loc, diag::err_opencl_block_ref_block);
18375     return false;
18376   }
18377 
18378   return true;
18379 }
18380 
18381 // Returns true if the capture by block was successful.
18382 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
18383                                  SourceLocation Loc,
18384                                  const bool BuildAndDiagnose,
18385                                  QualType &CaptureType,
18386                                  QualType &DeclRefType,
18387                                  const bool Nested,
18388                                  Sema &S, bool Invalid) {
18389   bool ByRef = false;
18390 
18391   // Blocks are not allowed to capture arrays, excepting OpenCL.
18392   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18393   // (decayed to pointers).
18394   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18395     if (BuildAndDiagnose) {
18396       S.Diag(Loc, diag::err_ref_array_type);
18397       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18398       Invalid = true;
18399     } else {
18400       return false;
18401     }
18402   }
18403 
18404   // Forbid the block-capture of autoreleasing variables.
18405   if (!Invalid &&
18406       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18407     if (BuildAndDiagnose) {
18408       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18409         << /*block*/ 0;
18410       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18411       Invalid = true;
18412     } else {
18413       return false;
18414     }
18415   }
18416 
18417   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18418   if (const auto *PT = CaptureType->getAs<PointerType>()) {
18419     QualType PointeeTy = PT->getPointeeType();
18420 
18421     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18422         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
18423         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18424       if (BuildAndDiagnose) {
18425         SourceLocation VarLoc = Var->getLocation();
18426         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18427         S.Diag(VarLoc, diag::note_declare_parameter_strong);
18428       }
18429     }
18430   }
18431 
18432   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18433   if (HasBlocksAttr || CaptureType->isReferenceType() ||
18434       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
18435     // Block capture by reference does not change the capture or
18436     // declaration reference types.
18437     ByRef = true;
18438   } else {
18439     // Block capture by copy introduces 'const'.
18440     CaptureType = CaptureType.getNonReferenceType().withConst();
18441     DeclRefType = CaptureType;
18442   }
18443 
18444   // Actually capture the variable.
18445   if (BuildAndDiagnose)
18446     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18447                     CaptureType, Invalid);
18448 
18449   return !Invalid;
18450 }
18451 
18452 
18453 /// Capture the given variable in the captured region.
18454 static bool captureInCapturedRegion(
18455     CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
18456     const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18457     const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18458     bool IsTopScope, Sema &S, bool Invalid) {
18459   // By default, capture variables by reference.
18460   bool ByRef = true;
18461   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18462     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18463   } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18464     // Using an LValue reference type is consistent with Lambdas (see below).
18465     if (S.isOpenMPCapturedDecl(Var)) {
18466       bool HasConst = DeclRefType.isConstQualified();
18467       DeclRefType = DeclRefType.getUnqualifiedType();
18468       // Don't lose diagnostics about assignments to const.
18469       if (HasConst)
18470         DeclRefType.addConst();
18471     }
18472     // Do not capture firstprivates in tasks.
18473     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
18474         OMPC_unknown)
18475       return true;
18476     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18477                                     RSI->OpenMPCaptureLevel);
18478   }
18479 
18480   if (ByRef)
18481     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18482   else
18483     CaptureType = DeclRefType;
18484 
18485   // Actually capture the variable.
18486   if (BuildAndDiagnose)
18487     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18488                     Loc, SourceLocation(), CaptureType, Invalid);
18489 
18490   return !Invalid;
18491 }
18492 
18493 /// Capture the given variable in the lambda.
18494 static bool captureInLambda(LambdaScopeInfo *LSI,
18495                             VarDecl *Var,
18496                             SourceLocation Loc,
18497                             const bool BuildAndDiagnose,
18498                             QualType &CaptureType,
18499                             QualType &DeclRefType,
18500                             const bool RefersToCapturedVariable,
18501                             const Sema::TryCaptureKind Kind,
18502                             SourceLocation EllipsisLoc,
18503                             const bool IsTopScope,
18504                             Sema &S, bool Invalid) {
18505   // Determine whether we are capturing by reference or by value.
18506   bool ByRef = false;
18507   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18508     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18509   } else {
18510     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18511   }
18512 
18513   // Compute the type of the field that will capture this variable.
18514   if (ByRef) {
18515     // C++11 [expr.prim.lambda]p15:
18516     //   An entity is captured by reference if it is implicitly or
18517     //   explicitly captured but not captured by copy. It is
18518     //   unspecified whether additional unnamed non-static data
18519     //   members are declared in the closure type for entities
18520     //   captured by reference.
18521     //
18522     // FIXME: It is not clear whether we want to build an lvalue reference
18523     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18524     // to do the former, while EDG does the latter. Core issue 1249 will
18525     // clarify, but for now we follow GCC because it's a more permissive and
18526     // easily defensible position.
18527     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18528   } else {
18529     // C++11 [expr.prim.lambda]p14:
18530     //   For each entity captured by copy, an unnamed non-static
18531     //   data member is declared in the closure type. The
18532     //   declaration order of these members is unspecified. The type
18533     //   of such a data member is the type of the corresponding
18534     //   captured entity if the entity is not a reference to an
18535     //   object, or the referenced type otherwise. [Note: If the
18536     //   captured entity is a reference to a function, the
18537     //   corresponding data member is also a reference to a
18538     //   function. - end note ]
18539     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18540       if (!RefType->getPointeeType()->isFunctionType())
18541         CaptureType = RefType->getPointeeType();
18542     }
18543 
18544     // Forbid the lambda copy-capture of autoreleasing variables.
18545     if (!Invalid &&
18546         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18547       if (BuildAndDiagnose) {
18548         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18549         S.Diag(Var->getLocation(), diag::note_previous_decl)
18550           << Var->getDeclName();
18551         Invalid = true;
18552       } else {
18553         return false;
18554       }
18555     }
18556 
18557     // Make sure that by-copy captures are of a complete and non-abstract type.
18558     if (!Invalid && BuildAndDiagnose) {
18559       if (!CaptureType->isDependentType() &&
18560           S.RequireCompleteSizedType(
18561               Loc, CaptureType,
18562               diag::err_capture_of_incomplete_or_sizeless_type,
18563               Var->getDeclName()))
18564         Invalid = true;
18565       else if (S.RequireNonAbstractType(Loc, CaptureType,
18566                                         diag::err_capture_of_abstract_type))
18567         Invalid = true;
18568     }
18569   }
18570 
18571   // Compute the type of a reference to this captured variable.
18572   if (ByRef)
18573     DeclRefType = CaptureType.getNonReferenceType();
18574   else {
18575     // C++ [expr.prim.lambda]p5:
18576     //   The closure type for a lambda-expression has a public inline
18577     //   function call operator [...]. This function call operator is
18578     //   declared const (9.3.1) if and only if the lambda-expression's
18579     //   parameter-declaration-clause is not followed by mutable.
18580     DeclRefType = CaptureType.getNonReferenceType();
18581     if (!LSI->Mutable && !CaptureType->isReferenceType())
18582       DeclRefType.addConst();
18583   }
18584 
18585   // Add the capture.
18586   if (BuildAndDiagnose)
18587     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18588                     Loc, EllipsisLoc, CaptureType, Invalid);
18589 
18590   return !Invalid;
18591 }
18592 
18593 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
18594   // Offer a Copy fix even if the type is dependent.
18595   if (Var->getType()->isDependentType())
18596     return true;
18597   QualType T = Var->getType().getNonReferenceType();
18598   if (T.isTriviallyCopyableType(Context))
18599     return true;
18600   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18601 
18602     if (!(RD = RD->getDefinition()))
18603       return false;
18604     if (RD->hasSimpleCopyConstructor())
18605       return true;
18606     if (RD->hasUserDeclaredCopyConstructor())
18607       for (CXXConstructorDecl *Ctor : RD->ctors())
18608         if (Ctor->isCopyConstructor())
18609           return !Ctor->isDeleted();
18610   }
18611   return false;
18612 }
18613 
18614 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18615 /// default capture. Fixes may be omitted if they aren't allowed by the
18616 /// standard, for example we can't emit a default copy capture fix-it if we
18617 /// already explicitly copy capture capture another variable.
18618 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
18619                                     VarDecl *Var) {
18620   assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
18621   // Don't offer Capture by copy of default capture by copy fixes if Var is
18622   // known not to be copy constructible.
18623   bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18624 
18625   SmallString<32> FixBuffer;
18626   StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18627   if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18628     SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18629     if (ShouldOfferCopyFix) {
18630       // Offer fixes to insert an explicit capture for the variable.
18631       // [] -> [VarName]
18632       // [OtherCapture] -> [OtherCapture, VarName]
18633       FixBuffer.assign({Separator, Var->getName()});
18634       Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18635           << Var << /*value*/ 0
18636           << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18637     }
18638     // As above but capture by reference.
18639     FixBuffer.assign({Separator, "&", Var->getName()});
18640     Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18641         << Var << /*reference*/ 1
18642         << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18643   }
18644 
18645   // Only try to offer default capture if there are no captures excluding this
18646   // and init captures.
18647   // [this]: OK.
18648   // [X = Y]: OK.
18649   // [&A, &B]: Don't offer.
18650   // [A, B]: Don't offer.
18651   if (llvm::any_of(LSI->Captures, [](Capture &C) {
18652         return !C.isThisCapture() && !C.isInitCapture();
18653       }))
18654     return;
18655 
18656   // The default capture specifiers, '=' or '&', must appear first in the
18657   // capture body.
18658   SourceLocation DefaultInsertLoc =
18659       LSI->IntroducerRange.getBegin().getLocWithOffset(1);
18660 
18661   if (ShouldOfferCopyFix) {
18662     bool CanDefaultCopyCapture = true;
18663     // [=, *this] OK since c++17
18664     // [=, this] OK since c++20
18665     if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18666       CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18667                                   ? LSI->getCXXThisCapture().isCopyCapture()
18668                                   : false;
18669     // We can't use default capture by copy if any captures already specified
18670     // capture by copy.
18671     if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18672           return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18673         })) {
18674       FixBuffer.assign({"=", Separator});
18675       Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18676           << /*value*/ 0
18677           << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18678     }
18679   }
18680 
18681   // We can't use default capture by reference if any captures already specified
18682   // capture by reference.
18683   if (llvm::none_of(LSI->Captures, [](Capture &C) {
18684         return !C.isInitCapture() && C.isReferenceCapture() &&
18685                !C.isThisCapture();
18686       })) {
18687     FixBuffer.assign({"&", Separator});
18688     Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18689         << /*reference*/ 1
18690         << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18691   }
18692 }
18693 
18694 bool Sema::tryCaptureVariable(
18695     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18696     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18697     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18698   // An init-capture is notionally from the context surrounding its
18699   // declaration, but its parent DC is the lambda class.
18700   DeclContext *VarDC = Var->getDeclContext();
18701   if (Var->isInitCapture())
18702     VarDC = VarDC->getParent();
18703 
18704   DeclContext *DC = CurContext;
18705   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18706       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18707   // We need to sync up the Declaration Context with the
18708   // FunctionScopeIndexToStopAt
18709   if (FunctionScopeIndexToStopAt) {
18710     unsigned FSIndex = FunctionScopes.size() - 1;
18711     while (FSIndex != MaxFunctionScopesIndex) {
18712       DC = getLambdaAwareParentOfDeclContext(DC);
18713       --FSIndex;
18714     }
18715   }
18716 
18717 
18718   // If the variable is declared in the current context, there is no need to
18719   // capture it.
18720   if (VarDC == DC) return true;
18721 
18722   // Capture global variables if it is required to use private copy of this
18723   // variable.
18724   bool IsGlobal = !Var->hasLocalStorage();
18725   if (IsGlobal &&
18726       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18727                                                 MaxFunctionScopesIndex)))
18728     return true;
18729   Var = Var->getCanonicalDecl();
18730 
18731   // Walk up the stack to determine whether we can capture the variable,
18732   // performing the "simple" checks that don't depend on type. We stop when
18733   // we've either hit the declared scope of the variable or find an existing
18734   // capture of that variable.  We start from the innermost capturing-entity
18735   // (the DC) and ensure that all intervening capturing-entities
18736   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18737   // declcontext can either capture the variable or have already captured
18738   // the variable.
18739   CaptureType = Var->getType();
18740   DeclRefType = CaptureType.getNonReferenceType();
18741   bool Nested = false;
18742   bool Explicit = (Kind != TryCapture_Implicit);
18743   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18744   do {
18745     // Only block literals, captured statements, and lambda expressions can
18746     // capture; other scopes don't work.
18747     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
18748                                                               ExprLoc,
18749                                                               BuildAndDiagnose,
18750                                                               *this);
18751     // We need to check for the parent *first* because, if we *have*
18752     // private-captured a global variable, we need to recursively capture it in
18753     // intermediate blocks, lambdas, etc.
18754     if (!ParentDC) {
18755       if (IsGlobal) {
18756         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18757         break;
18758       }
18759       return true;
18760     }
18761 
18762     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
18763     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18764 
18765 
18766     // Check whether we've already captured it.
18767     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18768                                              DeclRefType)) {
18769       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18770       break;
18771     }
18772     // If we are instantiating a generic lambda call operator body,
18773     // we do not want to capture new variables.  What was captured
18774     // during either a lambdas transformation or initial parsing
18775     // should be used.
18776     if (isGenericLambdaCallOperatorSpecialization(DC)) {
18777       if (BuildAndDiagnose) {
18778         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18779         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
18780           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18781           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18782           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18783           buildLambdaCaptureFixit(*this, LSI, Var);
18784         } else
18785           diagnoseUncapturableValueReference(*this, ExprLoc, Var);
18786       }
18787       return true;
18788     }
18789 
18790     // Try to capture variable-length arrays types.
18791     if (Var->getType()->isVariablyModifiedType()) {
18792       // We're going to walk down into the type and look for VLA
18793       // expressions.
18794       QualType QTy = Var->getType();
18795       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18796         QTy = PVD->getOriginalType();
18797       captureVariablyModifiedType(Context, QTy, CSI);
18798     }
18799 
18800     if (getLangOpts().OpenMP) {
18801       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18802         // OpenMP private variables should not be captured in outer scope, so
18803         // just break here. Similarly, global variables that are captured in a
18804         // target region should not be captured outside the scope of the region.
18805         if (RSI->CapRegionKind == CR_OpenMP) {
18806           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
18807               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18808           // If the variable is private (i.e. not captured) and has variably
18809           // modified type, we still need to capture the type for correct
18810           // codegen in all regions, associated with the construct. Currently,
18811           // it is captured in the innermost captured region only.
18812           if (IsOpenMPPrivateDecl != OMPC_unknown &&
18813               Var->getType()->isVariablyModifiedType()) {
18814             QualType QTy = Var->getType();
18815             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18816               QTy = PVD->getOriginalType();
18817             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
18818                  I < E; ++I) {
18819               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18820                   FunctionScopes[FunctionScopesIndex - I]);
18821               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
18822                      "Wrong number of captured regions associated with the "
18823                      "OpenMP construct.");
18824               captureVariablyModifiedType(Context, QTy, OuterRSI);
18825             }
18826           }
18827           bool IsTargetCap =
18828               IsOpenMPPrivateDecl != OMPC_private &&
18829               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
18830                                          RSI->OpenMPCaptureLevel);
18831           // Do not capture global if it is not privatized in outer regions.
18832           bool IsGlobalCap =
18833               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
18834                                                      RSI->OpenMPCaptureLevel);
18835 
18836           // When we detect target captures we are looking from inside the
18837           // target region, therefore we need to propagate the capture from the
18838           // enclosing region. Therefore, the capture is not initially nested.
18839           if (IsTargetCap)
18840             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
18841 
18842           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18843               (IsGlobal && !IsGlobalCap)) {
18844             Nested = !IsTargetCap;
18845             bool HasConst = DeclRefType.isConstQualified();
18846             DeclRefType = DeclRefType.getUnqualifiedType();
18847             // Don't lose diagnostics about assignments to const.
18848             if (HasConst)
18849               DeclRefType.addConst();
18850             CaptureType = Context.getLValueReferenceType(DeclRefType);
18851             break;
18852           }
18853         }
18854       }
18855     }
18856     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18857       // No capture-default, and this is not an explicit capture
18858       // so cannot capture this variable.
18859       if (BuildAndDiagnose) {
18860         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18861         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18862         auto *LSI = cast<LambdaScopeInfo>(CSI);
18863         if (LSI->Lambda) {
18864           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18865           buildLambdaCaptureFixit(*this, LSI, Var);
18866         }
18867         // FIXME: If we error out because an outer lambda can not implicitly
18868         // capture a variable that an inner lambda explicitly captures, we
18869         // should have the inner lambda do the explicit capture - because
18870         // it makes for cleaner diagnostics later.  This would purely be done
18871         // so that the diagnostic does not misleadingly claim that a variable
18872         // can not be captured by a lambda implicitly even though it is captured
18873         // explicitly.  Suggestion:
18874         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18875         //    at the function head
18876         //  - cache the StartingDeclContext - this must be a lambda
18877         //  - captureInLambda in the innermost lambda the variable.
18878       }
18879       return true;
18880     }
18881 
18882     FunctionScopesIndex--;
18883     DC = ParentDC;
18884     Explicit = false;
18885   } while (!VarDC->Equals(DC));
18886 
18887   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18888   // computing the type of the capture at each step, checking type-specific
18889   // requirements, and adding captures if requested.
18890   // If the variable had already been captured previously, we start capturing
18891   // at the lambda nested within that one.
18892   bool Invalid = false;
18893   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18894        ++I) {
18895     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18896 
18897     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18898     // certain types of variables (unnamed, variably modified types etc.)
18899     // so check for eligibility.
18900     if (!Invalid)
18901       Invalid =
18902           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18903 
18904     // After encountering an error, if we're actually supposed to capture, keep
18905     // capturing in nested contexts to suppress any follow-on diagnostics.
18906     if (Invalid && !BuildAndDiagnose)
18907       return true;
18908 
18909     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18910       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18911                                DeclRefType, Nested, *this, Invalid);
18912       Nested = true;
18913     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18914       Invalid = !captureInCapturedRegion(
18915           RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18916           Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18917       Nested = true;
18918     } else {
18919       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18920       Invalid =
18921           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18922                            DeclRefType, Nested, Kind, EllipsisLoc,
18923                            /*IsTopScope*/ I == N - 1, *this, Invalid);
18924       Nested = true;
18925     }
18926 
18927     if (Invalid && !BuildAndDiagnose)
18928       return true;
18929   }
18930   return Invalid;
18931 }
18932 
18933 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
18934                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18935   QualType CaptureType;
18936   QualType DeclRefType;
18937   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18938                             /*BuildAndDiagnose=*/true, CaptureType,
18939                             DeclRefType, nullptr);
18940 }
18941 
18942 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
18943   QualType CaptureType;
18944   QualType DeclRefType;
18945   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18946                              /*BuildAndDiagnose=*/false, CaptureType,
18947                              DeclRefType, nullptr);
18948 }
18949 
18950 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
18951   QualType CaptureType;
18952   QualType DeclRefType;
18953 
18954   // Determine whether we can capture this variable.
18955   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18956                          /*BuildAndDiagnose=*/false, CaptureType,
18957                          DeclRefType, nullptr))
18958     return QualType();
18959 
18960   return DeclRefType;
18961 }
18962 
18963 namespace {
18964 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
18965 // The produced TemplateArgumentListInfo* points to data stored within this
18966 // object, so should only be used in contexts where the pointer will not be
18967 // used after the CopiedTemplateArgs object is destroyed.
18968 class CopiedTemplateArgs {
18969   bool HasArgs;
18970   TemplateArgumentListInfo TemplateArgStorage;
18971 public:
18972   template<typename RefExpr>
18973   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
18974     if (HasArgs)
18975       E->copyTemplateArgumentsInto(TemplateArgStorage);
18976   }
18977   operator TemplateArgumentListInfo*()
18978 #ifdef __has_cpp_attribute
18979 #if __has_cpp_attribute(clang::lifetimebound)
18980   [[clang::lifetimebound]]
18981 #endif
18982 #endif
18983   {
18984     return HasArgs ? &TemplateArgStorage : nullptr;
18985   }
18986 };
18987 }
18988 
18989 /// Walk the set of potential results of an expression and mark them all as
18990 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
18991 ///
18992 /// \return A new expression if we found any potential results, ExprEmpty() if
18993 ///         not, and ExprError() if we diagnosed an error.
18994 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
18995                                                       NonOdrUseReason NOUR) {
18996   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
18997   // an object that satisfies the requirements for appearing in a
18998   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
18999   // is immediately applied."  This function handles the lvalue-to-rvalue
19000   // conversion part.
19001   //
19002   // If we encounter a node that claims to be an odr-use but shouldn't be, we
19003   // transform it into the relevant kind of non-odr-use node and rebuild the
19004   // tree of nodes leading to it.
19005   //
19006   // This is a mini-TreeTransform that only transforms a restricted subset of
19007   // nodes (and only certain operands of them).
19008 
19009   // Rebuild a subexpression.
19010   auto Rebuild = [&](Expr *Sub) {
19011     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19012   };
19013 
19014   // Check whether a potential result satisfies the requirements of NOUR.
19015   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19016     // Any entity other than a VarDecl is always odr-used whenever it's named
19017     // in a potentially-evaluated expression.
19018     auto *VD = dyn_cast<VarDecl>(D);
19019     if (!VD)
19020       return true;
19021 
19022     // C++2a [basic.def.odr]p4:
19023     //   A variable x whose name appears as a potentially-evalauted expression
19024     //   e is odr-used by e unless
19025     //   -- x is a reference that is usable in constant expressions, or
19026     //   -- x is a variable of non-reference type that is usable in constant
19027     //      expressions and has no mutable subobjects, and e is an element of
19028     //      the set of potential results of an expression of
19029     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
19030     //      conversion is applied, or
19031     //   -- x is a variable of non-reference type, and e is an element of the
19032     //      set of potential results of a discarded-value expression to which
19033     //      the lvalue-to-rvalue conversion is not applied
19034     //
19035     // We check the first bullet and the "potentially-evaluated" condition in
19036     // BuildDeclRefExpr. We check the type requirements in the second bullet
19037     // in CheckLValueToRValueConversionOperand below.
19038     switch (NOUR) {
19039     case NOUR_None:
19040     case NOUR_Unevaluated:
19041       llvm_unreachable("unexpected non-odr-use-reason");
19042 
19043     case NOUR_Constant:
19044       // Constant references were handled when they were built.
19045       if (VD->getType()->isReferenceType())
19046         return true;
19047       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19048         if (RD->hasMutableFields())
19049           return true;
19050       if (!VD->isUsableInConstantExpressions(S.Context))
19051         return true;
19052       break;
19053 
19054     case NOUR_Discarded:
19055       if (VD->getType()->isReferenceType())
19056         return true;
19057       break;
19058     }
19059     return false;
19060   };
19061 
19062   // Mark that this expression does not constitute an odr-use.
19063   auto MarkNotOdrUsed = [&] {
19064     S.MaybeODRUseExprs.remove(E);
19065     if (LambdaScopeInfo *LSI = S.getCurLambda())
19066       LSI->markVariableExprAsNonODRUsed(E);
19067   };
19068 
19069   // C++2a [basic.def.odr]p2:
19070   //   The set of potential results of an expression e is defined as follows:
19071   switch (E->getStmtClass()) {
19072   //   -- If e is an id-expression, ...
19073   case Expr::DeclRefExprClass: {
19074     auto *DRE = cast<DeclRefExpr>(E);
19075     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19076       break;
19077 
19078     // Rebuild as a non-odr-use DeclRefExpr.
19079     MarkNotOdrUsed();
19080     return DeclRefExpr::Create(
19081         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19082         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19083         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19084         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19085   }
19086 
19087   case Expr::FunctionParmPackExprClass: {
19088     auto *FPPE = cast<FunctionParmPackExpr>(E);
19089     // If any of the declarations in the pack is odr-used, then the expression
19090     // as a whole constitutes an odr-use.
19091     for (VarDecl *D : *FPPE)
19092       if (IsPotentialResultOdrUsed(D))
19093         return ExprEmpty();
19094 
19095     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19096     // nothing cares about whether we marked this as an odr-use, but it might
19097     // be useful for non-compiler tools.
19098     MarkNotOdrUsed();
19099     break;
19100   }
19101 
19102   //   -- If e is a subscripting operation with an array operand...
19103   case Expr::ArraySubscriptExprClass: {
19104     auto *ASE = cast<ArraySubscriptExpr>(E);
19105     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19106     if (!OldBase->getType()->isArrayType())
19107       break;
19108     ExprResult Base = Rebuild(OldBase);
19109     if (!Base.isUsable())
19110       return Base;
19111     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19112     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19113     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19114     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19115                                      ASE->getRBracketLoc());
19116   }
19117 
19118   case Expr::MemberExprClass: {
19119     auto *ME = cast<MemberExpr>(E);
19120     // -- If e is a class member access expression [...] naming a non-static
19121     //    data member...
19122     if (isa<FieldDecl>(ME->getMemberDecl())) {
19123       ExprResult Base = Rebuild(ME->getBase());
19124       if (!Base.isUsable())
19125         return Base;
19126       return MemberExpr::Create(
19127           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19128           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19129           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19130           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19131           ME->getObjectKind(), ME->isNonOdrUse());
19132     }
19133 
19134     if (ME->getMemberDecl()->isCXXInstanceMember())
19135       break;
19136 
19137     // -- If e is a class member access expression naming a static data member,
19138     //    ...
19139     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19140       break;
19141 
19142     // Rebuild as a non-odr-use MemberExpr.
19143     MarkNotOdrUsed();
19144     return MemberExpr::Create(
19145         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19146         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19147         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19148         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19149   }
19150 
19151   case Expr::BinaryOperatorClass: {
19152     auto *BO = cast<BinaryOperator>(E);
19153     Expr *LHS = BO->getLHS();
19154     Expr *RHS = BO->getRHS();
19155     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19156     if (BO->getOpcode() == BO_PtrMemD) {
19157       ExprResult Sub = Rebuild(LHS);
19158       if (!Sub.isUsable())
19159         return Sub;
19160       LHS = Sub.get();
19161     //   -- If e is a comma expression, ...
19162     } else if (BO->getOpcode() == BO_Comma) {
19163       ExprResult Sub = Rebuild(RHS);
19164       if (!Sub.isUsable())
19165         return Sub;
19166       RHS = Sub.get();
19167     } else {
19168       break;
19169     }
19170     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
19171                         LHS, RHS);
19172   }
19173 
19174   //   -- If e has the form (e1)...
19175   case Expr::ParenExprClass: {
19176     auto *PE = cast<ParenExpr>(E);
19177     ExprResult Sub = Rebuild(PE->getSubExpr());
19178     if (!Sub.isUsable())
19179       return Sub;
19180     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19181   }
19182 
19183   //   -- If e is a glvalue conditional expression, ...
19184   // We don't apply this to a binary conditional operator. FIXME: Should we?
19185   case Expr::ConditionalOperatorClass: {
19186     auto *CO = cast<ConditionalOperator>(E);
19187     ExprResult LHS = Rebuild(CO->getLHS());
19188     if (LHS.isInvalid())
19189       return ExprError();
19190     ExprResult RHS = Rebuild(CO->getRHS());
19191     if (RHS.isInvalid())
19192       return ExprError();
19193     if (!LHS.isUsable() && !RHS.isUsable())
19194       return ExprEmpty();
19195     if (!LHS.isUsable())
19196       LHS = CO->getLHS();
19197     if (!RHS.isUsable())
19198       RHS = CO->getRHS();
19199     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19200                                 CO->getCond(), LHS.get(), RHS.get());
19201   }
19202 
19203   // [Clang extension]
19204   //   -- If e has the form __extension__ e1...
19205   case Expr::UnaryOperatorClass: {
19206     auto *UO = cast<UnaryOperator>(E);
19207     if (UO->getOpcode() != UO_Extension)
19208       break;
19209     ExprResult Sub = Rebuild(UO->getSubExpr());
19210     if (!Sub.isUsable())
19211       return Sub;
19212     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19213                           Sub.get());
19214   }
19215 
19216   // [Clang extension]
19217   //   -- If e has the form _Generic(...), the set of potential results is the
19218   //      union of the sets of potential results of the associated expressions.
19219   case Expr::GenericSelectionExprClass: {
19220     auto *GSE = cast<GenericSelectionExpr>(E);
19221 
19222     SmallVector<Expr *, 4> AssocExprs;
19223     bool AnyChanged = false;
19224     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19225       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19226       if (AssocExpr.isInvalid())
19227         return ExprError();
19228       if (AssocExpr.isUsable()) {
19229         AssocExprs.push_back(AssocExpr.get());
19230         AnyChanged = true;
19231       } else {
19232         AssocExprs.push_back(OrigAssocExpr);
19233       }
19234     }
19235 
19236     return AnyChanged ? S.CreateGenericSelectionExpr(
19237                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
19238                             GSE->getRParenLoc(), GSE->getControllingExpr(),
19239                             GSE->getAssocTypeSourceInfos(), AssocExprs)
19240                       : ExprEmpty();
19241   }
19242 
19243   // [Clang extension]
19244   //   -- If e has the form __builtin_choose_expr(...), the set of potential
19245   //      results is the union of the sets of potential results of the
19246   //      second and third subexpressions.
19247   case Expr::ChooseExprClass: {
19248     auto *CE = cast<ChooseExpr>(E);
19249 
19250     ExprResult LHS = Rebuild(CE->getLHS());
19251     if (LHS.isInvalid())
19252       return ExprError();
19253 
19254     ExprResult RHS = Rebuild(CE->getLHS());
19255     if (RHS.isInvalid())
19256       return ExprError();
19257 
19258     if (!LHS.get() && !RHS.get())
19259       return ExprEmpty();
19260     if (!LHS.isUsable())
19261       LHS = CE->getLHS();
19262     if (!RHS.isUsable())
19263       RHS = CE->getRHS();
19264 
19265     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19266                              RHS.get(), CE->getRParenLoc());
19267   }
19268 
19269   // Step through non-syntactic nodes.
19270   case Expr::ConstantExprClass: {
19271     auto *CE = cast<ConstantExpr>(E);
19272     ExprResult Sub = Rebuild(CE->getSubExpr());
19273     if (!Sub.isUsable())
19274       return Sub;
19275     return ConstantExpr::Create(S.Context, Sub.get());
19276   }
19277 
19278   // We could mostly rely on the recursive rebuilding to rebuild implicit
19279   // casts, but not at the top level, so rebuild them here.
19280   case Expr::ImplicitCastExprClass: {
19281     auto *ICE = cast<ImplicitCastExpr>(E);
19282     // Only step through the narrow set of cast kinds we expect to encounter.
19283     // Anything else suggests we've left the region in which potential results
19284     // can be found.
19285     switch (ICE->getCastKind()) {
19286     case CK_NoOp:
19287     case CK_DerivedToBase:
19288     case CK_UncheckedDerivedToBase: {
19289       ExprResult Sub = Rebuild(ICE->getSubExpr());
19290       if (!Sub.isUsable())
19291         return Sub;
19292       CXXCastPath Path(ICE->path());
19293       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19294                                  ICE->getValueKind(), &Path);
19295     }
19296 
19297     default:
19298       break;
19299     }
19300     break;
19301   }
19302 
19303   default:
19304     break;
19305   }
19306 
19307   // Can't traverse through this node. Nothing to do.
19308   return ExprEmpty();
19309 }
19310 
19311 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
19312   // Check whether the operand is or contains an object of non-trivial C union
19313   // type.
19314   if (E->getType().isVolatileQualified() &&
19315       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
19316        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
19317     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
19318                           Sema::NTCUC_LValueToRValueVolatile,
19319                           NTCUK_Destruct|NTCUK_Copy);
19320 
19321   // C++2a [basic.def.odr]p4:
19322   //   [...] an expression of non-volatile-qualified non-class type to which
19323   //   the lvalue-to-rvalue conversion is applied [...]
19324   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
19325     return E;
19326 
19327   ExprResult Result =
19328       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
19329   if (Result.isInvalid())
19330     return ExprError();
19331   return Result.get() ? Result : E;
19332 }
19333 
19334 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
19335   Res = CorrectDelayedTyposInExpr(Res);
19336 
19337   if (!Res.isUsable())
19338     return Res;
19339 
19340   // If a constant-expression is a reference to a variable where we delay
19341   // deciding whether it is an odr-use, just assume we will apply the
19342   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
19343   // (a non-type template argument), we have special handling anyway.
19344   return CheckLValueToRValueConversionOperand(Res.get());
19345 }
19346 
19347 void Sema::CleanupVarDeclMarking() {
19348   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19349   // call.
19350   MaybeODRUseExprSet LocalMaybeODRUseExprs;
19351   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19352 
19353   for (Expr *E : LocalMaybeODRUseExprs) {
19354     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19355       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19356                          DRE->getLocation(), *this);
19357     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19358       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19359                          *this);
19360     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19361       for (VarDecl *VD : *FP)
19362         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19363     } else {
19364       llvm_unreachable("Unexpected expression");
19365     }
19366   }
19367 
19368   assert(MaybeODRUseExprs.empty() &&
19369          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19370 }
19371 
19372 static void DoMarkVarDeclReferenced(
19373     Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
19374     llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19375   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19376           isa<FunctionParmPackExpr>(E)) &&
19377          "Invalid Expr argument to DoMarkVarDeclReferenced");
19378   Var->setReferenced();
19379 
19380   if (Var->isInvalidDecl())
19381     return;
19382 
19383   auto *MSI = Var->getMemberSpecializationInfo();
19384   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
19385                                        : Var->getTemplateSpecializationKind();
19386 
19387   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19388   bool UsableInConstantExpr =
19389       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
19390 
19391   if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19392     RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19393   }
19394 
19395   // C++20 [expr.const]p12:
19396   //   A variable [...] is needed for constant evaluation if it is [...] a
19397   //   variable whose name appears as a potentially constant evaluated
19398   //   expression that is either a contexpr variable or is of non-volatile
19399   //   const-qualified integral type or of reference type
19400   bool NeededForConstantEvaluation =
19401       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19402 
19403   bool NeedDefinition =
19404       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19405 
19406   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19407          "Can't instantiate a partial template specialization.");
19408 
19409   // If this might be a member specialization of a static data member, check
19410   // the specialization is visible. We already did the checks for variable
19411   // template specializations when we created them.
19412   if (NeedDefinition && TSK != TSK_Undeclared &&
19413       !isa<VarTemplateSpecializationDecl>(Var))
19414     SemaRef.checkSpecializationVisibility(Loc, Var);
19415 
19416   // Perform implicit instantiation of static data members, static data member
19417   // templates of class templates, and variable template specializations. Delay
19418   // instantiations of variable templates, except for those that could be used
19419   // in a constant expression.
19420   if (NeedDefinition && isTemplateInstantiation(TSK)) {
19421     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19422     // instantiation declaration if a variable is usable in a constant
19423     // expression (among other cases).
19424     bool TryInstantiating =
19425         TSK == TSK_ImplicitInstantiation ||
19426         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19427 
19428     if (TryInstantiating) {
19429       SourceLocation PointOfInstantiation =
19430           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19431       bool FirstInstantiation = PointOfInstantiation.isInvalid();
19432       if (FirstInstantiation) {
19433         PointOfInstantiation = Loc;
19434         if (MSI)
19435           MSI->setPointOfInstantiation(PointOfInstantiation);
19436           // FIXME: Notify listener.
19437         else
19438           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19439       }
19440 
19441       if (UsableInConstantExpr) {
19442         // Do not defer instantiations of variables that could be used in a
19443         // constant expression.
19444         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19445           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19446         });
19447 
19448         // Re-set the member to trigger a recomputation of the dependence bits
19449         // for the expression.
19450         if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19451           DRE->setDecl(DRE->getDecl());
19452         else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19453           ME->setMemberDecl(ME->getMemberDecl());
19454       } else if (FirstInstantiation ||
19455                  isa<VarTemplateSpecializationDecl>(Var)) {
19456         // FIXME: For a specialization of a variable template, we don't
19457         // distinguish between "declaration and type implicitly instantiated"
19458         // and "implicit instantiation of definition requested", so we have
19459         // no direct way to avoid enqueueing the pending instantiation
19460         // multiple times.
19461         SemaRef.PendingInstantiations
19462             .push_back(std::make_pair(Var, PointOfInstantiation));
19463       }
19464     }
19465   }
19466 
19467   // C++2a [basic.def.odr]p4:
19468   //   A variable x whose name appears as a potentially-evaluated expression e
19469   //   is odr-used by e unless
19470   //   -- x is a reference that is usable in constant expressions
19471   //   -- x is a variable of non-reference type that is usable in constant
19472   //      expressions and has no mutable subobjects [FIXME], and e is an
19473   //      element of the set of potential results of an expression of
19474   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
19475   //      conversion is applied
19476   //   -- x is a variable of non-reference type, and e is an element of the set
19477   //      of potential results of a discarded-value expression to which the
19478   //      lvalue-to-rvalue conversion is not applied [FIXME]
19479   //
19480   // We check the first part of the second bullet here, and
19481   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19482   // FIXME: To get the third bullet right, we need to delay this even for
19483   // variables that are not usable in constant expressions.
19484 
19485   // If we already know this isn't an odr-use, there's nothing more to do.
19486   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19487     if (DRE->isNonOdrUse())
19488       return;
19489   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19490     if (ME->isNonOdrUse())
19491       return;
19492 
19493   switch (OdrUse) {
19494   case OdrUseContext::None:
19495     assert((!E || isa<FunctionParmPackExpr>(E)) &&
19496            "missing non-odr-use marking for unevaluated decl ref");
19497     break;
19498 
19499   case OdrUseContext::FormallyOdrUsed:
19500     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19501     // behavior.
19502     break;
19503 
19504   case OdrUseContext::Used:
19505     // If we might later find that this expression isn't actually an odr-use,
19506     // delay the marking.
19507     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
19508       SemaRef.MaybeODRUseExprs.insert(E);
19509     else
19510       MarkVarDeclODRUsed(Var, Loc, SemaRef);
19511     break;
19512 
19513   case OdrUseContext::Dependent:
19514     // If this is a dependent context, we don't need to mark variables as
19515     // odr-used, but we may still need to track them for lambda capture.
19516     // FIXME: Do we also need to do this inside dependent typeid expressions
19517     // (which are modeled as unevaluated at this point)?
19518     const bool RefersToEnclosingScope =
19519         (SemaRef.CurContext != Var->getDeclContext() &&
19520          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
19521     if (RefersToEnclosingScope) {
19522       LambdaScopeInfo *const LSI =
19523           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19524       if (LSI && (!LSI->CallOperator ||
19525                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19526         // If a variable could potentially be odr-used, defer marking it so
19527         // until we finish analyzing the full expression for any
19528         // lvalue-to-rvalue
19529         // or discarded value conversions that would obviate odr-use.
19530         // Add it to the list of potential captures that will be analyzed
19531         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19532         // unless the variable is a reference that was initialized by a constant
19533         // expression (this will never need to be captured or odr-used).
19534         //
19535         // FIXME: We can simplify this a lot after implementing P0588R1.
19536         assert(E && "Capture variable should be used in an expression.");
19537         if (!Var->getType()->isReferenceType() ||
19538             !Var->isUsableInConstantExpressions(SemaRef.Context))
19539           LSI->addPotentialCapture(E->IgnoreParens());
19540       }
19541     }
19542     break;
19543   }
19544 }
19545 
19546 /// Mark a variable referenced, and check whether it is odr-used
19547 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
19548 /// used directly for normal expressions referring to VarDecl.
19549 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
19550   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19551 }
19552 
19553 static void
19554 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
19555                    bool MightBeOdrUse,
19556                    llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19557   if (SemaRef.isInOpenMPDeclareTargetContext())
19558     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
19559 
19560   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19561     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
19562     return;
19563   }
19564 
19565   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19566 
19567   // If this is a call to a method via a cast, also mark the method in the
19568   // derived class used in case codegen can devirtualize the call.
19569   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19570   if (!ME)
19571     return;
19572   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19573   if (!MD)
19574     return;
19575   // Only attempt to devirtualize if this is truly a virtual call.
19576   bool IsVirtualCall = MD->isVirtual() &&
19577                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
19578   if (!IsVirtualCall)
19579     return;
19580 
19581   // If it's possible to devirtualize the call, mark the called function
19582   // referenced.
19583   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
19584       ME->getBase(), SemaRef.getLangOpts().AppleKext);
19585   if (DM)
19586     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
19587 }
19588 
19589 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
19590 ///
19591 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
19592 /// handled with care if the DeclRefExpr is not newly-created.
19593 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
19594   // TODO: update this with DR# once a defect report is filed.
19595   // C++11 defect. The address of a pure member should not be an ODR use, even
19596   // if it's a qualified reference.
19597   bool OdrUse = true;
19598   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
19599     if (Method->isVirtual() &&
19600         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
19601       OdrUse = false;
19602 
19603   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
19604     if (!isUnevaluatedContext() && !isConstantEvaluated() &&
19605         FD->isConsteval() && !RebuildingImmediateInvocation)
19606       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
19607   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
19608                      RefsMinusAssignments);
19609 }
19610 
19611 /// Perform reference-marking and odr-use handling for a MemberExpr.
19612 void Sema::MarkMemberReferenced(MemberExpr *E) {
19613   // C++11 [basic.def.odr]p2:
19614   //   A non-overloaded function whose name appears as a potentially-evaluated
19615   //   expression or a member of a set of candidate functions, if selected by
19616   //   overload resolution when referred to from a potentially-evaluated
19617   //   expression, is odr-used, unless it is a pure virtual function and its
19618   //   name is not explicitly qualified.
19619   bool MightBeOdrUse = true;
19620   if (E->performsVirtualDispatch(getLangOpts())) {
19621     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
19622       if (Method->isPure())
19623         MightBeOdrUse = false;
19624   }
19625   SourceLocation Loc =
19626       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
19627   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
19628                      RefsMinusAssignments);
19629 }
19630 
19631 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
19632 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
19633   for (VarDecl *VD : *E)
19634     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
19635                        RefsMinusAssignments);
19636 }
19637 
19638 /// Perform marking for a reference to an arbitrary declaration.  It
19639 /// marks the declaration referenced, and performs odr-use checking for
19640 /// functions and variables. This method should not be used when building a
19641 /// normal expression which refers to a variable.
19642 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
19643                                  bool MightBeOdrUse) {
19644   if (MightBeOdrUse) {
19645     if (auto *VD = dyn_cast<VarDecl>(D)) {
19646       MarkVariableReferenced(Loc, VD);
19647       return;
19648     }
19649   }
19650   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19651     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
19652     return;
19653   }
19654   D->setReferenced();
19655 }
19656 
19657 namespace {
19658   // Mark all of the declarations used by a type as referenced.
19659   // FIXME: Not fully implemented yet! We need to have a better understanding
19660   // of when we're entering a context we should not recurse into.
19661   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
19662   // TreeTransforms rebuilding the type in a new context. Rather than
19663   // duplicating the TreeTransform logic, we should consider reusing it here.
19664   // Currently that causes problems when rebuilding LambdaExprs.
19665   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
19666     Sema &S;
19667     SourceLocation Loc;
19668 
19669   public:
19670     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
19671 
19672     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
19673 
19674     bool TraverseTemplateArgument(const TemplateArgument &Arg);
19675   };
19676 }
19677 
19678 bool MarkReferencedDecls::TraverseTemplateArgument(
19679     const TemplateArgument &Arg) {
19680   {
19681     // A non-type template argument is a constant-evaluated context.
19682     EnterExpressionEvaluationContext Evaluated(
19683         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
19684     if (Arg.getKind() == TemplateArgument::Declaration) {
19685       if (Decl *D = Arg.getAsDecl())
19686         S.MarkAnyDeclReferenced(Loc, D, true);
19687     } else if (Arg.getKind() == TemplateArgument::Expression) {
19688       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
19689     }
19690   }
19691 
19692   return Inherited::TraverseTemplateArgument(Arg);
19693 }
19694 
19695 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
19696   MarkReferencedDecls Marker(*this, Loc);
19697   Marker.TraverseType(T);
19698 }
19699 
19700 namespace {
19701 /// Helper class that marks all of the declarations referenced by
19702 /// potentially-evaluated subexpressions as "referenced".
19703 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
19704 public:
19705   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
19706   bool SkipLocalVariables;
19707   ArrayRef<const Expr *> StopAt;
19708 
19709   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
19710                       ArrayRef<const Expr *> StopAt)
19711       : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
19712 
19713   void visitUsedDecl(SourceLocation Loc, Decl *D) {
19714     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
19715   }
19716 
19717   void Visit(Expr *E) {
19718     if (llvm::is_contained(StopAt, E))
19719       return;
19720     Inherited::Visit(E);
19721   }
19722 
19723   void VisitConstantExpr(ConstantExpr *E) {
19724     // Don't mark declarations within a ConstantExpression, as this expression
19725     // will be evaluated and folded to a value.
19726     return;
19727   }
19728 
19729   void VisitDeclRefExpr(DeclRefExpr *E) {
19730     // If we were asked not to visit local variables, don't.
19731     if (SkipLocalVariables) {
19732       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
19733         if (VD->hasLocalStorage())
19734           return;
19735     }
19736 
19737     // FIXME: This can trigger the instantiation of the initializer of a
19738     // variable, which can cause the expression to become value-dependent
19739     // or error-dependent. Do we need to propagate the new dependence bits?
19740     S.MarkDeclRefReferenced(E);
19741   }
19742 
19743   void VisitMemberExpr(MemberExpr *E) {
19744     S.MarkMemberReferenced(E);
19745     Visit(E->getBase());
19746   }
19747 };
19748 } // namespace
19749 
19750 /// Mark any declarations that appear within this expression or any
19751 /// potentially-evaluated subexpressions as "referenced".
19752 ///
19753 /// \param SkipLocalVariables If true, don't mark local variables as
19754 /// 'referenced'.
19755 /// \param StopAt Subexpressions that we shouldn't recurse into.
19756 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
19757                                             bool SkipLocalVariables,
19758                                             ArrayRef<const Expr*> StopAt) {
19759   EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
19760 }
19761 
19762 /// Emit a diagnostic when statements are reachable.
19763 /// FIXME: check for reachability even in expressions for which we don't build a
19764 ///        CFG (eg, in the initializer of a global or in a constant expression).
19765 ///        For example,
19766 ///        namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
19767 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
19768                            const PartialDiagnostic &PD) {
19769   if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
19770     if (!FunctionScopes.empty())
19771       FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
19772           sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
19773     return true;
19774   }
19775 
19776   // The initializer of a constexpr variable or of the first declaration of a
19777   // static data member is not syntactically a constant evaluated constant,
19778   // but nonetheless is always required to be a constant expression, so we
19779   // can skip diagnosing.
19780   // FIXME: Using the mangling context here is a hack.
19781   if (auto *VD = dyn_cast_or_null<VarDecl>(
19782           ExprEvalContexts.back().ManglingContextDecl)) {
19783     if (VD->isConstexpr() ||
19784         (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
19785       return false;
19786     // FIXME: For any other kind of variable, we should build a CFG for its
19787     // initializer and check whether the context in question is reachable.
19788   }
19789 
19790   Diag(Loc, PD);
19791   return true;
19792 }
19793 
19794 /// Emit a diagnostic that describes an effect on the run-time behavior
19795 /// of the program being compiled.
19796 ///
19797 /// This routine emits the given diagnostic when the code currently being
19798 /// type-checked is "potentially evaluated", meaning that there is a
19799 /// possibility that the code will actually be executable. Code in sizeof()
19800 /// expressions, code used only during overload resolution, etc., are not
19801 /// potentially evaluated. This routine will suppress such diagnostics or,
19802 /// in the absolutely nutty case of potentially potentially evaluated
19803 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
19804 /// later.
19805 ///
19806 /// This routine should be used for all diagnostics that describe the run-time
19807 /// behavior of a program, such as passing a non-POD value through an ellipsis.
19808 /// Failure to do so will likely result in spurious diagnostics or failures
19809 /// during overload resolution or within sizeof/alignof/typeof/typeid.
19810 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
19811                                const PartialDiagnostic &PD) {
19812 
19813   if (ExprEvalContexts.back().isDiscardedStatementContext())
19814     return false;
19815 
19816   switch (ExprEvalContexts.back().Context) {
19817   case ExpressionEvaluationContext::Unevaluated:
19818   case ExpressionEvaluationContext::UnevaluatedList:
19819   case ExpressionEvaluationContext::UnevaluatedAbstract:
19820   case ExpressionEvaluationContext::DiscardedStatement:
19821     // The argument will never be evaluated, so don't complain.
19822     break;
19823 
19824   case ExpressionEvaluationContext::ConstantEvaluated:
19825   case ExpressionEvaluationContext::ImmediateFunctionContext:
19826     // Relevant diagnostics should be produced by constant evaluation.
19827     break;
19828 
19829   case ExpressionEvaluationContext::PotentiallyEvaluated:
19830   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19831     return DiagIfReachable(Loc, Stmts, PD);
19832   }
19833 
19834   return false;
19835 }
19836 
19837 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
19838                                const PartialDiagnostic &PD) {
19839   return DiagRuntimeBehavior(
19840       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
19841 }
19842 
19843 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
19844                                CallExpr *CE, FunctionDecl *FD) {
19845   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
19846     return false;
19847 
19848   // If we're inside a decltype's expression, don't check for a valid return
19849   // type or construct temporaries until we know whether this is the last call.
19850   if (ExprEvalContexts.back().ExprContext ==
19851       ExpressionEvaluationContextRecord::EK_Decltype) {
19852     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
19853     return false;
19854   }
19855 
19856   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
19857     FunctionDecl *FD;
19858     CallExpr *CE;
19859 
19860   public:
19861     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
19862       : FD(FD), CE(CE) { }
19863 
19864     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19865       if (!FD) {
19866         S.Diag(Loc, diag::err_call_incomplete_return)
19867           << T << CE->getSourceRange();
19868         return;
19869       }
19870 
19871       S.Diag(Loc, diag::err_call_function_incomplete_return)
19872           << CE->getSourceRange() << FD << T;
19873       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
19874           << FD->getDeclName();
19875     }
19876   } Diagnoser(FD, CE);
19877 
19878   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
19879     return true;
19880 
19881   return false;
19882 }
19883 
19884 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
19885 // will prevent this condition from triggering, which is what we want.
19886 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
19887   SourceLocation Loc;
19888 
19889   unsigned diagnostic = diag::warn_condition_is_assignment;
19890   bool IsOrAssign = false;
19891 
19892   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
19893     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
19894       return;
19895 
19896     IsOrAssign = Op->getOpcode() == BO_OrAssign;
19897 
19898     // Greylist some idioms by putting them into a warning subcategory.
19899     if (ObjCMessageExpr *ME
19900           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
19901       Selector Sel = ME->getSelector();
19902 
19903       // self = [<foo> init...]
19904       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
19905         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19906 
19907       // <foo> = [<bar> nextObject]
19908       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
19909         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19910     }
19911 
19912     Loc = Op->getOperatorLoc();
19913   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
19914     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
19915       return;
19916 
19917     IsOrAssign = Op->getOperator() == OO_PipeEqual;
19918     Loc = Op->getOperatorLoc();
19919   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
19920     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
19921   else {
19922     // Not an assignment.
19923     return;
19924   }
19925 
19926   Diag(Loc, diagnostic) << E->getSourceRange();
19927 
19928   SourceLocation Open = E->getBeginLoc();
19929   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
19930   Diag(Loc, diag::note_condition_assign_silence)
19931         << FixItHint::CreateInsertion(Open, "(")
19932         << FixItHint::CreateInsertion(Close, ")");
19933 
19934   if (IsOrAssign)
19935     Diag(Loc, diag::note_condition_or_assign_to_comparison)
19936       << FixItHint::CreateReplacement(Loc, "!=");
19937   else
19938     Diag(Loc, diag::note_condition_assign_to_comparison)
19939       << FixItHint::CreateReplacement(Loc, "==");
19940 }
19941 
19942 /// Redundant parentheses over an equality comparison can indicate
19943 /// that the user intended an assignment used as condition.
19944 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
19945   // Don't warn if the parens came from a macro.
19946   SourceLocation parenLoc = ParenE->getBeginLoc();
19947   if (parenLoc.isInvalid() || parenLoc.isMacroID())
19948     return;
19949   // Don't warn for dependent expressions.
19950   if (ParenE->isTypeDependent())
19951     return;
19952 
19953   Expr *E = ParenE->IgnoreParens();
19954 
19955   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
19956     if (opE->getOpcode() == BO_EQ &&
19957         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
19958                                                            == Expr::MLV_Valid) {
19959       SourceLocation Loc = opE->getOperatorLoc();
19960 
19961       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
19962       SourceRange ParenERange = ParenE->getSourceRange();
19963       Diag(Loc, diag::note_equality_comparison_silence)
19964         << FixItHint::CreateRemoval(ParenERange.getBegin())
19965         << FixItHint::CreateRemoval(ParenERange.getEnd());
19966       Diag(Loc, diag::note_equality_comparison_to_assign)
19967         << FixItHint::CreateReplacement(Loc, "=");
19968     }
19969 }
19970 
19971 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
19972                                        bool IsConstexpr) {
19973   DiagnoseAssignmentAsCondition(E);
19974   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
19975     DiagnoseEqualityWithExtraParens(parenE);
19976 
19977   ExprResult result = CheckPlaceholderExpr(E);
19978   if (result.isInvalid()) return ExprError();
19979   E = result.get();
19980 
19981   if (!E->isTypeDependent()) {
19982     if (getLangOpts().CPlusPlus)
19983       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
19984 
19985     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
19986     if (ERes.isInvalid())
19987       return ExprError();
19988     E = ERes.get();
19989 
19990     QualType T = E->getType();
19991     if (!T->isScalarType()) { // C99 6.8.4.1p1
19992       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
19993         << T << E->getSourceRange();
19994       return ExprError();
19995     }
19996     CheckBoolLikeConversion(E, Loc);
19997   }
19998 
19999   return E;
20000 }
20001 
20002 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
20003                                            Expr *SubExpr, ConditionKind CK,
20004                                            bool MissingOK) {
20005   // MissingOK indicates whether having no condition expression is valid
20006   // (for loop) or invalid (e.g. while loop).
20007   if (!SubExpr)
20008     return MissingOK ? ConditionResult() : ConditionError();
20009 
20010   ExprResult Cond;
20011   switch (CK) {
20012   case ConditionKind::Boolean:
20013     Cond = CheckBooleanCondition(Loc, SubExpr);
20014     break;
20015 
20016   case ConditionKind::ConstexprIf:
20017     Cond = CheckBooleanCondition(Loc, SubExpr, true);
20018     break;
20019 
20020   case ConditionKind::Switch:
20021     Cond = CheckSwitchCondition(Loc, SubExpr);
20022     break;
20023   }
20024   if (Cond.isInvalid()) {
20025     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20026                               {SubExpr}, PreferredConditionType(CK));
20027     if (!Cond.get())
20028       return ConditionError();
20029   }
20030   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20031   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
20032   if (!FullExpr.get())
20033     return ConditionError();
20034 
20035   return ConditionResult(*this, nullptr, FullExpr,
20036                          CK == ConditionKind::ConstexprIf);
20037 }
20038 
20039 namespace {
20040   /// A visitor for rebuilding a call to an __unknown_any expression
20041   /// to have an appropriate type.
20042   struct RebuildUnknownAnyFunction
20043     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20044 
20045     Sema &S;
20046 
20047     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20048 
20049     ExprResult VisitStmt(Stmt *S) {
20050       llvm_unreachable("unexpected statement!");
20051     }
20052 
20053     ExprResult VisitExpr(Expr *E) {
20054       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20055         << E->getSourceRange();
20056       return ExprError();
20057     }
20058 
20059     /// Rebuild an expression which simply semantically wraps another
20060     /// expression which it shares the type and value kind of.
20061     template <class T> ExprResult rebuildSugarExpr(T *E) {
20062       ExprResult SubResult = Visit(E->getSubExpr());
20063       if (SubResult.isInvalid()) return ExprError();
20064 
20065       Expr *SubExpr = SubResult.get();
20066       E->setSubExpr(SubExpr);
20067       E->setType(SubExpr->getType());
20068       E->setValueKind(SubExpr->getValueKind());
20069       assert(E->getObjectKind() == OK_Ordinary);
20070       return E;
20071     }
20072 
20073     ExprResult VisitParenExpr(ParenExpr *E) {
20074       return rebuildSugarExpr(E);
20075     }
20076 
20077     ExprResult VisitUnaryExtension(UnaryOperator *E) {
20078       return rebuildSugarExpr(E);
20079     }
20080 
20081     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20082       ExprResult SubResult = Visit(E->getSubExpr());
20083       if (SubResult.isInvalid()) return ExprError();
20084 
20085       Expr *SubExpr = SubResult.get();
20086       E->setSubExpr(SubExpr);
20087       E->setType(S.Context.getPointerType(SubExpr->getType()));
20088       assert(E->isPRValue());
20089       assert(E->getObjectKind() == OK_Ordinary);
20090       return E;
20091     }
20092 
20093     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20094       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20095 
20096       E->setType(VD->getType());
20097 
20098       assert(E->isPRValue());
20099       if (S.getLangOpts().CPlusPlus &&
20100           !(isa<CXXMethodDecl>(VD) &&
20101             cast<CXXMethodDecl>(VD)->isInstance()))
20102         E->setValueKind(VK_LValue);
20103 
20104       return E;
20105     }
20106 
20107     ExprResult VisitMemberExpr(MemberExpr *E) {
20108       return resolveDecl(E, E->getMemberDecl());
20109     }
20110 
20111     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20112       return resolveDecl(E, E->getDecl());
20113     }
20114   };
20115 }
20116 
20117 /// Given a function expression of unknown-any type, try to rebuild it
20118 /// to have a function type.
20119 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
20120   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20121   if (Result.isInvalid()) return ExprError();
20122   return S.DefaultFunctionArrayConversion(Result.get());
20123 }
20124 
20125 namespace {
20126   /// A visitor for rebuilding an expression of type __unknown_anytype
20127   /// into one which resolves the type directly on the referring
20128   /// expression.  Strict preservation of the original source
20129   /// structure is not a goal.
20130   struct RebuildUnknownAnyExpr
20131     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20132 
20133     Sema &S;
20134 
20135     /// The current destination type.
20136     QualType DestType;
20137 
20138     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20139       : S(S), DestType(CastType) {}
20140 
20141     ExprResult VisitStmt(Stmt *S) {
20142       llvm_unreachable("unexpected statement!");
20143     }
20144 
20145     ExprResult VisitExpr(Expr *E) {
20146       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20147         << E->getSourceRange();
20148       return ExprError();
20149     }
20150 
20151     ExprResult VisitCallExpr(CallExpr *E);
20152     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20153 
20154     /// Rebuild an expression which simply semantically wraps another
20155     /// expression which it shares the type and value kind of.
20156     template <class T> ExprResult rebuildSugarExpr(T *E) {
20157       ExprResult SubResult = Visit(E->getSubExpr());
20158       if (SubResult.isInvalid()) return ExprError();
20159       Expr *SubExpr = SubResult.get();
20160       E->setSubExpr(SubExpr);
20161       E->setType(SubExpr->getType());
20162       E->setValueKind(SubExpr->getValueKind());
20163       assert(E->getObjectKind() == OK_Ordinary);
20164       return E;
20165     }
20166 
20167     ExprResult VisitParenExpr(ParenExpr *E) {
20168       return rebuildSugarExpr(E);
20169     }
20170 
20171     ExprResult VisitUnaryExtension(UnaryOperator *E) {
20172       return rebuildSugarExpr(E);
20173     }
20174 
20175     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20176       const PointerType *Ptr = DestType->getAs<PointerType>();
20177       if (!Ptr) {
20178         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20179           << E->getSourceRange();
20180         return ExprError();
20181       }
20182 
20183       if (isa<CallExpr>(E->getSubExpr())) {
20184         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20185           << E->getSourceRange();
20186         return ExprError();
20187       }
20188 
20189       assert(E->isPRValue());
20190       assert(E->getObjectKind() == OK_Ordinary);
20191       E->setType(DestType);
20192 
20193       // Build the sub-expression as if it were an object of the pointee type.
20194       DestType = Ptr->getPointeeType();
20195       ExprResult SubResult = Visit(E->getSubExpr());
20196       if (SubResult.isInvalid()) return ExprError();
20197       E->setSubExpr(SubResult.get());
20198       return E;
20199     }
20200 
20201     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20202 
20203     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20204 
20205     ExprResult VisitMemberExpr(MemberExpr *E) {
20206       return resolveDecl(E, E->getMemberDecl());
20207     }
20208 
20209     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20210       return resolveDecl(E, E->getDecl());
20211     }
20212   };
20213 }
20214 
20215 /// Rebuilds a call expression which yielded __unknown_anytype.
20216 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20217   Expr *CalleeExpr = E->getCallee();
20218 
20219   enum FnKind {
20220     FK_MemberFunction,
20221     FK_FunctionPointer,
20222     FK_BlockPointer
20223   };
20224 
20225   FnKind Kind;
20226   QualType CalleeType = CalleeExpr->getType();
20227   if (CalleeType == S.Context.BoundMemberTy) {
20228     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20229     Kind = FK_MemberFunction;
20230     CalleeType = Expr::findBoundMemberType(CalleeExpr);
20231   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20232     CalleeType = Ptr->getPointeeType();
20233     Kind = FK_FunctionPointer;
20234   } else {
20235     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20236     Kind = FK_BlockPointer;
20237   }
20238   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20239 
20240   // Verify that this is a legal result type of a function.
20241   if (DestType->isArrayType() || DestType->isFunctionType()) {
20242     unsigned diagID = diag::err_func_returning_array_function;
20243     if (Kind == FK_BlockPointer)
20244       diagID = diag::err_block_returning_array_function;
20245 
20246     S.Diag(E->getExprLoc(), diagID)
20247       << DestType->isFunctionType() << DestType;
20248     return ExprError();
20249   }
20250 
20251   // Otherwise, go ahead and set DestType as the call's result.
20252   E->setType(DestType.getNonLValueExprType(S.Context));
20253   E->setValueKind(Expr::getValueKindForType(DestType));
20254   assert(E->getObjectKind() == OK_Ordinary);
20255 
20256   // Rebuild the function type, replacing the result type with DestType.
20257   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20258   if (Proto) {
20259     // __unknown_anytype(...) is a special case used by the debugger when
20260     // it has no idea what a function's signature is.
20261     //
20262     // We want to build this call essentially under the K&R
20263     // unprototyped rules, but making a FunctionNoProtoType in C++
20264     // would foul up all sorts of assumptions.  However, we cannot
20265     // simply pass all arguments as variadic arguments, nor can we
20266     // portably just call the function under a non-variadic type; see
20267     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20268     // However, it turns out that in practice it is generally safe to
20269     // call a function declared as "A foo(B,C,D);" under the prototype
20270     // "A foo(B,C,D,...);".  The only known exception is with the
20271     // Windows ABI, where any variadic function is implicitly cdecl
20272     // regardless of its normal CC.  Therefore we change the parameter
20273     // types to match the types of the arguments.
20274     //
20275     // This is a hack, but it is far superior to moving the
20276     // corresponding target-specific code from IR-gen to Sema/AST.
20277 
20278     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20279     SmallVector<QualType, 8> ArgTypes;
20280     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20281       ArgTypes.reserve(E->getNumArgs());
20282       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20283         ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20284       }
20285       ParamTypes = ArgTypes;
20286     }
20287     DestType = S.Context.getFunctionType(DestType, ParamTypes,
20288                                          Proto->getExtProtoInfo());
20289   } else {
20290     DestType = S.Context.getFunctionNoProtoType(DestType,
20291                                                 FnType->getExtInfo());
20292   }
20293 
20294   // Rebuild the appropriate pointer-to-function type.
20295   switch (Kind) {
20296   case FK_MemberFunction:
20297     // Nothing to do.
20298     break;
20299 
20300   case FK_FunctionPointer:
20301     DestType = S.Context.getPointerType(DestType);
20302     break;
20303 
20304   case FK_BlockPointer:
20305     DestType = S.Context.getBlockPointerType(DestType);
20306     break;
20307   }
20308 
20309   // Finally, we can recurse.
20310   ExprResult CalleeResult = Visit(CalleeExpr);
20311   if (!CalleeResult.isUsable()) return ExprError();
20312   E->setCallee(CalleeResult.get());
20313 
20314   // Bind a temporary if necessary.
20315   return S.MaybeBindToTemporary(E);
20316 }
20317 
20318 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20319   // Verify that this is a legal result type of a call.
20320   if (DestType->isArrayType() || DestType->isFunctionType()) {
20321     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20322       << DestType->isFunctionType() << DestType;
20323     return ExprError();
20324   }
20325 
20326   // Rewrite the method result type if available.
20327   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20328     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20329     Method->setReturnType(DestType);
20330   }
20331 
20332   // Change the type of the message.
20333   E->setType(DestType.getNonReferenceType());
20334   E->setValueKind(Expr::getValueKindForType(DestType));
20335 
20336   return S.MaybeBindToTemporary(E);
20337 }
20338 
20339 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20340   // The only case we should ever see here is a function-to-pointer decay.
20341   if (E->getCastKind() == CK_FunctionToPointerDecay) {
20342     assert(E->isPRValue());
20343     assert(E->getObjectKind() == OK_Ordinary);
20344 
20345     E->setType(DestType);
20346 
20347     // Rebuild the sub-expression as the pointee (function) type.
20348     DestType = DestType->castAs<PointerType>()->getPointeeType();
20349 
20350     ExprResult Result = Visit(E->getSubExpr());
20351     if (!Result.isUsable()) return ExprError();
20352 
20353     E->setSubExpr(Result.get());
20354     return E;
20355   } else if (E->getCastKind() == CK_LValueToRValue) {
20356     assert(E->isPRValue());
20357     assert(E->getObjectKind() == OK_Ordinary);
20358 
20359     assert(isa<BlockPointerType>(E->getType()));
20360 
20361     E->setType(DestType);
20362 
20363     // The sub-expression has to be a lvalue reference, so rebuild it as such.
20364     DestType = S.Context.getLValueReferenceType(DestType);
20365 
20366     ExprResult Result = Visit(E->getSubExpr());
20367     if (!Result.isUsable()) return ExprError();
20368 
20369     E->setSubExpr(Result.get());
20370     return E;
20371   } else {
20372     llvm_unreachable("Unhandled cast type!");
20373   }
20374 }
20375 
20376 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20377   ExprValueKind ValueKind = VK_LValue;
20378   QualType Type = DestType;
20379 
20380   // We know how to make this work for certain kinds of decls:
20381 
20382   //  - functions
20383   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20384     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20385       DestType = Ptr->getPointeeType();
20386       ExprResult Result = resolveDecl(E, VD);
20387       if (Result.isInvalid()) return ExprError();
20388       return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20389                                  VK_PRValue);
20390     }
20391 
20392     if (!Type->isFunctionType()) {
20393       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20394         << VD << E->getSourceRange();
20395       return ExprError();
20396     }
20397     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20398       // We must match the FunctionDecl's type to the hack introduced in
20399       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20400       // type. See the lengthy commentary in that routine.
20401       QualType FDT = FD->getType();
20402       const FunctionType *FnType = FDT->castAs<FunctionType>();
20403       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20404       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20405       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20406         SourceLocation Loc = FD->getLocation();
20407         FunctionDecl *NewFD = FunctionDecl::Create(
20408             S.Context, FD->getDeclContext(), Loc, Loc,
20409             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20410             SC_None, S.getCurFPFeatures().isFPConstrained(),
20411             false /*isInlineSpecified*/, FD->hasPrototype(),
20412             /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20413 
20414         if (FD->getQualifier())
20415           NewFD->setQualifierInfo(FD->getQualifierLoc());
20416 
20417         SmallVector<ParmVarDecl*, 16> Params;
20418         for (const auto &AI : FT->param_types()) {
20419           ParmVarDecl *Param =
20420             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
20421           Param->setScopeInfo(0, Params.size());
20422           Params.push_back(Param);
20423         }
20424         NewFD->setParams(Params);
20425         DRE->setDecl(NewFD);
20426         VD = DRE->getDecl();
20427       }
20428     }
20429 
20430     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20431       if (MD->isInstance()) {
20432         ValueKind = VK_PRValue;
20433         Type = S.Context.BoundMemberTy;
20434       }
20435 
20436     // Function references aren't l-values in C.
20437     if (!S.getLangOpts().CPlusPlus)
20438       ValueKind = VK_PRValue;
20439 
20440   //  - variables
20441   } else if (isa<VarDecl>(VD)) {
20442     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20443       Type = RefTy->getPointeeType();
20444     } else if (Type->isFunctionType()) {
20445       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20446         << VD << E->getSourceRange();
20447       return ExprError();
20448     }
20449 
20450   //  - nothing else
20451   } else {
20452     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20453       << VD << E->getSourceRange();
20454     return ExprError();
20455   }
20456 
20457   // Modifying the declaration like this is friendly to IR-gen but
20458   // also really dangerous.
20459   VD->setType(DestType);
20460   E->setType(Type);
20461   E->setValueKind(ValueKind);
20462   return E;
20463 }
20464 
20465 /// Check a cast of an unknown-any type.  We intentionally only
20466 /// trigger this for C-style casts.
20467 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
20468                                      Expr *CastExpr, CastKind &CastKind,
20469                                      ExprValueKind &VK, CXXCastPath &Path) {
20470   // The type we're casting to must be either void or complete.
20471   if (!CastType->isVoidType() &&
20472       RequireCompleteType(TypeRange.getBegin(), CastType,
20473                           diag::err_typecheck_cast_to_incomplete))
20474     return ExprError();
20475 
20476   // Rewrite the casted expression from scratch.
20477   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20478   if (!result.isUsable()) return ExprError();
20479 
20480   CastExpr = result.get();
20481   VK = CastExpr->getValueKind();
20482   CastKind = CK_NoOp;
20483 
20484   return CastExpr;
20485 }
20486 
20487 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
20488   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20489 }
20490 
20491 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
20492                                     Expr *arg, QualType &paramType) {
20493   // If the syntactic form of the argument is not an explicit cast of
20494   // any sort, just do default argument promotion.
20495   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20496   if (!castArg) {
20497     ExprResult result = DefaultArgumentPromotion(arg);
20498     if (result.isInvalid()) return ExprError();
20499     paramType = result.get()->getType();
20500     return result;
20501   }
20502 
20503   // Otherwise, use the type that was written in the explicit cast.
20504   assert(!arg->hasPlaceholderType());
20505   paramType = castArg->getTypeAsWritten();
20506 
20507   // Copy-initialize a parameter of that type.
20508   InitializedEntity entity =
20509     InitializedEntity::InitializeParameter(Context, paramType,
20510                                            /*consumed*/ false);
20511   return PerformCopyInitialization(entity, callLoc, arg);
20512 }
20513 
20514 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
20515   Expr *orig = E;
20516   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20517   while (true) {
20518     E = E->IgnoreParenImpCasts();
20519     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20520       E = call->getCallee();
20521       diagID = diag::err_uncasted_call_of_unknown_any;
20522     } else {
20523       break;
20524     }
20525   }
20526 
20527   SourceLocation loc;
20528   NamedDecl *d;
20529   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20530     loc = ref->getLocation();
20531     d = ref->getDecl();
20532   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20533     loc = mem->getMemberLoc();
20534     d = mem->getMemberDecl();
20535   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20536     diagID = diag::err_uncasted_call_of_unknown_any;
20537     loc = msg->getSelectorStartLoc();
20538     d = msg->getMethodDecl();
20539     if (!d) {
20540       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20541         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20542         << orig->getSourceRange();
20543       return ExprError();
20544     }
20545   } else {
20546     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20547       << E->getSourceRange();
20548     return ExprError();
20549   }
20550 
20551   S.Diag(loc, diagID) << d << orig->getSourceRange();
20552 
20553   // Never recoverable.
20554   return ExprError();
20555 }
20556 
20557 /// Check for operands with placeholder types and complain if found.
20558 /// Returns ExprError() if there was an error and no recovery was possible.
20559 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
20560   if (!Context.isDependenceAllowed()) {
20561     // C cannot handle TypoExpr nodes on either side of a binop because it
20562     // doesn't handle dependent types properly, so make sure any TypoExprs have
20563     // been dealt with before checking the operands.
20564     ExprResult Result = CorrectDelayedTyposInExpr(E);
20565     if (!Result.isUsable()) return ExprError();
20566     E = Result.get();
20567   }
20568 
20569   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20570   if (!placeholderType) return E;
20571 
20572   switch (placeholderType->getKind()) {
20573 
20574   // Overloaded expressions.
20575   case BuiltinType::Overload: {
20576     // Try to resolve a single function template specialization.
20577     // This is obligatory.
20578     ExprResult Result = E;
20579     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
20580       return Result;
20581 
20582     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20583     // leaves Result unchanged on failure.
20584     Result = E;
20585     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
20586       return Result;
20587 
20588     // If that failed, try to recover with a call.
20589     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
20590                          /*complain*/ true);
20591     return Result;
20592   }
20593 
20594   // Bound member functions.
20595   case BuiltinType::BoundMember: {
20596     ExprResult result = E;
20597     const Expr *BME = E->IgnoreParens();
20598     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
20599     // Try to give a nicer diagnostic if it is a bound member that we recognize.
20600     if (isa<CXXPseudoDestructorExpr>(BME)) {
20601       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
20602     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
20603       if (ME->getMemberNameInfo().getName().getNameKind() ==
20604           DeclarationName::CXXDestructorName)
20605         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
20606     }
20607     tryToRecoverWithCall(result, PD,
20608                          /*complain*/ true);
20609     return result;
20610   }
20611 
20612   // ARC unbridged casts.
20613   case BuiltinType::ARCUnbridgedCast: {
20614     Expr *realCast = stripARCUnbridgedCast(E);
20615     diagnoseARCUnbridgedCast(realCast);
20616     return realCast;
20617   }
20618 
20619   // Expressions of unknown type.
20620   case BuiltinType::UnknownAny:
20621     return diagnoseUnknownAnyExpr(*this, E);
20622 
20623   // Pseudo-objects.
20624   case BuiltinType::PseudoObject:
20625     return checkPseudoObjectRValue(E);
20626 
20627   case BuiltinType::BuiltinFn: {
20628     // Accept __noop without parens by implicitly converting it to a call expr.
20629     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
20630     if (DRE) {
20631       auto *FD = cast<FunctionDecl>(DRE->getDecl());
20632       unsigned BuiltinID = FD->getBuiltinID();
20633       if (BuiltinID == Builtin::BI__noop) {
20634         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
20635                               CK_BuiltinFnToFnPtr)
20636                 .get();
20637         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
20638                                 VK_PRValue, SourceLocation(),
20639                                 FPOptionsOverride());
20640       }
20641 
20642       if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
20643         // Any use of these other than a direct call is ill-formed as of C++20,
20644         // because they are not addressable functions. In earlier language
20645         // modes, warn and force an instantiation of the real body.
20646         Diag(E->getBeginLoc(),
20647              getLangOpts().CPlusPlus20
20648                  ? diag::err_use_of_unaddressable_function
20649                  : diag::warn_cxx20_compat_use_of_unaddressable_function);
20650         if (FD->isImplicitlyInstantiable()) {
20651           // Require a definition here because a normal attempt at
20652           // instantiation for a builtin will be ignored, and we won't try
20653           // again later. We assume that the definition of the template
20654           // precedes this use.
20655           InstantiateFunctionDefinition(E->getBeginLoc(), FD,
20656                                         /*Recursive=*/false,
20657                                         /*DefinitionRequired=*/true,
20658                                         /*AtEndOfTU=*/false);
20659         }
20660         // Produce a properly-typed reference to the function.
20661         CXXScopeSpec SS;
20662         SS.Adopt(DRE->getQualifierLoc());
20663         TemplateArgumentListInfo TemplateArgs;
20664         DRE->copyTemplateArgumentsInto(TemplateArgs);
20665         return BuildDeclRefExpr(
20666             FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
20667             DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
20668             DRE->getTemplateKeywordLoc(),
20669             DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
20670       }
20671     }
20672 
20673     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
20674     return ExprError();
20675   }
20676 
20677   case BuiltinType::IncompleteMatrixIdx:
20678     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
20679              ->getRowIdx()
20680              ->getBeginLoc(),
20681          diag::err_matrix_incomplete_index);
20682     return ExprError();
20683 
20684   // Expressions of unknown type.
20685   case BuiltinType::OMPArraySection:
20686     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
20687     return ExprError();
20688 
20689   // Expressions of unknown type.
20690   case BuiltinType::OMPArrayShaping:
20691     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
20692 
20693   case BuiltinType::OMPIterator:
20694     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
20695 
20696   // Everything else should be impossible.
20697 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
20698   case BuiltinType::Id:
20699 #include "clang/Basic/OpenCLImageTypes.def"
20700 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
20701   case BuiltinType::Id:
20702 #include "clang/Basic/OpenCLExtensionTypes.def"
20703 #define SVE_TYPE(Name, Id, SingletonId) \
20704   case BuiltinType::Id:
20705 #include "clang/Basic/AArch64SVEACLETypes.def"
20706 #define PPC_VECTOR_TYPE(Name, Id, Size) \
20707   case BuiltinType::Id:
20708 #include "clang/Basic/PPCTypes.def"
20709 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20710 #include "clang/Basic/RISCVVTypes.def"
20711 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
20712 #define PLACEHOLDER_TYPE(Id, SingletonId)
20713 #include "clang/AST/BuiltinTypes.def"
20714     break;
20715   }
20716 
20717   llvm_unreachable("invalid placeholder type!");
20718 }
20719 
20720 bool Sema::CheckCaseExpression(Expr *E) {
20721   if (E->isTypeDependent())
20722     return true;
20723   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
20724     return E->getType()->isIntegralOrEnumerationType();
20725   return false;
20726 }
20727 
20728 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
20729 ExprResult
20730 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
20731   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
20732          "Unknown Objective-C Boolean value!");
20733   QualType BoolT = Context.ObjCBuiltinBoolTy;
20734   if (!Context.getBOOLDecl()) {
20735     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
20736                         Sema::LookupOrdinaryName);
20737     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
20738       NamedDecl *ND = Result.getFoundDecl();
20739       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
20740         Context.setBOOLDecl(TD);
20741     }
20742   }
20743   if (Context.getBOOLDecl())
20744     BoolT = Context.getBOOLType();
20745   return new (Context)
20746       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
20747 }
20748 
20749 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
20750     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
20751     SourceLocation RParen) {
20752   auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
20753     auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20754       return Spec.getPlatform() == Platform;
20755     });
20756     // Transcribe the "ios" availability check to "maccatalyst" when compiling
20757     // for "maccatalyst" if "maccatalyst" is not specified.
20758     if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
20759       Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20760         return Spec.getPlatform() == "ios";
20761       });
20762     }
20763     if (Spec == AvailSpecs.end())
20764       return None;
20765     return Spec->getVersion();
20766   };
20767 
20768   VersionTuple Version;
20769   if (auto MaybeVersion =
20770           FindSpecVersion(Context.getTargetInfo().getPlatformName()))
20771     Version = *MaybeVersion;
20772 
20773   // The use of `@available` in the enclosing context should be analyzed to
20774   // warn when it's used inappropriately (i.e. not if(@available)).
20775   if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
20776     Context->HasPotentialAvailabilityViolations = true;
20777 
20778   return new (Context)
20779       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
20780 }
20781 
20782 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
20783                                     ArrayRef<Expr *> SubExprs, QualType T) {
20784   if (!Context.getLangOpts().RecoveryAST)
20785     return ExprError();
20786 
20787   if (isSFINAEContext())
20788     return ExprError();
20789 
20790   if (T.isNull() || T->isUndeducedType() ||
20791       !Context.getLangOpts().RecoveryASTType)
20792     // We don't know the concrete type, fallback to dependent type.
20793     T = Context.DependentTy;
20794 
20795   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
20796 }
20797