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/RecursiveASTVisitor.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/Builtins.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/AnalysisBasedWarnings.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Designator.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/Overload.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaFixItUtils.h"
47 #include "clang/Sema/SemaInternal.h"
48 #include "clang/Sema/Template.h"
49 #include "llvm/Support/ConvertUTF.h"
50 #include "llvm/Support/SaveAndRestore.h"
51 using namespace clang;
52 using namespace sema;
53 using llvm::RoundingMode;
54 
55 /// Determine whether the use of this declaration is valid, without
56 /// emitting diagnostics.
57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
58   // See if this is an auto-typed variable whose initializer we are parsing.
59   if (ParsingInitForAutoVars.count(D))
60     return false;
61 
62   // See if this is a deleted function.
63   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
64     if (FD->isDeleted())
65       return false;
66 
67     // If the function has a deduced return type, and we can't deduce it,
68     // then we can't use it either.
69     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
70         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
71       return false;
72 
73     // See if this is an aligned allocation/deallocation function that is
74     // unavailable.
75     if (TreatUnavailableAsInvalid &&
76         isUnavailableAlignedAllocationFunction(*FD))
77       return false;
78   }
79 
80   // See if this function is unavailable.
81   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
82       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
83     return false;
84 
85   return true;
86 }
87 
88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
89   // Warn if this is used but marked unused.
90   if (const auto *A = D->getAttr<UnusedAttr>()) {
91     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
92     // should diagnose them.
93     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
94         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
95       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
96       if (DC && !DC->hasAttr<UnusedAttr>())
97         S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
98     }
99   }
100 }
101 
102 /// Emit a note explaining that this function is deleted.
103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
104   assert(Decl && Decl->isDeleted());
105 
106   if (Decl->isDefaulted()) {
107     // If the method was explicitly defaulted, point at that declaration.
108     if (!Decl->isImplicit())
109       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
110 
111     // Try to diagnose why this special member function was implicitly
112     // deleted. This might fail, if that reason no longer applies.
113     DiagnoseDeletedDefaultedFunction(Decl);
114     return;
115   }
116 
117   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
118   if (Ctor && Ctor->isInheritingConstructor())
119     return NoteDeletedInheritingConstructor(Ctor);
120 
121   Diag(Decl->getLocation(), diag::note_availability_specified_here)
122     << Decl << 1;
123 }
124 
125 /// Determine whether a FunctionDecl was ever declared with an
126 /// explicit storage class.
127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
128   for (auto I : D->redecls()) {
129     if (I->getStorageClass() != SC_None)
130       return true;
131   }
132   return false;
133 }
134 
135 /// Check whether we're in an extern inline function and referring to a
136 /// variable or function with internal linkage (C11 6.7.4p3).
137 ///
138 /// This is only a warning because we used to silently accept this code, but
139 /// in many cases it will not behave correctly. This is not enabled in C++ mode
140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
141 /// and so while there may still be user mistakes, most of the time we can't
142 /// prove that there are errors.
143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
144                                                       const NamedDecl *D,
145                                                       SourceLocation Loc) {
146   // This is disabled under C++; there are too many ways for this to fire in
147   // contexts where the warning is a false positive, or where it is technically
148   // correct but benign.
149   if (S.getLangOpts().CPlusPlus)
150     return;
151 
152   // Check if this is an inlined function or method.
153   FunctionDecl *Current = S.getCurFunctionDecl();
154   if (!Current)
155     return;
156   if (!Current->isInlined())
157     return;
158   if (!Current->isExternallyVisible())
159     return;
160 
161   // Check if the decl has internal linkage.
162   if (D->getFormalLinkage() != InternalLinkage)
163     return;
164 
165   // Downgrade from ExtWarn to Extension if
166   //  (1) the supposedly external inline function is in the main file,
167   //      and probably won't be included anywhere else.
168   //  (2) the thing we're referencing is a pure function.
169   //  (3) the thing we're referencing is another inline function.
170   // This last can give us false negatives, but it's better than warning on
171   // wrappers for simple C library functions.
172   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
173   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
174   if (!DowngradeWarning && UsedFn)
175     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
176 
177   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
178                                : diag::ext_internal_in_extern_inline)
179     << /*IsVar=*/!UsedFn << D;
180 
181   S.MaybeSuggestAddingStaticToDecl(Current);
182 
183   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
184       << D;
185 }
186 
187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
188   const FunctionDecl *First = Cur->getFirstDecl();
189 
190   // Suggest "static" on the function, if possible.
191   if (!hasAnyExplicitStorageClass(First)) {
192     SourceLocation DeclBegin = First->getSourceRange().getBegin();
193     Diag(DeclBegin, diag::note_convert_inline_to_static)
194       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
195   }
196 }
197 
198 /// Determine whether the use of this declaration is valid, and
199 /// emit any corresponding diagnostics.
200 ///
201 /// This routine diagnoses various problems with referencing
202 /// declarations that can occur when using a declaration. For example,
203 /// it might warn if a deprecated or unavailable declaration is being
204 /// used, or produce an error (and return true) if a C++0x deleted
205 /// function is being used.
206 ///
207 /// \returns true if there was an error (this declaration cannot be
208 /// referenced), false otherwise.
209 ///
210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
211                              const ObjCInterfaceDecl *UnknownObjCClass,
212                              bool ObjCPropertyAccess,
213                              bool AvoidPartialAvailabilityChecks,
214                              ObjCInterfaceDecl *ClassReceiver) {
215   SourceLocation Loc = Locs.front();
216   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
217     // If there were any diagnostics suppressed by template argument deduction,
218     // emit them now.
219     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
220     if (Pos != SuppressedDiagnostics.end()) {
221       for (const PartialDiagnosticAt &Suppressed : Pos->second)
222         Diag(Suppressed.first, Suppressed.second);
223 
224       // Clear out the list of suppressed diagnostics, so that we don't emit
225       // them again for this specialization. However, we don't obsolete this
226       // entry from the table, because we want to avoid ever emitting these
227       // diagnostics again.
228       Pos->second.clear();
229     }
230 
231     // C++ [basic.start.main]p3:
232     //   The function 'main' shall not be used within a program.
233     if (cast<FunctionDecl>(D)->isMain())
234       Diag(Loc, diag::ext_main_used);
235 
236     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
237   }
238 
239   // See if this is an auto-typed variable whose initializer we are parsing.
240   if (ParsingInitForAutoVars.count(D)) {
241     if (isa<BindingDecl>(D)) {
242       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
243         << D->getDeclName();
244     } else {
245       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
246         << D->getDeclName() << cast<VarDecl>(D)->getType();
247     }
248     return true;
249   }
250 
251   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
252     // See if this is a deleted function.
253     if (FD->isDeleted()) {
254       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
255       if (Ctor && Ctor->isInheritingConstructor())
256         Diag(Loc, diag::err_deleted_inherited_ctor_use)
257             << Ctor->getParent()
258             << Ctor->getInheritedConstructor().getConstructor()->getParent();
259       else
260         Diag(Loc, diag::err_deleted_function_use);
261       NoteDeletedFunction(FD);
262       return true;
263     }
264 
265     // [expr.prim.id]p4
266     //   A program that refers explicitly or implicitly to a function with a
267     //   trailing requires-clause whose constraint-expression is not satisfied,
268     //   other than to declare it, is ill-formed. [...]
269     //
270     // See if this is a function with constraints that need to be satisfied.
271     // Check this before deducing the return type, as it might instantiate the
272     // definition.
273     if (FD->getTrailingRequiresClause()) {
274       ConstraintSatisfaction Satisfaction;
275       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
276         // A diagnostic will have already been generated (non-constant
277         // constraint expression, for example)
278         return true;
279       if (!Satisfaction.IsSatisfied) {
280         Diag(Loc,
281              diag::err_reference_to_function_with_unsatisfied_constraints)
282             << D;
283         DiagnoseUnsatisfiedConstraint(Satisfaction);
284         return true;
285       }
286     }
287 
288     // If the function has a deduced return type, and we can't deduce it,
289     // then we can't use it either.
290     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
291         DeduceReturnType(FD, Loc))
292       return true;
293 
294     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
295       return true;
296 
297     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
298       return true;
299   }
300 
301   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
302     // Lambdas are only default-constructible or assignable in C++2a onwards.
303     if (MD->getParent()->isLambda() &&
304         ((isa<CXXConstructorDecl>(MD) &&
305           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
306          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
307       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
308         << !isa<CXXConstructorDecl>(MD);
309     }
310   }
311 
312   auto getReferencedObjCProp = [](const NamedDecl *D) ->
313                                       const ObjCPropertyDecl * {
314     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
315       return MD->findPropertyDecl();
316     return nullptr;
317   };
318   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
319     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
320       return true;
321   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
322       return true;
323   }
324 
325   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
326   // Only the variables omp_in and omp_out are allowed in the combiner.
327   // Only the variables omp_priv and omp_orig are allowed in the
328   // initializer-clause.
329   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
330   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
331       isa<VarDecl>(D)) {
332     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
333         << getCurFunction()->HasOMPDeclareReductionCombiner;
334     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
335     return true;
336   }
337 
338   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
339   //  List-items in map clauses on this construct may only refer to the declared
340   //  variable var and entities that could be referenced by a procedure defined
341   //  at the same location
342   if (LangOpts.OpenMP && isa<VarDecl>(D) &&
343       !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
344     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
345         << getOpenMPDeclareMapperVarName();
346     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
347     return true;
348   }
349 
350   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
351                              AvoidPartialAvailabilityChecks, ClassReceiver);
352 
353   DiagnoseUnusedOfDecl(*this, D, Loc);
354 
355   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
356 
357   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
358     if (const auto *VD = dyn_cast<ValueDecl>(D))
359       checkDeviceDecl(VD, Loc);
360 
361     if (!Context.getTargetInfo().isTLSSupported())
362       if (const auto *VD = dyn_cast<VarDecl>(D))
363         if (VD->getTLSKind() != VarDecl::TLS_None)
364           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
365   }
366 
367   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
368       !isUnevaluatedContext()) {
369     // C++ [expr.prim.req.nested] p3
370     //   A local parameter shall only appear as an unevaluated operand
371     //   (Clause 8) within the constraint-expression.
372     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
373         << D;
374     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
375     return true;
376   }
377 
378   return false;
379 }
380 
381 /// DiagnoseSentinelCalls - This routine checks whether a call or
382 /// message-send is to a declaration with the sentinel attribute, and
383 /// if so, it checks that the requirements of the sentinel are
384 /// satisfied.
385 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
386                                  ArrayRef<Expr *> Args) {
387   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
388   if (!attr)
389     return;
390 
391   // The number of formal parameters of the declaration.
392   unsigned numFormalParams;
393 
394   // The kind of declaration.  This is also an index into a %select in
395   // the diagnostic.
396   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
397 
398   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
399     numFormalParams = MD->param_size();
400     calleeType = CT_Method;
401   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
402     numFormalParams = FD->param_size();
403     calleeType = CT_Function;
404   } else if (isa<VarDecl>(D)) {
405     QualType type = cast<ValueDecl>(D)->getType();
406     const FunctionType *fn = nullptr;
407     if (const PointerType *ptr = type->getAs<PointerType>()) {
408       fn = ptr->getPointeeType()->getAs<FunctionType>();
409       if (!fn) return;
410       calleeType = CT_Function;
411     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
412       fn = ptr->getPointeeType()->castAs<FunctionType>();
413       calleeType = CT_Block;
414     } else {
415       return;
416     }
417 
418     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
419       numFormalParams = proto->getNumParams();
420     } else {
421       numFormalParams = 0;
422     }
423   } else {
424     return;
425   }
426 
427   // "nullPos" is the number of formal parameters at the end which
428   // effectively count as part of the variadic arguments.  This is
429   // useful if you would prefer to not have *any* formal parameters,
430   // but the language forces you to have at least one.
431   unsigned nullPos = attr->getNullPos();
432   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
433   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
434 
435   // The number of arguments which should follow the sentinel.
436   unsigned numArgsAfterSentinel = attr->getSentinel();
437 
438   // If there aren't enough arguments for all the formal parameters,
439   // the sentinel, and the args after the sentinel, complain.
440   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
441     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
442     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
443     return;
444   }
445 
446   // Otherwise, find the sentinel expression.
447   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
448   if (!sentinelExpr) return;
449   if (sentinelExpr->isValueDependent()) return;
450   if (Context.isSentinelNullExpr(sentinelExpr)) return;
451 
452   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
453   // or 'NULL' if those are actually defined in the context.  Only use
454   // 'nil' for ObjC methods, where it's much more likely that the
455   // variadic arguments form a list of object pointers.
456   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
457   std::string NullValue;
458   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
459     NullValue = "nil";
460   else if (getLangOpts().CPlusPlus11)
461     NullValue = "nullptr";
462   else if (PP.isMacroDefined("NULL"))
463     NullValue = "NULL";
464   else
465     NullValue = "(void*) 0";
466 
467   if (MissingNilLoc.isInvalid())
468     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
469   else
470     Diag(MissingNilLoc, diag::warn_missing_sentinel)
471       << int(calleeType)
472       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
473   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
474 }
475 
476 SourceRange Sema::getExprRange(Expr *E) const {
477   return E ? E->getSourceRange() : SourceRange();
478 }
479 
480 //===----------------------------------------------------------------------===//
481 //  Standard Promotions and Conversions
482 //===----------------------------------------------------------------------===//
483 
484 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
485 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
486   // Handle any placeholder expressions which made it here.
487   if (E->getType()->isPlaceholderType()) {
488     ExprResult result = CheckPlaceholderExpr(E);
489     if (result.isInvalid()) return ExprError();
490     E = result.get();
491   }
492 
493   QualType Ty = E->getType();
494   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
495 
496   if (Ty->isFunctionType()) {
497     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
498       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
499         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
500           return ExprError();
501 
502     E = ImpCastExprToType(E, Context.getPointerType(Ty),
503                           CK_FunctionToPointerDecay).get();
504   } else if (Ty->isArrayType()) {
505     // In C90 mode, arrays only promote to pointers if the array expression is
506     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
507     // type 'array of type' is converted to an expression that has type 'pointer
508     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
509     // that has type 'array of type' ...".  The relevant change is "an lvalue"
510     // (C90) to "an expression" (C99).
511     //
512     // C++ 4.2p1:
513     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
514     // T" can be converted to an rvalue of type "pointer to T".
515     //
516     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
517       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
518                             CK_ArrayToPointerDecay).get();
519   }
520   return E;
521 }
522 
523 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
524   // Check to see if we are dereferencing a null pointer.  If so,
525   // and if not volatile-qualified, this is undefined behavior that the
526   // optimizer will delete, so warn about it.  People sometimes try to use this
527   // to get a deterministic trap and are surprised by clang's behavior.  This
528   // only handles the pattern "*null", which is a very syntactic check.
529   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
530   if (UO && UO->getOpcode() == UO_Deref &&
531       UO->getSubExpr()->getType()->isPointerType()) {
532     const LangAS AS =
533         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
534     if ((!isTargetAddressSpace(AS) ||
535          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
536         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
537             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
538         !UO->getType().isVolatileQualified()) {
539       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
540                             S.PDiag(diag::warn_indirection_through_null)
541                                 << UO->getSubExpr()->getSourceRange());
542       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
543                             S.PDiag(diag::note_indirection_through_null));
544     }
545   }
546 }
547 
548 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
549                                     SourceLocation AssignLoc,
550                                     const Expr* RHS) {
551   const ObjCIvarDecl *IV = OIRE->getDecl();
552   if (!IV)
553     return;
554 
555   DeclarationName MemberName = IV->getDeclName();
556   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
557   if (!Member || !Member->isStr("isa"))
558     return;
559 
560   const Expr *Base = OIRE->getBase();
561   QualType BaseType = Base->getType();
562   if (OIRE->isArrow())
563     BaseType = BaseType->getPointeeType();
564   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
565     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
566       ObjCInterfaceDecl *ClassDeclared = nullptr;
567       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
568       if (!ClassDeclared->getSuperClass()
569           && (*ClassDeclared->ivar_begin()) == IV) {
570         if (RHS) {
571           NamedDecl *ObjectSetClass =
572             S.LookupSingleName(S.TUScope,
573                                &S.Context.Idents.get("object_setClass"),
574                                SourceLocation(), S.LookupOrdinaryName);
575           if (ObjectSetClass) {
576             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
577             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
578                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
579                                               "object_setClass(")
580                 << FixItHint::CreateReplacement(
581                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
582                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
583           }
584           else
585             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
586         } else {
587           NamedDecl *ObjectGetClass =
588             S.LookupSingleName(S.TUScope,
589                                &S.Context.Idents.get("object_getClass"),
590                                SourceLocation(), S.LookupOrdinaryName);
591           if (ObjectGetClass)
592             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
593                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
594                                               "object_getClass(")
595                 << FixItHint::CreateReplacement(
596                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
597           else
598             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
599         }
600         S.Diag(IV->getLocation(), diag::note_ivar_decl);
601       }
602     }
603 }
604 
605 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
606   // Handle any placeholder expressions which made it here.
607   if (E->getType()->isPlaceholderType()) {
608     ExprResult result = CheckPlaceholderExpr(E);
609     if (result.isInvalid()) return ExprError();
610     E = result.get();
611   }
612 
613   // C++ [conv.lval]p1:
614   //   A glvalue of a non-function, non-array type T can be
615   //   converted to a prvalue.
616   if (!E->isGLValue()) return E;
617 
618   QualType T = E->getType();
619   assert(!T.isNull() && "r-value conversion on typeless expression?");
620 
621   // lvalue-to-rvalue conversion cannot be applied to function or array types.
622   if (T->isFunctionType() || T->isArrayType())
623     return E;
624 
625   // We don't want to throw lvalue-to-rvalue casts on top of
626   // expressions of certain types in C++.
627   if (getLangOpts().CPlusPlus &&
628       (E->getType() == Context.OverloadTy ||
629        T->isDependentType() ||
630        T->isRecordType()))
631     return E;
632 
633   // The C standard is actually really unclear on this point, and
634   // DR106 tells us what the result should be but not why.  It's
635   // generally best to say that void types just doesn't undergo
636   // lvalue-to-rvalue at all.  Note that expressions of unqualified
637   // 'void' type are never l-values, but qualified void can be.
638   if (T->isVoidType())
639     return E;
640 
641   // OpenCL usually rejects direct accesses to values of 'half' type.
642   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
643       T->isHalfType()) {
644     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
645       << 0 << T;
646     return ExprError();
647   }
648 
649   CheckForNullPointerDereference(*this, E);
650   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
651     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
652                                      &Context.Idents.get("object_getClass"),
653                                      SourceLocation(), LookupOrdinaryName);
654     if (ObjectGetClass)
655       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
656           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
657           << FixItHint::CreateReplacement(
658                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
659     else
660       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
661   }
662   else if (const ObjCIvarRefExpr *OIRE =
663             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
664     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
665 
666   // C++ [conv.lval]p1:
667   //   [...] If T is a non-class type, the type of the prvalue is the
668   //   cv-unqualified version of T. Otherwise, the type of the
669   //   rvalue is T.
670   //
671   // C99 6.3.2.1p2:
672   //   If the lvalue has qualified type, the value has the unqualified
673   //   version of the type of the lvalue; otherwise, the value has the
674   //   type of the lvalue.
675   if (T.hasQualifiers())
676     T = T.getUnqualifiedType();
677 
678   // Under the MS ABI, lock down the inheritance model now.
679   if (T->isMemberPointerType() &&
680       Context.getTargetInfo().getCXXABI().isMicrosoft())
681     (void)isCompleteType(E->getExprLoc(), T);
682 
683   ExprResult Res = CheckLValueToRValueConversionOperand(E);
684   if (Res.isInvalid())
685     return Res;
686   E = Res.get();
687 
688   // Loading a __weak object implicitly retains the value, so we need a cleanup to
689   // balance that.
690   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
691     Cleanup.setExprNeedsCleanups(true);
692 
693   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
694     Cleanup.setExprNeedsCleanups(true);
695 
696   // C++ [conv.lval]p3:
697   //   If T is cv std::nullptr_t, the result is a null pointer constant.
698   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
699   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue,
700                                  CurFPFeatureOverrides());
701 
702   // C11 6.3.2.1p2:
703   //   ... if the lvalue has atomic type, the value has the non-atomic version
704   //   of the type of the lvalue ...
705   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
706     T = Atomic->getValueType().getUnqualifiedType();
707     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
708                                    nullptr, VK_RValue, FPOptionsOverride());
709   }
710 
711   return Res;
712 }
713 
714 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
715   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
716   if (Res.isInvalid())
717     return ExprError();
718   Res = DefaultLvalueConversion(Res.get());
719   if (Res.isInvalid())
720     return ExprError();
721   return Res;
722 }
723 
724 /// CallExprUnaryConversions - a special case of an unary conversion
725 /// performed on a function designator of a call expression.
726 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
727   QualType Ty = E->getType();
728   ExprResult Res = E;
729   // Only do implicit cast for a function type, but not for a pointer
730   // to function type.
731   if (Ty->isFunctionType()) {
732     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
733                             CK_FunctionToPointerDecay);
734     if (Res.isInvalid())
735       return ExprError();
736   }
737   Res = DefaultLvalueConversion(Res.get());
738   if (Res.isInvalid())
739     return ExprError();
740   return Res.get();
741 }
742 
743 /// UsualUnaryConversions - Performs various conversions that are common to most
744 /// operators (C99 6.3). The conversions of array and function types are
745 /// sometimes suppressed. For example, the array->pointer conversion doesn't
746 /// apply if the array is an argument to the sizeof or address (&) operators.
747 /// In these instances, this routine should *not* be called.
748 ExprResult Sema::UsualUnaryConversions(Expr *E) {
749   // First, convert to an r-value.
750   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
751   if (Res.isInvalid())
752     return ExprError();
753   E = Res.get();
754 
755   QualType Ty = E->getType();
756   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
757 
758   // Half FP have to be promoted to float unless it is natively supported
759   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
760     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
761 
762   // Try to perform integral promotions if the object has a theoretically
763   // promotable type.
764   if (Ty->isIntegralOrUnscopedEnumerationType()) {
765     // C99 6.3.1.1p2:
766     //
767     //   The following may be used in an expression wherever an int or
768     //   unsigned int may be used:
769     //     - an object or expression with an integer type whose integer
770     //       conversion rank is less than or equal to the rank of int
771     //       and unsigned int.
772     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
773     //
774     //   If an int can represent all values of the original type, the
775     //   value is converted to an int; otherwise, it is converted to an
776     //   unsigned int. These are called the integer promotions. All
777     //   other types are unchanged by the integer promotions.
778 
779     QualType PTy = Context.isPromotableBitField(E);
780     if (!PTy.isNull()) {
781       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
782       return E;
783     }
784     if (Ty->isPromotableIntegerType()) {
785       QualType PT = Context.getPromotedIntegerType(Ty);
786       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
787       return E;
788     }
789   }
790   return E;
791 }
792 
793 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
794 /// do not have a prototype. Arguments that have type float or __fp16
795 /// are promoted to double. All other argument types are converted by
796 /// UsualUnaryConversions().
797 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
798   QualType Ty = E->getType();
799   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
800 
801   ExprResult Res = UsualUnaryConversions(E);
802   if (Res.isInvalid())
803     return ExprError();
804   E = Res.get();
805 
806   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
807   // promote to double.
808   // Note that default argument promotion applies only to float (and
809   // half/fp16); it does not apply to _Float16.
810   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
811   if (BTy && (BTy->getKind() == BuiltinType::Half ||
812               BTy->getKind() == BuiltinType::Float)) {
813     if (getLangOpts().OpenCL &&
814         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
815         if (BTy->getKind() == BuiltinType::Half) {
816             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
817         }
818     } else {
819       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
820     }
821   }
822 
823   // C++ performs lvalue-to-rvalue conversion as a default argument
824   // promotion, even on class types, but note:
825   //   C++11 [conv.lval]p2:
826   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
827   //     operand or a subexpression thereof the value contained in the
828   //     referenced object is not accessed. Otherwise, if the glvalue
829   //     has a class type, the conversion copy-initializes a temporary
830   //     of type T from the glvalue and the result of the conversion
831   //     is a prvalue for the temporary.
832   // FIXME: add some way to gate this entire thing for correctness in
833   // potentially potentially evaluated contexts.
834   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
835     ExprResult Temp = PerformCopyInitialization(
836                        InitializedEntity::InitializeTemporary(E->getType()),
837                                                 E->getExprLoc(), E);
838     if (Temp.isInvalid())
839       return ExprError();
840     E = Temp.get();
841   }
842 
843   return E;
844 }
845 
846 /// Determine the degree of POD-ness for an expression.
847 /// Incomplete types are considered POD, since this check can be performed
848 /// when we're in an unevaluated context.
849 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
850   if (Ty->isIncompleteType()) {
851     // C++11 [expr.call]p7:
852     //   After these conversions, if the argument does not have arithmetic,
853     //   enumeration, pointer, pointer to member, or class type, the program
854     //   is ill-formed.
855     //
856     // Since we've already performed array-to-pointer and function-to-pointer
857     // decay, the only such type in C++ is cv void. This also handles
858     // initializer lists as variadic arguments.
859     if (Ty->isVoidType())
860       return VAK_Invalid;
861 
862     if (Ty->isObjCObjectType())
863       return VAK_Invalid;
864     return VAK_Valid;
865   }
866 
867   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
868     return VAK_Invalid;
869 
870   if (Ty.isCXX98PODType(Context))
871     return VAK_Valid;
872 
873   // C++11 [expr.call]p7:
874   //   Passing a potentially-evaluated argument of class type (Clause 9)
875   //   having a non-trivial copy constructor, a non-trivial move constructor,
876   //   or a non-trivial destructor, with no corresponding parameter,
877   //   is conditionally-supported with implementation-defined semantics.
878   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
879     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
880       if (!Record->hasNonTrivialCopyConstructor() &&
881           !Record->hasNonTrivialMoveConstructor() &&
882           !Record->hasNonTrivialDestructor())
883         return VAK_ValidInCXX11;
884 
885   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
886     return VAK_Valid;
887 
888   if (Ty->isObjCObjectType())
889     return VAK_Invalid;
890 
891   if (getLangOpts().MSVCCompat)
892     return VAK_MSVCUndefined;
893 
894   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
895   // permitted to reject them. We should consider doing so.
896   return VAK_Undefined;
897 }
898 
899 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
900   // Don't allow one to pass an Objective-C interface to a vararg.
901   const QualType &Ty = E->getType();
902   VarArgKind VAK = isValidVarArgType(Ty);
903 
904   // Complain about passing non-POD types through varargs.
905   switch (VAK) {
906   case VAK_ValidInCXX11:
907     DiagRuntimeBehavior(
908         E->getBeginLoc(), nullptr,
909         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
910     LLVM_FALLTHROUGH;
911   case VAK_Valid:
912     if (Ty->isRecordType()) {
913       // This is unlikely to be what the user intended. If the class has a
914       // 'c_str' member function, the user probably meant to call that.
915       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
916                           PDiag(diag::warn_pass_class_arg_to_vararg)
917                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
918     }
919     break;
920 
921   case VAK_Undefined:
922   case VAK_MSVCUndefined:
923     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
924                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
925                             << getLangOpts().CPlusPlus11 << Ty << CT);
926     break;
927 
928   case VAK_Invalid:
929     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
930       Diag(E->getBeginLoc(),
931            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
932           << Ty << CT;
933     else if (Ty->isObjCObjectType())
934       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
935                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
936                               << Ty << CT);
937     else
938       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
939           << isa<InitListExpr>(E) << Ty << CT;
940     break;
941   }
942 }
943 
944 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
945 /// will create a trap if the resulting type is not a POD type.
946 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
947                                                   FunctionDecl *FDecl) {
948   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
949     // Strip the unbridged-cast placeholder expression off, if applicable.
950     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
951         (CT == VariadicMethod ||
952          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
953       E = stripARCUnbridgedCast(E);
954 
955     // Otherwise, do normal placeholder checking.
956     } else {
957       ExprResult ExprRes = CheckPlaceholderExpr(E);
958       if (ExprRes.isInvalid())
959         return ExprError();
960       E = ExprRes.get();
961     }
962   }
963 
964   ExprResult ExprRes = DefaultArgumentPromotion(E);
965   if (ExprRes.isInvalid())
966     return ExprError();
967 
968   // Copy blocks to the heap.
969   if (ExprRes.get()->getType()->isBlockPointerType())
970     maybeExtendBlockObject(ExprRes);
971 
972   E = ExprRes.get();
973 
974   // Diagnostics regarding non-POD argument types are
975   // emitted along with format string checking in Sema::CheckFunctionCall().
976   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
977     // Turn this into a trap.
978     CXXScopeSpec SS;
979     SourceLocation TemplateKWLoc;
980     UnqualifiedId Name;
981     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
982                        E->getBeginLoc());
983     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
984                                           /*HasTrailingLParen=*/true,
985                                           /*IsAddressOfOperand=*/false);
986     if (TrapFn.isInvalid())
987       return ExprError();
988 
989     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
990                                     None, E->getEndLoc());
991     if (Call.isInvalid())
992       return ExprError();
993 
994     ExprResult Comma =
995         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
996     if (Comma.isInvalid())
997       return ExprError();
998     return Comma.get();
999   }
1000 
1001   if (!getLangOpts().CPlusPlus &&
1002       RequireCompleteType(E->getExprLoc(), E->getType(),
1003                           diag::err_call_incomplete_argument))
1004     return ExprError();
1005 
1006   return E;
1007 }
1008 
1009 /// Converts an integer to complex float type.  Helper function of
1010 /// UsualArithmeticConversions()
1011 ///
1012 /// \return false if the integer expression is an integer type and is
1013 /// successfully converted to the complex type.
1014 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1015                                                   ExprResult &ComplexExpr,
1016                                                   QualType IntTy,
1017                                                   QualType ComplexTy,
1018                                                   bool SkipCast) {
1019   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1020   if (SkipCast) return false;
1021   if (IntTy->isIntegerType()) {
1022     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1023     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1024     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1025                                   CK_FloatingRealToComplex);
1026   } else {
1027     assert(IntTy->isComplexIntegerType());
1028     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1029                                   CK_IntegralComplexToFloatingComplex);
1030   }
1031   return false;
1032 }
1033 
1034 /// Handle arithmetic conversion with complex types.  Helper function of
1035 /// UsualArithmeticConversions()
1036 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1037                                              ExprResult &RHS, QualType LHSType,
1038                                              QualType RHSType,
1039                                              bool IsCompAssign) {
1040   // if we have an integer operand, the result is the complex type.
1041   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1042                                              /*skipCast*/false))
1043     return LHSType;
1044   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1045                                              /*skipCast*/IsCompAssign))
1046     return RHSType;
1047 
1048   // This handles complex/complex, complex/float, or float/complex.
1049   // When both operands are complex, the shorter operand is converted to the
1050   // type of the longer, and that is the type of the result. This corresponds
1051   // to what is done when combining two real floating-point operands.
1052   // The fun begins when size promotion occur across type domains.
1053   // From H&S 6.3.4: When one operand is complex and the other is a real
1054   // floating-point type, the less precise type is converted, within it's
1055   // real or complex domain, to the precision of the other type. For example,
1056   // when combining a "long double" with a "double _Complex", the
1057   // "double _Complex" is promoted to "long double _Complex".
1058 
1059   // Compute the rank of the two types, regardless of whether they are complex.
1060   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1061 
1062   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1063   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1064   QualType LHSElementType =
1065       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1066   QualType RHSElementType =
1067       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1068 
1069   QualType ResultType = S.Context.getComplexType(LHSElementType);
1070   if (Order < 0) {
1071     // Promote the precision of the LHS if not an assignment.
1072     ResultType = S.Context.getComplexType(RHSElementType);
1073     if (!IsCompAssign) {
1074       if (LHSComplexType)
1075         LHS =
1076             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1077       else
1078         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1079     }
1080   } else if (Order > 0) {
1081     // Promote the precision of the RHS.
1082     if (RHSComplexType)
1083       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1084     else
1085       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1086   }
1087   return ResultType;
1088 }
1089 
1090 /// Handle arithmetic conversion from integer to float.  Helper function
1091 /// of UsualArithmeticConversions()
1092 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1093                                            ExprResult &IntExpr,
1094                                            QualType FloatTy, QualType IntTy,
1095                                            bool ConvertFloat, bool ConvertInt) {
1096   if (IntTy->isIntegerType()) {
1097     if (ConvertInt)
1098       // Convert intExpr to the lhs floating point type.
1099       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1100                                     CK_IntegralToFloating);
1101     return FloatTy;
1102   }
1103 
1104   // Convert both sides to the appropriate complex float.
1105   assert(IntTy->isComplexIntegerType());
1106   QualType result = S.Context.getComplexType(FloatTy);
1107 
1108   // _Complex int -> _Complex float
1109   if (ConvertInt)
1110     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1111                                   CK_IntegralComplexToFloatingComplex);
1112 
1113   // float -> _Complex float
1114   if (ConvertFloat)
1115     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1116                                     CK_FloatingRealToComplex);
1117 
1118   return result;
1119 }
1120 
1121 /// Handle arithmethic conversion with floating point types.  Helper
1122 /// function of UsualArithmeticConversions()
1123 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1124                                       ExprResult &RHS, QualType LHSType,
1125                                       QualType RHSType, bool IsCompAssign) {
1126   bool LHSFloat = LHSType->isRealFloatingType();
1127   bool RHSFloat = RHSType->isRealFloatingType();
1128 
1129   // N1169 4.1.4: If one of the operands has a floating type and the other
1130   //              operand has a fixed-point type, the fixed-point operand
1131   //              is converted to the floating type [...]
1132   if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1133     if (LHSFloat)
1134       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1135     else if (!IsCompAssign)
1136       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1137     return LHSFloat ? LHSType : RHSType;
1138   }
1139 
1140   // If we have two real floating types, convert the smaller operand
1141   // to the bigger result.
1142   if (LHSFloat && RHSFloat) {
1143     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1144     if (order > 0) {
1145       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1146       return LHSType;
1147     }
1148 
1149     assert(order < 0 && "illegal float comparison");
1150     if (!IsCompAssign)
1151       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1152     return RHSType;
1153   }
1154 
1155   if (LHSFloat) {
1156     // Half FP has to be promoted to float unless it is natively supported
1157     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1158       LHSType = S.Context.FloatTy;
1159 
1160     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1161                                       /*ConvertFloat=*/!IsCompAssign,
1162                                       /*ConvertInt=*/ true);
1163   }
1164   assert(RHSFloat);
1165   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1166                                     /*ConvertFloat=*/ true,
1167                                     /*ConvertInt=*/!IsCompAssign);
1168 }
1169 
1170 /// Diagnose attempts to convert between __float128 and long double if
1171 /// there is no support for such conversion. Helper function of
1172 /// UsualArithmeticConversions().
1173 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1174                                       QualType RHSType) {
1175   /*  No issue converting if at least one of the types is not a floating point
1176       type or the two types have the same rank.
1177   */
1178   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1179       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1180     return false;
1181 
1182   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1183          "The remaining types must be floating point types.");
1184 
1185   auto *LHSComplex = LHSType->getAs<ComplexType>();
1186   auto *RHSComplex = RHSType->getAs<ComplexType>();
1187 
1188   QualType LHSElemType = LHSComplex ?
1189     LHSComplex->getElementType() : LHSType;
1190   QualType RHSElemType = RHSComplex ?
1191     RHSComplex->getElementType() : RHSType;
1192 
1193   // No issue if the two types have the same representation
1194   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1195       &S.Context.getFloatTypeSemantics(RHSElemType))
1196     return false;
1197 
1198   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1199                                 RHSElemType == S.Context.LongDoubleTy);
1200   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1201                             RHSElemType == S.Context.Float128Ty);
1202 
1203   // We've handled the situation where __float128 and long double have the same
1204   // representation. We allow all conversions for all possible long double types
1205   // except PPC's double double.
1206   return Float128AndLongDouble &&
1207     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1208      &llvm::APFloat::PPCDoubleDouble());
1209 }
1210 
1211 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1212 
1213 namespace {
1214 /// These helper callbacks are placed in an anonymous namespace to
1215 /// permit their use as function template parameters.
1216 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1217   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1218 }
1219 
1220 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1221   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1222                              CK_IntegralComplexCast);
1223 }
1224 }
1225 
1226 /// Handle integer arithmetic conversions.  Helper function of
1227 /// UsualArithmeticConversions()
1228 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1229 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1230                                         ExprResult &RHS, QualType LHSType,
1231                                         QualType RHSType, bool IsCompAssign) {
1232   // The rules for this case are in C99 6.3.1.8
1233   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1234   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1235   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1236   if (LHSSigned == RHSSigned) {
1237     // Same signedness; use the higher-ranked type
1238     if (order >= 0) {
1239       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1240       return LHSType;
1241     } else if (!IsCompAssign)
1242       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1243     return RHSType;
1244   } else if (order != (LHSSigned ? 1 : -1)) {
1245     // The unsigned type has greater than or equal rank to the
1246     // signed type, so use the unsigned type
1247     if (RHSSigned) {
1248       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1249       return LHSType;
1250     } else if (!IsCompAssign)
1251       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1252     return RHSType;
1253   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1254     // The two types are different widths; if we are here, that
1255     // means the signed type is larger than the unsigned type, so
1256     // use the signed type.
1257     if (LHSSigned) {
1258       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1259       return LHSType;
1260     } else if (!IsCompAssign)
1261       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1262     return RHSType;
1263   } else {
1264     // The signed type is higher-ranked than the unsigned type,
1265     // but isn't actually any bigger (like unsigned int and long
1266     // on most 32-bit systems).  Use the unsigned type corresponding
1267     // to the signed type.
1268     QualType result =
1269       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1270     RHS = (*doRHSCast)(S, RHS.get(), result);
1271     if (!IsCompAssign)
1272       LHS = (*doLHSCast)(S, LHS.get(), result);
1273     return result;
1274   }
1275 }
1276 
1277 /// Handle conversions with GCC complex int extension.  Helper function
1278 /// of UsualArithmeticConversions()
1279 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1280                                            ExprResult &RHS, QualType LHSType,
1281                                            QualType RHSType,
1282                                            bool IsCompAssign) {
1283   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1284   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1285 
1286   if (LHSComplexInt && RHSComplexInt) {
1287     QualType LHSEltType = LHSComplexInt->getElementType();
1288     QualType RHSEltType = RHSComplexInt->getElementType();
1289     QualType ScalarType =
1290       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1291         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1292 
1293     return S.Context.getComplexType(ScalarType);
1294   }
1295 
1296   if (LHSComplexInt) {
1297     QualType LHSEltType = LHSComplexInt->getElementType();
1298     QualType ScalarType =
1299       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1300         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1301     QualType ComplexType = S.Context.getComplexType(ScalarType);
1302     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1303                               CK_IntegralRealToComplex);
1304 
1305     return ComplexType;
1306   }
1307 
1308   assert(RHSComplexInt);
1309 
1310   QualType RHSEltType = RHSComplexInt->getElementType();
1311   QualType ScalarType =
1312     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1313       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1314   QualType ComplexType = S.Context.getComplexType(ScalarType);
1315 
1316   if (!IsCompAssign)
1317     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1318                               CK_IntegralRealToComplex);
1319   return ComplexType;
1320 }
1321 
1322 /// Return the rank of a given fixed point or integer type. The value itself
1323 /// doesn't matter, but the values must be increasing with proper increasing
1324 /// rank as described in N1169 4.1.1.
1325 static unsigned GetFixedPointRank(QualType Ty) {
1326   const auto *BTy = Ty->getAs<BuiltinType>();
1327   assert(BTy && "Expected a builtin type.");
1328 
1329   switch (BTy->getKind()) {
1330   case BuiltinType::ShortFract:
1331   case BuiltinType::UShortFract:
1332   case BuiltinType::SatShortFract:
1333   case BuiltinType::SatUShortFract:
1334     return 1;
1335   case BuiltinType::Fract:
1336   case BuiltinType::UFract:
1337   case BuiltinType::SatFract:
1338   case BuiltinType::SatUFract:
1339     return 2;
1340   case BuiltinType::LongFract:
1341   case BuiltinType::ULongFract:
1342   case BuiltinType::SatLongFract:
1343   case BuiltinType::SatULongFract:
1344     return 3;
1345   case BuiltinType::ShortAccum:
1346   case BuiltinType::UShortAccum:
1347   case BuiltinType::SatShortAccum:
1348   case BuiltinType::SatUShortAccum:
1349     return 4;
1350   case BuiltinType::Accum:
1351   case BuiltinType::UAccum:
1352   case BuiltinType::SatAccum:
1353   case BuiltinType::SatUAccum:
1354     return 5;
1355   case BuiltinType::LongAccum:
1356   case BuiltinType::ULongAccum:
1357   case BuiltinType::SatLongAccum:
1358   case BuiltinType::SatULongAccum:
1359     return 6;
1360   default:
1361     if (BTy->isInteger())
1362       return 0;
1363     llvm_unreachable("Unexpected fixed point or integer type");
1364   }
1365 }
1366 
1367 /// handleFixedPointConversion - Fixed point operations between fixed
1368 /// point types and integers or other fixed point types do not fall under
1369 /// usual arithmetic conversion since these conversions could result in loss
1370 /// of precsision (N1169 4.1.4). These operations should be calculated with
1371 /// the full precision of their result type (N1169 4.1.6.2.1).
1372 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1373                                            QualType RHSTy) {
1374   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1375          "Expected at least one of the operands to be a fixed point type");
1376   assert((LHSTy->isFixedPointOrIntegerType() ||
1377           RHSTy->isFixedPointOrIntegerType()) &&
1378          "Special fixed point arithmetic operation conversions are only "
1379          "applied to ints or other fixed point types");
1380 
1381   // If one operand has signed fixed-point type and the other operand has
1382   // unsigned fixed-point type, then the unsigned fixed-point operand is
1383   // converted to its corresponding signed fixed-point type and the resulting
1384   // type is the type of the converted operand.
1385   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1386     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1387   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1388     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1389 
1390   // The result type is the type with the highest rank, whereby a fixed-point
1391   // conversion rank is always greater than an integer conversion rank; if the
1392   // type of either of the operands is a saturating fixedpoint type, the result
1393   // type shall be the saturating fixed-point type corresponding to the type
1394   // with the highest rank; the resulting value is converted (taking into
1395   // account rounding and overflow) to the precision of the resulting type.
1396   // Same ranks between signed and unsigned types are resolved earlier, so both
1397   // types are either signed or both unsigned at this point.
1398   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1399   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1400 
1401   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1402 
1403   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1404     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1405 
1406   return ResultTy;
1407 }
1408 
1409 /// Check that the usual arithmetic conversions can be performed on this pair of
1410 /// expressions that might be of enumeration type.
1411 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1412                                            SourceLocation Loc,
1413                                            Sema::ArithConvKind ACK) {
1414   // C++2a [expr.arith.conv]p1:
1415   //   If one operand is of enumeration type and the other operand is of a
1416   //   different enumeration type or a floating-point type, this behavior is
1417   //   deprecated ([depr.arith.conv.enum]).
1418   //
1419   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1420   // Eventually we will presumably reject these cases (in C++23 onwards?).
1421   QualType L = LHS->getType(), R = RHS->getType();
1422   bool LEnum = L->isUnscopedEnumerationType(),
1423        REnum = R->isUnscopedEnumerationType();
1424   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1425   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1426       (REnum && L->isFloatingType())) {
1427     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1428                     ? diag::warn_arith_conv_enum_float_cxx20
1429                     : diag::warn_arith_conv_enum_float)
1430         << LHS->getSourceRange() << RHS->getSourceRange()
1431         << (int)ACK << LEnum << L << R;
1432   } else if (!IsCompAssign && LEnum && REnum &&
1433              !S.Context.hasSameUnqualifiedType(L, R)) {
1434     unsigned DiagID;
1435     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1436         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1437       // If either enumeration type is unnamed, it's less likely that the
1438       // user cares about this, but this situation is still deprecated in
1439       // C++2a. Use a different warning group.
1440       DiagID = S.getLangOpts().CPlusPlus20
1441                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1442                     : diag::warn_arith_conv_mixed_anon_enum_types;
1443     } else if (ACK == Sema::ACK_Conditional) {
1444       // Conditional expressions are separated out because they have
1445       // historically had a different warning flag.
1446       DiagID = S.getLangOpts().CPlusPlus20
1447                    ? diag::warn_conditional_mixed_enum_types_cxx20
1448                    : diag::warn_conditional_mixed_enum_types;
1449     } else if (ACK == Sema::ACK_Comparison) {
1450       // Comparison expressions are separated out because they have
1451       // historically had a different warning flag.
1452       DiagID = S.getLangOpts().CPlusPlus20
1453                    ? diag::warn_comparison_mixed_enum_types_cxx20
1454                    : diag::warn_comparison_mixed_enum_types;
1455     } else {
1456       DiagID = S.getLangOpts().CPlusPlus20
1457                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1458                    : diag::warn_arith_conv_mixed_enum_types;
1459     }
1460     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1461                         << (int)ACK << L << R;
1462   }
1463 }
1464 
1465 /// UsualArithmeticConversions - Performs various conversions that are common to
1466 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1467 /// routine returns the first non-arithmetic type found. The client is
1468 /// responsible for emitting appropriate error diagnostics.
1469 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1470                                           SourceLocation Loc,
1471                                           ArithConvKind ACK) {
1472   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1473 
1474   if (ACK != ACK_CompAssign) {
1475     LHS = UsualUnaryConversions(LHS.get());
1476     if (LHS.isInvalid())
1477       return QualType();
1478   }
1479 
1480   RHS = UsualUnaryConversions(RHS.get());
1481   if (RHS.isInvalid())
1482     return QualType();
1483 
1484   // For conversion purposes, we ignore any qualifiers.
1485   // For example, "const float" and "float" are equivalent.
1486   QualType LHSType =
1487     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1488   QualType RHSType =
1489     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1490 
1491   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1492   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1493     LHSType = AtomicLHS->getValueType();
1494 
1495   // If both types are identical, no conversion is needed.
1496   if (LHSType == RHSType)
1497     return LHSType;
1498 
1499   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1500   // The caller can deal with this (e.g. pointer + int).
1501   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1502     return QualType();
1503 
1504   // Apply unary and bitfield promotions to the LHS's type.
1505   QualType LHSUnpromotedType = LHSType;
1506   if (LHSType->isPromotableIntegerType())
1507     LHSType = Context.getPromotedIntegerType(LHSType);
1508   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1509   if (!LHSBitfieldPromoteTy.isNull())
1510     LHSType = LHSBitfieldPromoteTy;
1511   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1512     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1513 
1514   // If both types are identical, no conversion is needed.
1515   if (LHSType == RHSType)
1516     return LHSType;
1517 
1518   // ExtInt types aren't subject to conversions between them or normal integers,
1519   // so this fails.
1520   if(LHSType->isExtIntType() || RHSType->isExtIntType())
1521     return QualType();
1522 
1523   // At this point, we have two different arithmetic types.
1524 
1525   // Diagnose attempts to convert between __float128 and long double where
1526   // such conversions currently can't be handled.
1527   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1528     return QualType();
1529 
1530   // Handle complex types first (C99 6.3.1.8p1).
1531   if (LHSType->isComplexType() || RHSType->isComplexType())
1532     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1533                                         ACK == ACK_CompAssign);
1534 
1535   // Now handle "real" floating types (i.e. float, double, long double).
1536   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1537     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1538                                  ACK == ACK_CompAssign);
1539 
1540   // Handle GCC complex int extension.
1541   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1542     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1543                                       ACK == ACK_CompAssign);
1544 
1545   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1546     return handleFixedPointConversion(*this, LHSType, RHSType);
1547 
1548   // Finally, we have two differing integer types.
1549   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1550            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1551 }
1552 
1553 //===----------------------------------------------------------------------===//
1554 //  Semantic Analysis for various Expression Types
1555 //===----------------------------------------------------------------------===//
1556 
1557 
1558 ExprResult
1559 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1560                                 SourceLocation DefaultLoc,
1561                                 SourceLocation RParenLoc,
1562                                 Expr *ControllingExpr,
1563                                 ArrayRef<ParsedType> ArgTypes,
1564                                 ArrayRef<Expr *> ArgExprs) {
1565   unsigned NumAssocs = ArgTypes.size();
1566   assert(NumAssocs == ArgExprs.size());
1567 
1568   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1569   for (unsigned i = 0; i < NumAssocs; ++i) {
1570     if (ArgTypes[i])
1571       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1572     else
1573       Types[i] = nullptr;
1574   }
1575 
1576   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1577                                              ControllingExpr,
1578                                              llvm::makeArrayRef(Types, NumAssocs),
1579                                              ArgExprs);
1580   delete [] Types;
1581   return ER;
1582 }
1583 
1584 ExprResult
1585 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1586                                  SourceLocation DefaultLoc,
1587                                  SourceLocation RParenLoc,
1588                                  Expr *ControllingExpr,
1589                                  ArrayRef<TypeSourceInfo *> Types,
1590                                  ArrayRef<Expr *> Exprs) {
1591   unsigned NumAssocs = Types.size();
1592   assert(NumAssocs == Exprs.size());
1593 
1594   // Decay and strip qualifiers for the controlling expression type, and handle
1595   // placeholder type replacement. See committee discussion from WG14 DR423.
1596   {
1597     EnterExpressionEvaluationContext Unevaluated(
1598         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1599     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1600     if (R.isInvalid())
1601       return ExprError();
1602     ControllingExpr = R.get();
1603   }
1604 
1605   // The controlling expression is an unevaluated operand, so side effects are
1606   // likely unintended.
1607   if (!inTemplateInstantiation() &&
1608       ControllingExpr->HasSideEffects(Context, false))
1609     Diag(ControllingExpr->getExprLoc(),
1610          diag::warn_side_effects_unevaluated_context);
1611 
1612   bool TypeErrorFound = false,
1613        IsResultDependent = ControllingExpr->isTypeDependent(),
1614        ContainsUnexpandedParameterPack
1615          = ControllingExpr->containsUnexpandedParameterPack();
1616 
1617   for (unsigned i = 0; i < NumAssocs; ++i) {
1618     if (Exprs[i]->containsUnexpandedParameterPack())
1619       ContainsUnexpandedParameterPack = true;
1620 
1621     if (Types[i]) {
1622       if (Types[i]->getType()->containsUnexpandedParameterPack())
1623         ContainsUnexpandedParameterPack = true;
1624 
1625       if (Types[i]->getType()->isDependentType()) {
1626         IsResultDependent = true;
1627       } else {
1628         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1629         // complete object type other than a variably modified type."
1630         unsigned D = 0;
1631         if (Types[i]->getType()->isIncompleteType())
1632           D = diag::err_assoc_type_incomplete;
1633         else if (!Types[i]->getType()->isObjectType())
1634           D = diag::err_assoc_type_nonobject;
1635         else if (Types[i]->getType()->isVariablyModifiedType())
1636           D = diag::err_assoc_type_variably_modified;
1637 
1638         if (D != 0) {
1639           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1640             << Types[i]->getTypeLoc().getSourceRange()
1641             << Types[i]->getType();
1642           TypeErrorFound = true;
1643         }
1644 
1645         // C11 6.5.1.1p2 "No two generic associations in the same generic
1646         // selection shall specify compatible types."
1647         for (unsigned j = i+1; j < NumAssocs; ++j)
1648           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1649               Context.typesAreCompatible(Types[i]->getType(),
1650                                          Types[j]->getType())) {
1651             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1652                  diag::err_assoc_compatible_types)
1653               << Types[j]->getTypeLoc().getSourceRange()
1654               << Types[j]->getType()
1655               << Types[i]->getType();
1656             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1657                  diag::note_compat_assoc)
1658               << Types[i]->getTypeLoc().getSourceRange()
1659               << Types[i]->getType();
1660             TypeErrorFound = true;
1661           }
1662       }
1663     }
1664   }
1665   if (TypeErrorFound)
1666     return ExprError();
1667 
1668   // If we determined that the generic selection is result-dependent, don't
1669   // try to compute the result expression.
1670   if (IsResultDependent)
1671     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1672                                         Exprs, DefaultLoc, RParenLoc,
1673                                         ContainsUnexpandedParameterPack);
1674 
1675   SmallVector<unsigned, 1> CompatIndices;
1676   unsigned DefaultIndex = -1U;
1677   for (unsigned i = 0; i < NumAssocs; ++i) {
1678     if (!Types[i])
1679       DefaultIndex = i;
1680     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1681                                         Types[i]->getType()))
1682       CompatIndices.push_back(i);
1683   }
1684 
1685   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1686   // type compatible with at most one of the types named in its generic
1687   // association list."
1688   if (CompatIndices.size() > 1) {
1689     // We strip parens here because the controlling expression is typically
1690     // parenthesized in macro definitions.
1691     ControllingExpr = ControllingExpr->IgnoreParens();
1692     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1693         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1694         << (unsigned)CompatIndices.size();
1695     for (unsigned I : CompatIndices) {
1696       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1697            diag::note_compat_assoc)
1698         << Types[I]->getTypeLoc().getSourceRange()
1699         << Types[I]->getType();
1700     }
1701     return ExprError();
1702   }
1703 
1704   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1705   // its controlling expression shall have type compatible with exactly one of
1706   // the types named in its generic association list."
1707   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1708     // We strip parens here because the controlling expression is typically
1709     // parenthesized in macro definitions.
1710     ControllingExpr = ControllingExpr->IgnoreParens();
1711     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1712         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1713     return ExprError();
1714   }
1715 
1716   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1717   // type name that is compatible with the type of the controlling expression,
1718   // then the result expression of the generic selection is the expression
1719   // in that generic association. Otherwise, the result expression of the
1720   // generic selection is the expression in the default generic association."
1721   unsigned ResultIndex =
1722     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1723 
1724   return GenericSelectionExpr::Create(
1725       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1726       ContainsUnexpandedParameterPack, ResultIndex);
1727 }
1728 
1729 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1730 /// location of the token and the offset of the ud-suffix within it.
1731 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1732                                      unsigned Offset) {
1733   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1734                                         S.getLangOpts());
1735 }
1736 
1737 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1738 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1739 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1740                                                  IdentifierInfo *UDSuffix,
1741                                                  SourceLocation UDSuffixLoc,
1742                                                  ArrayRef<Expr*> Args,
1743                                                  SourceLocation LitEndLoc) {
1744   assert(Args.size() <= 2 && "too many arguments for literal operator");
1745 
1746   QualType ArgTy[2];
1747   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1748     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1749     if (ArgTy[ArgIdx]->isArrayType())
1750       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1751   }
1752 
1753   DeclarationName OpName =
1754     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1755   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1756   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1757 
1758   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1759   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1760                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1761                               /*AllowStringTemplatePack*/ false,
1762                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1763     return ExprError();
1764 
1765   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1766 }
1767 
1768 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1769 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1770 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1771 /// multiple tokens.  However, the common case is that StringToks points to one
1772 /// string.
1773 ///
1774 ExprResult
1775 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1776   assert(!StringToks.empty() && "Must have at least one string!");
1777 
1778   StringLiteralParser Literal(StringToks, PP);
1779   if (Literal.hadError)
1780     return ExprError();
1781 
1782   SmallVector<SourceLocation, 4> StringTokLocs;
1783   for (const Token &Tok : StringToks)
1784     StringTokLocs.push_back(Tok.getLocation());
1785 
1786   QualType CharTy = Context.CharTy;
1787   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1788   if (Literal.isWide()) {
1789     CharTy = Context.getWideCharType();
1790     Kind = StringLiteral::Wide;
1791   } else if (Literal.isUTF8()) {
1792     if (getLangOpts().Char8)
1793       CharTy = Context.Char8Ty;
1794     Kind = StringLiteral::UTF8;
1795   } else if (Literal.isUTF16()) {
1796     CharTy = Context.Char16Ty;
1797     Kind = StringLiteral::UTF16;
1798   } else if (Literal.isUTF32()) {
1799     CharTy = Context.Char32Ty;
1800     Kind = StringLiteral::UTF32;
1801   } else if (Literal.isPascal()) {
1802     CharTy = Context.UnsignedCharTy;
1803   }
1804 
1805   // Warn on initializing an array of char from a u8 string literal; this
1806   // becomes ill-formed in C++2a.
1807   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1808       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1809     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1810 
1811     // Create removals for all 'u8' prefixes in the string literal(s). This
1812     // ensures C++2a compatibility (but may change the program behavior when
1813     // built by non-Clang compilers for which the execution character set is
1814     // not always UTF-8).
1815     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1816     SourceLocation RemovalDiagLoc;
1817     for (const Token &Tok : StringToks) {
1818       if (Tok.getKind() == tok::utf8_string_literal) {
1819         if (RemovalDiagLoc.isInvalid())
1820           RemovalDiagLoc = Tok.getLocation();
1821         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1822             Tok.getLocation(),
1823             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1824                                            getSourceManager(), getLangOpts())));
1825       }
1826     }
1827     Diag(RemovalDiagLoc, RemovalDiag);
1828   }
1829 
1830   QualType StrTy =
1831       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1832 
1833   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1834   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1835                                              Kind, Literal.Pascal, StrTy,
1836                                              &StringTokLocs[0],
1837                                              StringTokLocs.size());
1838   if (Literal.getUDSuffix().empty())
1839     return Lit;
1840 
1841   // We're building a user-defined literal.
1842   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1843   SourceLocation UDSuffixLoc =
1844     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1845                    Literal.getUDSuffixOffset());
1846 
1847   // Make sure we're allowed user-defined literals here.
1848   if (!UDLScope)
1849     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1850 
1851   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1852   //   operator "" X (str, len)
1853   QualType SizeType = Context.getSizeType();
1854 
1855   DeclarationName OpName =
1856     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1857   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1858   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1859 
1860   QualType ArgTy[] = {
1861     Context.getArrayDecayedType(StrTy), SizeType
1862   };
1863 
1864   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1865   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1866                                 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1867                                 /*AllowStringTemplatePack*/ true,
1868                                 /*DiagnoseMissing*/ true, Lit)) {
1869 
1870   case LOLR_Cooked: {
1871     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1872     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1873                                                     StringTokLocs[0]);
1874     Expr *Args[] = { Lit, LenArg };
1875 
1876     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1877   }
1878 
1879   case LOLR_Template: {
1880     TemplateArgumentListInfo ExplicitArgs;
1881     TemplateArgument Arg(Lit);
1882     TemplateArgumentLocInfo ArgInfo(Lit);
1883     ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1884     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1885                                     &ExplicitArgs);
1886   }
1887 
1888   case LOLR_StringTemplatePack: {
1889     TemplateArgumentListInfo ExplicitArgs;
1890 
1891     unsigned CharBits = Context.getIntWidth(CharTy);
1892     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1893     llvm::APSInt Value(CharBits, CharIsUnsigned);
1894 
1895     TemplateArgument TypeArg(CharTy);
1896     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1897     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1898 
1899     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1900       Value = Lit->getCodeUnit(I);
1901       TemplateArgument Arg(Context, Value, CharTy);
1902       TemplateArgumentLocInfo ArgInfo;
1903       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1904     }
1905     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1906                                     &ExplicitArgs);
1907   }
1908   case LOLR_Raw:
1909   case LOLR_ErrorNoDiagnostic:
1910     llvm_unreachable("unexpected literal operator lookup result");
1911   case LOLR_Error:
1912     return ExprError();
1913   }
1914   llvm_unreachable("unexpected literal operator lookup result");
1915 }
1916 
1917 DeclRefExpr *
1918 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1919                        SourceLocation Loc,
1920                        const CXXScopeSpec *SS) {
1921   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1922   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1923 }
1924 
1925 DeclRefExpr *
1926 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1927                        const DeclarationNameInfo &NameInfo,
1928                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1929                        SourceLocation TemplateKWLoc,
1930                        const TemplateArgumentListInfo *TemplateArgs) {
1931   NestedNameSpecifierLoc NNS =
1932       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1933   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1934                           TemplateArgs);
1935 }
1936 
1937 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1938   // A declaration named in an unevaluated operand never constitutes an odr-use.
1939   if (isUnevaluatedContext())
1940     return NOUR_Unevaluated;
1941 
1942   // C++2a [basic.def.odr]p4:
1943   //   A variable x whose name appears as a potentially-evaluated expression e
1944   //   is odr-used by e unless [...] x is a reference that is usable in
1945   //   constant expressions.
1946   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1947     if (VD->getType()->isReferenceType() &&
1948         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1949         VD->isUsableInConstantExpressions(Context))
1950       return NOUR_Constant;
1951   }
1952 
1953   // All remaining non-variable cases constitute an odr-use. For variables, we
1954   // need to wait and see how the expression is used.
1955   return NOUR_None;
1956 }
1957 
1958 /// BuildDeclRefExpr - Build an expression that references a
1959 /// declaration that does not require a closure capture.
1960 DeclRefExpr *
1961 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1962                        const DeclarationNameInfo &NameInfo,
1963                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1964                        SourceLocation TemplateKWLoc,
1965                        const TemplateArgumentListInfo *TemplateArgs) {
1966   bool RefersToCapturedVariable =
1967       isa<VarDecl>(D) &&
1968       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1969 
1970   DeclRefExpr *E = DeclRefExpr::Create(
1971       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1972       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1973   MarkDeclRefReferenced(E);
1974 
1975   // C++ [except.spec]p17:
1976   //   An exception-specification is considered to be needed when:
1977   //   - in an expression, the function is the unique lookup result or
1978   //     the selected member of a set of overloaded functions.
1979   //
1980   // We delay doing this until after we've built the function reference and
1981   // marked it as used so that:
1982   //  a) if the function is defaulted, we get errors from defining it before /
1983   //     instead of errors from computing its exception specification, and
1984   //  b) if the function is a defaulted comparison, we can use the body we
1985   //     build when defining it as input to the exception specification
1986   //     computation rather than computing a new body.
1987   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1988     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1989       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1990         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1991     }
1992   }
1993 
1994   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1995       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1996       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1997     getCurFunction()->recordUseOfWeak(E);
1998 
1999   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2000   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2001     FD = IFD->getAnonField();
2002   if (FD) {
2003     UnusedPrivateFields.remove(FD);
2004     // Just in case we're building an illegal pointer-to-member.
2005     if (FD->isBitField())
2006       E->setObjectKind(OK_BitField);
2007   }
2008 
2009   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2010   // designates a bit-field.
2011   if (auto *BD = dyn_cast<BindingDecl>(D))
2012     if (auto *BE = BD->getBinding())
2013       E->setObjectKind(BE->getObjectKind());
2014 
2015   return E;
2016 }
2017 
2018 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2019 /// possibly a list of template arguments.
2020 ///
2021 /// If this produces template arguments, it is permitted to call
2022 /// DecomposeTemplateName.
2023 ///
2024 /// This actually loses a lot of source location information for
2025 /// non-standard name kinds; we should consider preserving that in
2026 /// some way.
2027 void
2028 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2029                              TemplateArgumentListInfo &Buffer,
2030                              DeclarationNameInfo &NameInfo,
2031                              const TemplateArgumentListInfo *&TemplateArgs) {
2032   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2033     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2034     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2035 
2036     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2037                                        Id.TemplateId->NumArgs);
2038     translateTemplateArguments(TemplateArgsPtr, Buffer);
2039 
2040     TemplateName TName = Id.TemplateId->Template.get();
2041     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2042     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2043     TemplateArgs = &Buffer;
2044   } else {
2045     NameInfo = GetNameFromUnqualifiedId(Id);
2046     TemplateArgs = nullptr;
2047   }
2048 }
2049 
2050 static void emitEmptyLookupTypoDiagnostic(
2051     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2052     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2053     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2054   DeclContext *Ctx =
2055       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2056   if (!TC) {
2057     // Emit a special diagnostic for failed member lookups.
2058     // FIXME: computing the declaration context might fail here (?)
2059     if (Ctx)
2060       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2061                                                  << SS.getRange();
2062     else
2063       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2064     return;
2065   }
2066 
2067   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2068   bool DroppedSpecifier =
2069       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2070   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2071                         ? diag::note_implicit_param_decl
2072                         : diag::note_previous_decl;
2073   if (!Ctx)
2074     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2075                          SemaRef.PDiag(NoteID));
2076   else
2077     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2078                                  << Typo << Ctx << DroppedSpecifier
2079                                  << SS.getRange(),
2080                          SemaRef.PDiag(NoteID));
2081 }
2082 
2083 /// Diagnose an empty lookup.
2084 ///
2085 /// \return false if new lookup candidates were found
2086 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2087                                CorrectionCandidateCallback &CCC,
2088                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2089                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2090   DeclarationName Name = R.getLookupName();
2091 
2092   unsigned diagnostic = diag::err_undeclared_var_use;
2093   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2094   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2095       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2096       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2097     diagnostic = diag::err_undeclared_use;
2098     diagnostic_suggest = diag::err_undeclared_use_suggest;
2099   }
2100 
2101   // If the original lookup was an unqualified lookup, fake an
2102   // unqualified lookup.  This is useful when (for example) the
2103   // original lookup would not have found something because it was a
2104   // dependent name.
2105   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2106   while (DC) {
2107     if (isa<CXXRecordDecl>(DC)) {
2108       LookupQualifiedName(R, DC);
2109 
2110       if (!R.empty()) {
2111         // Don't give errors about ambiguities in this lookup.
2112         R.suppressDiagnostics();
2113 
2114         // During a default argument instantiation the CurContext points
2115         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2116         // function parameter list, hence add an explicit check.
2117         bool isDefaultArgument =
2118             !CodeSynthesisContexts.empty() &&
2119             CodeSynthesisContexts.back().Kind ==
2120                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2121         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2122         bool isInstance = CurMethod &&
2123                           CurMethod->isInstance() &&
2124                           DC == CurMethod->getParent() && !isDefaultArgument;
2125 
2126         // Give a code modification hint to insert 'this->'.
2127         // TODO: fixit for inserting 'Base<T>::' in the other cases.
2128         // Actually quite difficult!
2129         if (getLangOpts().MSVCCompat)
2130           diagnostic = diag::ext_found_via_dependent_bases_lookup;
2131         if (isInstance) {
2132           Diag(R.getNameLoc(), diagnostic) << Name
2133             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2134           CheckCXXThisCapture(R.getNameLoc());
2135         } else {
2136           Diag(R.getNameLoc(), diagnostic) << Name;
2137         }
2138 
2139         // Do we really want to note all of these?
2140         for (NamedDecl *D : R)
2141           Diag(D->getLocation(), diag::note_dependent_var_use);
2142 
2143         // Return true if we are inside a default argument instantiation
2144         // and the found name refers to an instance member function, otherwise
2145         // the function calling DiagnoseEmptyLookup will try to create an
2146         // implicit member call and this is wrong for default argument.
2147         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2148           Diag(R.getNameLoc(), diag::err_member_call_without_object);
2149           return true;
2150         }
2151 
2152         // Tell the callee to try to recover.
2153         return false;
2154       }
2155 
2156       R.clear();
2157     }
2158 
2159     DC = DC->getLookupParent();
2160   }
2161 
2162   // We didn't find anything, so try to correct for a typo.
2163   TypoCorrection Corrected;
2164   if (S && Out) {
2165     SourceLocation TypoLoc = R.getNameLoc();
2166     assert(!ExplicitTemplateArgs &&
2167            "Diagnosing an empty lookup with explicit template args!");
2168     *Out = CorrectTypoDelayed(
2169         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2170         [=](const TypoCorrection &TC) {
2171           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2172                                         diagnostic, diagnostic_suggest);
2173         },
2174         nullptr, CTK_ErrorRecovery);
2175     if (*Out)
2176       return true;
2177   } else if (S &&
2178              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2179                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2180     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2181     bool DroppedSpecifier =
2182         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2183     R.setLookupName(Corrected.getCorrection());
2184 
2185     bool AcceptableWithRecovery = false;
2186     bool AcceptableWithoutRecovery = false;
2187     NamedDecl *ND = Corrected.getFoundDecl();
2188     if (ND) {
2189       if (Corrected.isOverloaded()) {
2190         OverloadCandidateSet OCS(R.getNameLoc(),
2191                                  OverloadCandidateSet::CSK_Normal);
2192         OverloadCandidateSet::iterator Best;
2193         for (NamedDecl *CD : Corrected) {
2194           if (FunctionTemplateDecl *FTD =
2195                    dyn_cast<FunctionTemplateDecl>(CD))
2196             AddTemplateOverloadCandidate(
2197                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2198                 Args, OCS);
2199           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2200             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2201               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2202                                    Args, OCS);
2203         }
2204         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2205         case OR_Success:
2206           ND = Best->FoundDecl;
2207           Corrected.setCorrectionDecl(ND);
2208           break;
2209         default:
2210           // FIXME: Arbitrarily pick the first declaration for the note.
2211           Corrected.setCorrectionDecl(ND);
2212           break;
2213         }
2214       }
2215       R.addDecl(ND);
2216       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2217         CXXRecordDecl *Record = nullptr;
2218         if (Corrected.getCorrectionSpecifier()) {
2219           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2220           Record = Ty->getAsCXXRecordDecl();
2221         }
2222         if (!Record)
2223           Record = cast<CXXRecordDecl>(
2224               ND->getDeclContext()->getRedeclContext());
2225         R.setNamingClass(Record);
2226       }
2227 
2228       auto *UnderlyingND = ND->getUnderlyingDecl();
2229       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2230                                isa<FunctionTemplateDecl>(UnderlyingND);
2231       // FIXME: If we ended up with a typo for a type name or
2232       // Objective-C class name, we're in trouble because the parser
2233       // is in the wrong place to recover. Suggest the typo
2234       // correction, but don't make it a fix-it since we're not going
2235       // to recover well anyway.
2236       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2237                                   getAsTypeTemplateDecl(UnderlyingND) ||
2238                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2239     } else {
2240       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2241       // because we aren't able to recover.
2242       AcceptableWithoutRecovery = true;
2243     }
2244 
2245     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2246       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2247                             ? diag::note_implicit_param_decl
2248                             : diag::note_previous_decl;
2249       if (SS.isEmpty())
2250         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2251                      PDiag(NoteID), AcceptableWithRecovery);
2252       else
2253         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2254                                   << Name << computeDeclContext(SS, false)
2255                                   << DroppedSpecifier << SS.getRange(),
2256                      PDiag(NoteID), AcceptableWithRecovery);
2257 
2258       // Tell the callee whether to try to recover.
2259       return !AcceptableWithRecovery;
2260     }
2261   }
2262   R.clear();
2263 
2264   // Emit a special diagnostic for failed member lookups.
2265   // FIXME: computing the declaration context might fail here (?)
2266   if (!SS.isEmpty()) {
2267     Diag(R.getNameLoc(), diag::err_no_member)
2268       << Name << computeDeclContext(SS, false)
2269       << SS.getRange();
2270     return true;
2271   }
2272 
2273   // Give up, we can't recover.
2274   Diag(R.getNameLoc(), diagnostic) << Name;
2275   return true;
2276 }
2277 
2278 /// In Microsoft mode, if we are inside a template class whose parent class has
2279 /// dependent base classes, and we can't resolve an unqualified identifier, then
2280 /// assume the identifier is a member of a dependent base class.  We can only
2281 /// recover successfully in static methods, instance methods, and other contexts
2282 /// where 'this' is available.  This doesn't precisely match MSVC's
2283 /// instantiation model, but it's close enough.
2284 static Expr *
2285 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2286                                DeclarationNameInfo &NameInfo,
2287                                SourceLocation TemplateKWLoc,
2288                                const TemplateArgumentListInfo *TemplateArgs) {
2289   // Only try to recover from lookup into dependent bases in static methods or
2290   // contexts where 'this' is available.
2291   QualType ThisType = S.getCurrentThisType();
2292   const CXXRecordDecl *RD = nullptr;
2293   if (!ThisType.isNull())
2294     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2295   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2296     RD = MD->getParent();
2297   if (!RD || !RD->hasAnyDependentBases())
2298     return nullptr;
2299 
2300   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2301   // is available, suggest inserting 'this->' as a fixit.
2302   SourceLocation Loc = NameInfo.getLoc();
2303   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2304   DB << NameInfo.getName() << RD;
2305 
2306   if (!ThisType.isNull()) {
2307     DB << FixItHint::CreateInsertion(Loc, "this->");
2308     return CXXDependentScopeMemberExpr::Create(
2309         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2310         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2311         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2312   }
2313 
2314   // Synthesize a fake NNS that points to the derived class.  This will
2315   // perform name lookup during template instantiation.
2316   CXXScopeSpec SS;
2317   auto *NNS =
2318       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2319   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2320   return DependentScopeDeclRefExpr::Create(
2321       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2322       TemplateArgs);
2323 }
2324 
2325 ExprResult
2326 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2327                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2328                         bool HasTrailingLParen, bool IsAddressOfOperand,
2329                         CorrectionCandidateCallback *CCC,
2330                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2331   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2332          "cannot be direct & operand and have a trailing lparen");
2333   if (SS.isInvalid())
2334     return ExprError();
2335 
2336   TemplateArgumentListInfo TemplateArgsBuffer;
2337 
2338   // Decompose the UnqualifiedId into the following data.
2339   DeclarationNameInfo NameInfo;
2340   const TemplateArgumentListInfo *TemplateArgs;
2341   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2342 
2343   DeclarationName Name = NameInfo.getName();
2344   IdentifierInfo *II = Name.getAsIdentifierInfo();
2345   SourceLocation NameLoc = NameInfo.getLoc();
2346 
2347   if (II && II->isEditorPlaceholder()) {
2348     // FIXME: When typed placeholders are supported we can create a typed
2349     // placeholder expression node.
2350     return ExprError();
2351   }
2352 
2353   // C++ [temp.dep.expr]p3:
2354   //   An id-expression is type-dependent if it contains:
2355   //     -- an identifier that was declared with a dependent type,
2356   //        (note: handled after lookup)
2357   //     -- a template-id that is dependent,
2358   //        (note: handled in BuildTemplateIdExpr)
2359   //     -- a conversion-function-id that specifies a dependent type,
2360   //     -- a nested-name-specifier that contains a class-name that
2361   //        names a dependent type.
2362   // Determine whether this is a member of an unknown specialization;
2363   // we need to handle these differently.
2364   bool DependentID = false;
2365   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2366       Name.getCXXNameType()->isDependentType()) {
2367     DependentID = true;
2368   } else if (SS.isSet()) {
2369     if (DeclContext *DC = computeDeclContext(SS, false)) {
2370       if (RequireCompleteDeclContext(SS, DC))
2371         return ExprError();
2372     } else {
2373       DependentID = true;
2374     }
2375   }
2376 
2377   if (DependentID)
2378     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2379                                       IsAddressOfOperand, TemplateArgs);
2380 
2381   // Perform the required lookup.
2382   LookupResult R(*this, NameInfo,
2383                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2384                      ? LookupObjCImplicitSelfParam
2385                      : LookupOrdinaryName);
2386   if (TemplateKWLoc.isValid() || TemplateArgs) {
2387     // Lookup the template name again to correctly establish the context in
2388     // which it was found. This is really unfortunate as we already did the
2389     // lookup to determine that it was a template name in the first place. If
2390     // this becomes a performance hit, we can work harder to preserve those
2391     // results until we get here but it's likely not worth it.
2392     bool MemberOfUnknownSpecialization;
2393     AssumedTemplateKind AssumedTemplate;
2394     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2395                            MemberOfUnknownSpecialization, TemplateKWLoc,
2396                            &AssumedTemplate))
2397       return ExprError();
2398 
2399     if (MemberOfUnknownSpecialization ||
2400         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2401       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2402                                         IsAddressOfOperand, TemplateArgs);
2403   } else {
2404     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2405     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2406 
2407     // If the result might be in a dependent base class, this is a dependent
2408     // id-expression.
2409     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2410       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2411                                         IsAddressOfOperand, TemplateArgs);
2412 
2413     // If this reference is in an Objective-C method, then we need to do
2414     // some special Objective-C lookup, too.
2415     if (IvarLookupFollowUp) {
2416       ExprResult E(LookupInObjCMethod(R, S, II, true));
2417       if (E.isInvalid())
2418         return ExprError();
2419 
2420       if (Expr *Ex = E.getAs<Expr>())
2421         return Ex;
2422     }
2423   }
2424 
2425   if (R.isAmbiguous())
2426     return ExprError();
2427 
2428   // This could be an implicitly declared function reference (legal in C90,
2429   // extension in C99, forbidden in C++).
2430   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2431     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2432     if (D) R.addDecl(D);
2433   }
2434 
2435   // Determine whether this name might be a candidate for
2436   // argument-dependent lookup.
2437   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2438 
2439   if (R.empty() && !ADL) {
2440     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2441       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2442                                                    TemplateKWLoc, TemplateArgs))
2443         return E;
2444     }
2445 
2446     // Don't diagnose an empty lookup for inline assembly.
2447     if (IsInlineAsmIdentifier)
2448       return ExprError();
2449 
2450     // If this name wasn't predeclared and if this is not a function
2451     // call, diagnose the problem.
2452     TypoExpr *TE = nullptr;
2453     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2454                                                        : nullptr);
2455     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2456     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2457            "Typo correction callback misconfigured");
2458     if (CCC) {
2459       // Make sure the callback knows what the typo being diagnosed is.
2460       CCC->setTypoName(II);
2461       if (SS.isValid())
2462         CCC->setTypoNNS(SS.getScopeRep());
2463     }
2464     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2465     // a template name, but we happen to have always already looked up the name
2466     // before we get here if it must be a template name.
2467     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2468                             None, &TE)) {
2469       if (TE && KeywordReplacement) {
2470         auto &State = getTypoExprState(TE);
2471         auto BestTC = State.Consumer->getNextCorrection();
2472         if (BestTC.isKeyword()) {
2473           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2474           if (State.DiagHandler)
2475             State.DiagHandler(BestTC);
2476           KeywordReplacement->startToken();
2477           KeywordReplacement->setKind(II->getTokenID());
2478           KeywordReplacement->setIdentifierInfo(II);
2479           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2480           // Clean up the state associated with the TypoExpr, since it has
2481           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2482           clearDelayedTypo(TE);
2483           // Signal that a correction to a keyword was performed by returning a
2484           // valid-but-null ExprResult.
2485           return (Expr*)nullptr;
2486         }
2487         State.Consumer->resetCorrectionStream();
2488       }
2489       return TE ? TE : ExprError();
2490     }
2491 
2492     assert(!R.empty() &&
2493            "DiagnoseEmptyLookup returned false but added no results");
2494 
2495     // If we found an Objective-C instance variable, let
2496     // LookupInObjCMethod build the appropriate expression to
2497     // reference the ivar.
2498     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2499       R.clear();
2500       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2501       // In a hopelessly buggy code, Objective-C instance variable
2502       // lookup fails and no expression will be built to reference it.
2503       if (!E.isInvalid() && !E.get())
2504         return ExprError();
2505       return E;
2506     }
2507   }
2508 
2509   // This is guaranteed from this point on.
2510   assert(!R.empty() || ADL);
2511 
2512   // Check whether this might be a C++ implicit instance member access.
2513   // C++ [class.mfct.non-static]p3:
2514   //   When an id-expression that is not part of a class member access
2515   //   syntax and not used to form a pointer to member is used in the
2516   //   body of a non-static member function of class X, if name lookup
2517   //   resolves the name in the id-expression to a non-static non-type
2518   //   member of some class C, the id-expression is transformed into a
2519   //   class member access expression using (*this) as the
2520   //   postfix-expression to the left of the . operator.
2521   //
2522   // But we don't actually need to do this for '&' operands if R
2523   // resolved to a function or overloaded function set, because the
2524   // expression is ill-formed if it actually works out to be a
2525   // non-static member function:
2526   //
2527   // C++ [expr.ref]p4:
2528   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2529   //   [t]he expression can be used only as the left-hand operand of a
2530   //   member function call.
2531   //
2532   // There are other safeguards against such uses, but it's important
2533   // to get this right here so that we don't end up making a
2534   // spuriously dependent expression if we're inside a dependent
2535   // instance method.
2536   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2537     bool MightBeImplicitMember;
2538     if (!IsAddressOfOperand)
2539       MightBeImplicitMember = true;
2540     else if (!SS.isEmpty())
2541       MightBeImplicitMember = false;
2542     else if (R.isOverloadedResult())
2543       MightBeImplicitMember = false;
2544     else if (R.isUnresolvableResult())
2545       MightBeImplicitMember = true;
2546     else
2547       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2548                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2549                               isa<MSPropertyDecl>(R.getFoundDecl());
2550 
2551     if (MightBeImplicitMember)
2552       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2553                                              R, TemplateArgs, S);
2554   }
2555 
2556   if (TemplateArgs || TemplateKWLoc.isValid()) {
2557 
2558     // In C++1y, if this is a variable template id, then check it
2559     // in BuildTemplateIdExpr().
2560     // The single lookup result must be a variable template declaration.
2561     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2562         Id.TemplateId->Kind == TNK_Var_template) {
2563       assert(R.getAsSingle<VarTemplateDecl>() &&
2564              "There should only be one declaration found.");
2565     }
2566 
2567     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2568   }
2569 
2570   return BuildDeclarationNameExpr(SS, R, ADL);
2571 }
2572 
2573 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2574 /// declaration name, generally during template instantiation.
2575 /// There's a large number of things which don't need to be done along
2576 /// this path.
2577 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2578     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2579     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2580   DeclContext *DC = computeDeclContext(SS, false);
2581   if (!DC)
2582     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2583                                      NameInfo, /*TemplateArgs=*/nullptr);
2584 
2585   if (RequireCompleteDeclContext(SS, DC))
2586     return ExprError();
2587 
2588   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2589   LookupQualifiedName(R, DC);
2590 
2591   if (R.isAmbiguous())
2592     return ExprError();
2593 
2594   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2595     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2596                                      NameInfo, /*TemplateArgs=*/nullptr);
2597 
2598   if (R.empty()) {
2599     // Don't diagnose problems with invalid record decl, the secondary no_member
2600     // diagnostic during template instantiation is likely bogus, e.g. if a class
2601     // is invalid because it's derived from an invalid base class, then missing
2602     // members were likely supposed to be inherited.
2603     if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2604       if (CD->isInvalidDecl())
2605         return ExprError();
2606     Diag(NameInfo.getLoc(), diag::err_no_member)
2607       << NameInfo.getName() << DC << SS.getRange();
2608     return ExprError();
2609   }
2610 
2611   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2612     // Diagnose a missing typename if this resolved unambiguously to a type in
2613     // a dependent context.  If we can recover with a type, downgrade this to
2614     // a warning in Microsoft compatibility mode.
2615     unsigned DiagID = diag::err_typename_missing;
2616     if (RecoveryTSI && getLangOpts().MSVCCompat)
2617       DiagID = diag::ext_typename_missing;
2618     SourceLocation Loc = SS.getBeginLoc();
2619     auto D = Diag(Loc, DiagID);
2620     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2621       << SourceRange(Loc, NameInfo.getEndLoc());
2622 
2623     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2624     // context.
2625     if (!RecoveryTSI)
2626       return ExprError();
2627 
2628     // Only issue the fixit if we're prepared to recover.
2629     D << FixItHint::CreateInsertion(Loc, "typename ");
2630 
2631     // Recover by pretending this was an elaborated type.
2632     QualType Ty = Context.getTypeDeclType(TD);
2633     TypeLocBuilder TLB;
2634     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2635 
2636     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2637     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2638     QTL.setElaboratedKeywordLoc(SourceLocation());
2639     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2640 
2641     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2642 
2643     return ExprEmpty();
2644   }
2645 
2646   // Defend against this resolving to an implicit member access. We usually
2647   // won't get here if this might be a legitimate a class member (we end up in
2648   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2649   // a pointer-to-member or in an unevaluated context in C++11.
2650   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2651     return BuildPossibleImplicitMemberExpr(SS,
2652                                            /*TemplateKWLoc=*/SourceLocation(),
2653                                            R, /*TemplateArgs=*/nullptr, S);
2654 
2655   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2656 }
2657 
2658 /// The parser has read a name in, and Sema has detected that we're currently
2659 /// inside an ObjC method. Perform some additional checks and determine if we
2660 /// should form a reference to an ivar.
2661 ///
2662 /// Ideally, most of this would be done by lookup, but there's
2663 /// actually quite a lot of extra work involved.
2664 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2665                                         IdentifierInfo *II) {
2666   SourceLocation Loc = Lookup.getNameLoc();
2667   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2668 
2669   // Check for error condition which is already reported.
2670   if (!CurMethod)
2671     return DeclResult(true);
2672 
2673   // There are two cases to handle here.  1) scoped lookup could have failed,
2674   // in which case we should look for an ivar.  2) scoped lookup could have
2675   // found a decl, but that decl is outside the current instance method (i.e.
2676   // a global variable).  In these two cases, we do a lookup for an ivar with
2677   // this name, if the lookup sucedes, we replace it our current decl.
2678 
2679   // If we're in a class method, we don't normally want to look for
2680   // ivars.  But if we don't find anything else, and there's an
2681   // ivar, that's an error.
2682   bool IsClassMethod = CurMethod->isClassMethod();
2683 
2684   bool LookForIvars;
2685   if (Lookup.empty())
2686     LookForIvars = true;
2687   else if (IsClassMethod)
2688     LookForIvars = false;
2689   else
2690     LookForIvars = (Lookup.isSingleResult() &&
2691                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2692   ObjCInterfaceDecl *IFace = nullptr;
2693   if (LookForIvars) {
2694     IFace = CurMethod->getClassInterface();
2695     ObjCInterfaceDecl *ClassDeclared;
2696     ObjCIvarDecl *IV = nullptr;
2697     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2698       // Diagnose using an ivar in a class method.
2699       if (IsClassMethod) {
2700         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2701         return DeclResult(true);
2702       }
2703 
2704       // Diagnose the use of an ivar outside of the declaring class.
2705       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2706           !declaresSameEntity(ClassDeclared, IFace) &&
2707           !getLangOpts().DebuggerSupport)
2708         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2709 
2710       // Success.
2711       return IV;
2712     }
2713   } else if (CurMethod->isInstanceMethod()) {
2714     // We should warn if a local variable hides an ivar.
2715     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2716       ObjCInterfaceDecl *ClassDeclared;
2717       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2718         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2719             declaresSameEntity(IFace, ClassDeclared))
2720           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2721       }
2722     }
2723   } else if (Lookup.isSingleResult() &&
2724              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2725     // If accessing a stand-alone ivar in a class method, this is an error.
2726     if (const ObjCIvarDecl *IV =
2727             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2728       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2729       return DeclResult(true);
2730     }
2731   }
2732 
2733   // Didn't encounter an error, didn't find an ivar.
2734   return DeclResult(false);
2735 }
2736 
2737 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2738                                   ObjCIvarDecl *IV) {
2739   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2740   assert(CurMethod && CurMethod->isInstanceMethod() &&
2741          "should not reference ivar from this context");
2742 
2743   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2744   assert(IFace && "should not reference ivar from this context");
2745 
2746   // If we're referencing an invalid decl, just return this as a silent
2747   // error node.  The error diagnostic was already emitted on the decl.
2748   if (IV->isInvalidDecl())
2749     return ExprError();
2750 
2751   // Check if referencing a field with __attribute__((deprecated)).
2752   if (DiagnoseUseOfDecl(IV, Loc))
2753     return ExprError();
2754 
2755   // FIXME: This should use a new expr for a direct reference, don't
2756   // turn this into Self->ivar, just return a BareIVarExpr or something.
2757   IdentifierInfo &II = Context.Idents.get("self");
2758   UnqualifiedId SelfName;
2759   SelfName.setIdentifier(&II, SourceLocation());
2760   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2761   CXXScopeSpec SelfScopeSpec;
2762   SourceLocation TemplateKWLoc;
2763   ExprResult SelfExpr =
2764       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2765                         /*HasTrailingLParen=*/false,
2766                         /*IsAddressOfOperand=*/false);
2767   if (SelfExpr.isInvalid())
2768     return ExprError();
2769 
2770   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2771   if (SelfExpr.isInvalid())
2772     return ExprError();
2773 
2774   MarkAnyDeclReferenced(Loc, IV, true);
2775 
2776   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2777   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2778       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2779     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2780 
2781   ObjCIvarRefExpr *Result = new (Context)
2782       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2783                       IV->getLocation(), SelfExpr.get(), true, true);
2784 
2785   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2786     if (!isUnevaluatedContext() &&
2787         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2788       getCurFunction()->recordUseOfWeak(Result);
2789   }
2790   if (getLangOpts().ObjCAutoRefCount)
2791     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2792       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2793 
2794   return Result;
2795 }
2796 
2797 /// The parser has read a name in, and Sema has detected that we're currently
2798 /// inside an ObjC method. Perform some additional checks and determine if we
2799 /// should form a reference to an ivar. If so, build an expression referencing
2800 /// that ivar.
2801 ExprResult
2802 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2803                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2804   // FIXME: Integrate this lookup step into LookupParsedName.
2805   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2806   if (Ivar.isInvalid())
2807     return ExprError();
2808   if (Ivar.isUsable())
2809     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2810                             cast<ObjCIvarDecl>(Ivar.get()));
2811 
2812   if (Lookup.empty() && II && AllowBuiltinCreation)
2813     LookupBuiltin(Lookup);
2814 
2815   // Sentinel value saying that we didn't do anything special.
2816   return ExprResult(false);
2817 }
2818 
2819 /// Cast a base object to a member's actual type.
2820 ///
2821 /// Logically this happens in three phases:
2822 ///
2823 /// * First we cast from the base type to the naming class.
2824 ///   The naming class is the class into which we were looking
2825 ///   when we found the member;  it's the qualifier type if a
2826 ///   qualifier was provided, and otherwise it's the base type.
2827 ///
2828 /// * Next we cast from the naming class to the declaring class.
2829 ///   If the member we found was brought into a class's scope by
2830 ///   a using declaration, this is that class;  otherwise it's
2831 ///   the class declaring the member.
2832 ///
2833 /// * Finally we cast from the declaring class to the "true"
2834 ///   declaring class of the member.  This conversion does not
2835 ///   obey access control.
2836 ExprResult
2837 Sema::PerformObjectMemberConversion(Expr *From,
2838                                     NestedNameSpecifier *Qualifier,
2839                                     NamedDecl *FoundDecl,
2840                                     NamedDecl *Member) {
2841   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2842   if (!RD)
2843     return From;
2844 
2845   QualType DestRecordType;
2846   QualType DestType;
2847   QualType FromRecordType;
2848   QualType FromType = From->getType();
2849   bool PointerConversions = false;
2850   if (isa<FieldDecl>(Member)) {
2851     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2852     auto FromPtrType = FromType->getAs<PointerType>();
2853     DestRecordType = Context.getAddrSpaceQualType(
2854         DestRecordType, FromPtrType
2855                             ? FromType->getPointeeType().getAddressSpace()
2856                             : FromType.getAddressSpace());
2857 
2858     if (FromPtrType) {
2859       DestType = Context.getPointerType(DestRecordType);
2860       FromRecordType = FromPtrType->getPointeeType();
2861       PointerConversions = true;
2862     } else {
2863       DestType = DestRecordType;
2864       FromRecordType = FromType;
2865     }
2866   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2867     if (Method->isStatic())
2868       return From;
2869 
2870     DestType = Method->getThisType();
2871     DestRecordType = DestType->getPointeeType();
2872 
2873     if (FromType->getAs<PointerType>()) {
2874       FromRecordType = FromType->getPointeeType();
2875       PointerConversions = true;
2876     } else {
2877       FromRecordType = FromType;
2878       DestType = DestRecordType;
2879     }
2880 
2881     LangAS FromAS = FromRecordType.getAddressSpace();
2882     LangAS DestAS = DestRecordType.getAddressSpace();
2883     if (FromAS != DestAS) {
2884       QualType FromRecordTypeWithoutAS =
2885           Context.removeAddrSpaceQualType(FromRecordType);
2886       QualType FromTypeWithDestAS =
2887           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2888       if (PointerConversions)
2889         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2890       From = ImpCastExprToType(From, FromTypeWithDestAS,
2891                                CK_AddressSpaceConversion, From->getValueKind())
2892                  .get();
2893     }
2894   } else {
2895     // No conversion necessary.
2896     return From;
2897   }
2898 
2899   if (DestType->isDependentType() || FromType->isDependentType())
2900     return From;
2901 
2902   // If the unqualified types are the same, no conversion is necessary.
2903   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2904     return From;
2905 
2906   SourceRange FromRange = From->getSourceRange();
2907   SourceLocation FromLoc = FromRange.getBegin();
2908 
2909   ExprValueKind VK = From->getValueKind();
2910 
2911   // C++ [class.member.lookup]p8:
2912   //   [...] Ambiguities can often be resolved by qualifying a name with its
2913   //   class name.
2914   //
2915   // If the member was a qualified name and the qualified referred to a
2916   // specific base subobject type, we'll cast to that intermediate type
2917   // first and then to the object in which the member is declared. That allows
2918   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2919   //
2920   //   class Base { public: int x; };
2921   //   class Derived1 : public Base { };
2922   //   class Derived2 : public Base { };
2923   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2924   //
2925   //   void VeryDerived::f() {
2926   //     x = 17; // error: ambiguous base subobjects
2927   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2928   //   }
2929   if (Qualifier && Qualifier->getAsType()) {
2930     QualType QType = QualType(Qualifier->getAsType(), 0);
2931     assert(QType->isRecordType() && "lookup done with non-record type");
2932 
2933     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2934 
2935     // In C++98, the qualifier type doesn't actually have to be a base
2936     // type of the object type, in which case we just ignore it.
2937     // Otherwise build the appropriate casts.
2938     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2939       CXXCastPath BasePath;
2940       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2941                                        FromLoc, FromRange, &BasePath))
2942         return ExprError();
2943 
2944       if (PointerConversions)
2945         QType = Context.getPointerType(QType);
2946       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2947                                VK, &BasePath).get();
2948 
2949       FromType = QType;
2950       FromRecordType = QRecordType;
2951 
2952       // If the qualifier type was the same as the destination type,
2953       // we're done.
2954       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2955         return From;
2956     }
2957   }
2958 
2959   bool IgnoreAccess = false;
2960 
2961   // If we actually found the member through a using declaration, cast
2962   // down to the using declaration's type.
2963   //
2964   // Pointer equality is fine here because only one declaration of a
2965   // class ever has member declarations.
2966   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2967     assert(isa<UsingShadowDecl>(FoundDecl));
2968     QualType URecordType = Context.getTypeDeclType(
2969                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2970 
2971     // We only need to do this if the naming-class to declaring-class
2972     // conversion is non-trivial.
2973     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2974       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2975       CXXCastPath BasePath;
2976       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2977                                        FromLoc, FromRange, &BasePath))
2978         return ExprError();
2979 
2980       QualType UType = URecordType;
2981       if (PointerConversions)
2982         UType = Context.getPointerType(UType);
2983       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2984                                VK, &BasePath).get();
2985       FromType = UType;
2986       FromRecordType = URecordType;
2987     }
2988 
2989     // We don't do access control for the conversion from the
2990     // declaring class to the true declaring class.
2991     IgnoreAccess = true;
2992   }
2993 
2994   CXXCastPath BasePath;
2995   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2996                                    FromLoc, FromRange, &BasePath,
2997                                    IgnoreAccess))
2998     return ExprError();
2999 
3000   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3001                            VK, &BasePath);
3002 }
3003 
3004 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3005                                       const LookupResult &R,
3006                                       bool HasTrailingLParen) {
3007   // Only when used directly as the postfix-expression of a call.
3008   if (!HasTrailingLParen)
3009     return false;
3010 
3011   // Never if a scope specifier was provided.
3012   if (SS.isSet())
3013     return false;
3014 
3015   // Only in C++ or ObjC++.
3016   if (!getLangOpts().CPlusPlus)
3017     return false;
3018 
3019   // Turn off ADL when we find certain kinds of declarations during
3020   // normal lookup:
3021   for (NamedDecl *D : R) {
3022     // C++0x [basic.lookup.argdep]p3:
3023     //     -- a declaration of a class member
3024     // Since using decls preserve this property, we check this on the
3025     // original decl.
3026     if (D->isCXXClassMember())
3027       return false;
3028 
3029     // C++0x [basic.lookup.argdep]p3:
3030     //     -- a block-scope function declaration that is not a
3031     //        using-declaration
3032     // NOTE: we also trigger this for function templates (in fact, we
3033     // don't check the decl type at all, since all other decl types
3034     // turn off ADL anyway).
3035     if (isa<UsingShadowDecl>(D))
3036       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3037     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3038       return false;
3039 
3040     // C++0x [basic.lookup.argdep]p3:
3041     //     -- a declaration that is neither a function or a function
3042     //        template
3043     // And also for builtin functions.
3044     if (isa<FunctionDecl>(D)) {
3045       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3046 
3047       // But also builtin functions.
3048       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3049         return false;
3050     } else if (!isa<FunctionTemplateDecl>(D))
3051       return false;
3052   }
3053 
3054   return true;
3055 }
3056 
3057 
3058 /// Diagnoses obvious problems with the use of the given declaration
3059 /// as an expression.  This is only actually called for lookups that
3060 /// were not overloaded, and it doesn't promise that the declaration
3061 /// will in fact be used.
3062 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3063   if (D->isInvalidDecl())
3064     return true;
3065 
3066   if (isa<TypedefNameDecl>(D)) {
3067     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3068     return true;
3069   }
3070 
3071   if (isa<ObjCInterfaceDecl>(D)) {
3072     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3073     return true;
3074   }
3075 
3076   if (isa<NamespaceDecl>(D)) {
3077     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3078     return true;
3079   }
3080 
3081   return false;
3082 }
3083 
3084 // Certain multiversion types should be treated as overloaded even when there is
3085 // only one result.
3086 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3087   assert(R.isSingleResult() && "Expected only a single result");
3088   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3089   return FD &&
3090          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3091 }
3092 
3093 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3094                                           LookupResult &R, bool NeedsADL,
3095                                           bool AcceptInvalidDecl) {
3096   // If this is a single, fully-resolved result and we don't need ADL,
3097   // just build an ordinary singleton decl ref.
3098   if (!NeedsADL && R.isSingleResult() &&
3099       !R.getAsSingle<FunctionTemplateDecl>() &&
3100       !ShouldLookupResultBeMultiVersionOverload(R))
3101     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3102                                     R.getRepresentativeDecl(), nullptr,
3103                                     AcceptInvalidDecl);
3104 
3105   // We only need to check the declaration if there's exactly one
3106   // result, because in the overloaded case the results can only be
3107   // functions and function templates.
3108   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3109       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3110     return ExprError();
3111 
3112   // Otherwise, just build an unresolved lookup expression.  Suppress
3113   // any lookup-related diagnostics; we'll hash these out later, when
3114   // we've picked a target.
3115   R.suppressDiagnostics();
3116 
3117   UnresolvedLookupExpr *ULE
3118     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3119                                    SS.getWithLocInContext(Context),
3120                                    R.getLookupNameInfo(),
3121                                    NeedsADL, R.isOverloadedResult(),
3122                                    R.begin(), R.end());
3123 
3124   return ULE;
3125 }
3126 
3127 static void
3128 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3129                                    ValueDecl *var, DeclContext *DC);
3130 
3131 /// Complete semantic analysis for a reference to the given declaration.
3132 ExprResult Sema::BuildDeclarationNameExpr(
3133     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3134     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3135     bool AcceptInvalidDecl) {
3136   assert(D && "Cannot refer to a NULL declaration");
3137   assert(!isa<FunctionTemplateDecl>(D) &&
3138          "Cannot refer unambiguously to a function template");
3139 
3140   SourceLocation Loc = NameInfo.getLoc();
3141   if (CheckDeclInExpr(*this, Loc, D))
3142     return ExprError();
3143 
3144   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3145     // Specifically diagnose references to class templates that are missing
3146     // a template argument list.
3147     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3148     return ExprError();
3149   }
3150 
3151   // Make sure that we're referring to a value.
3152   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3153   if (!VD) {
3154     Diag(Loc, diag::err_ref_non_value)
3155       << D << SS.getRange();
3156     Diag(D->getLocation(), diag::note_declared_at);
3157     return ExprError();
3158   }
3159 
3160   // Check whether this declaration can be used. Note that we suppress
3161   // this check when we're going to perform argument-dependent lookup
3162   // on this function name, because this might not be the function
3163   // that overload resolution actually selects.
3164   if (DiagnoseUseOfDecl(VD, Loc))
3165     return ExprError();
3166 
3167   // Only create DeclRefExpr's for valid Decl's.
3168   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3169     return ExprError();
3170 
3171   // Handle members of anonymous structs and unions.  If we got here,
3172   // and the reference is to a class member indirect field, then this
3173   // must be the subject of a pointer-to-member expression.
3174   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3175     if (!indirectField->isCXXClassMember())
3176       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3177                                                       indirectField);
3178 
3179   {
3180     QualType type = VD->getType();
3181     if (type.isNull())
3182       return ExprError();
3183     ExprValueKind valueKind = VK_RValue;
3184 
3185     // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3186     // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3187     // is expanded by some outer '...' in the context of the use.
3188     type = type.getNonPackExpansionType();
3189 
3190     switch (D->getKind()) {
3191     // Ignore all the non-ValueDecl kinds.
3192 #define ABSTRACT_DECL(kind)
3193 #define VALUE(type, base)
3194 #define DECL(type, base) \
3195     case Decl::type:
3196 #include "clang/AST/DeclNodes.inc"
3197       llvm_unreachable("invalid value decl kind");
3198 
3199     // These shouldn't make it here.
3200     case Decl::ObjCAtDefsField:
3201       llvm_unreachable("forming non-member reference to ivar?");
3202 
3203     // Enum constants are always r-values and never references.
3204     // Unresolved using declarations are dependent.
3205     case Decl::EnumConstant:
3206     case Decl::UnresolvedUsingValue:
3207     case Decl::OMPDeclareReduction:
3208     case Decl::OMPDeclareMapper:
3209       valueKind = VK_RValue;
3210       break;
3211 
3212     // Fields and indirect fields that got here must be for
3213     // pointer-to-member expressions; we just call them l-values for
3214     // internal consistency, because this subexpression doesn't really
3215     // exist in the high-level semantics.
3216     case Decl::Field:
3217     case Decl::IndirectField:
3218     case Decl::ObjCIvar:
3219       assert(getLangOpts().CPlusPlus &&
3220              "building reference to field in C?");
3221 
3222       // These can't have reference type in well-formed programs, but
3223       // for internal consistency we do this anyway.
3224       type = type.getNonReferenceType();
3225       valueKind = VK_LValue;
3226       break;
3227 
3228     // Non-type template parameters are either l-values or r-values
3229     // depending on the type.
3230     case Decl::NonTypeTemplateParm: {
3231       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3232         type = reftype->getPointeeType();
3233         valueKind = VK_LValue; // even if the parameter is an r-value reference
3234         break;
3235       }
3236 
3237       // [expr.prim.id.unqual]p2:
3238       //   If the entity is a template parameter object for a template
3239       //   parameter of type T, the type of the expression is const T.
3240       //   [...] The expression is an lvalue if the entity is a [...] template
3241       //   parameter object.
3242       if (type->isRecordType()) {
3243         type = type.getUnqualifiedType().withConst();
3244         valueKind = VK_LValue;
3245         break;
3246       }
3247 
3248       // For non-references, we need to strip qualifiers just in case
3249       // the template parameter was declared as 'const int' or whatever.
3250       valueKind = VK_RValue;
3251       type = type.getUnqualifiedType();
3252       break;
3253     }
3254 
3255     case Decl::Var:
3256     case Decl::VarTemplateSpecialization:
3257     case Decl::VarTemplatePartialSpecialization:
3258     case Decl::Decomposition:
3259     case Decl::OMPCapturedExpr:
3260       // In C, "extern void blah;" is valid and is an r-value.
3261       if (!getLangOpts().CPlusPlus &&
3262           !type.hasQualifiers() &&
3263           type->isVoidType()) {
3264         valueKind = VK_RValue;
3265         break;
3266       }
3267       LLVM_FALLTHROUGH;
3268 
3269     case Decl::ImplicitParam:
3270     case Decl::ParmVar: {
3271       // These are always l-values.
3272       valueKind = VK_LValue;
3273       type = type.getNonReferenceType();
3274 
3275       // FIXME: Does the addition of const really only apply in
3276       // potentially-evaluated contexts? Since the variable isn't actually
3277       // captured in an unevaluated context, it seems that the answer is no.
3278       if (!isUnevaluatedContext()) {
3279         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3280         if (!CapturedType.isNull())
3281           type = CapturedType;
3282       }
3283 
3284       break;
3285     }
3286 
3287     case Decl::Binding: {
3288       // These are always lvalues.
3289       valueKind = VK_LValue;
3290       type = type.getNonReferenceType();
3291       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3292       // decides how that's supposed to work.
3293       auto *BD = cast<BindingDecl>(VD);
3294       if (BD->getDeclContext() != CurContext) {
3295         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3296         if (DD && DD->hasLocalStorage())
3297           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3298       }
3299       break;
3300     }
3301 
3302     case Decl::Function: {
3303       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3304         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3305           type = Context.BuiltinFnTy;
3306           valueKind = VK_RValue;
3307           break;
3308         }
3309       }
3310 
3311       const FunctionType *fty = type->castAs<FunctionType>();
3312 
3313       // If we're referring to a function with an __unknown_anytype
3314       // result type, make the entire expression __unknown_anytype.
3315       if (fty->getReturnType() == Context.UnknownAnyTy) {
3316         type = Context.UnknownAnyTy;
3317         valueKind = VK_RValue;
3318         break;
3319       }
3320 
3321       // Functions are l-values in C++.
3322       if (getLangOpts().CPlusPlus) {
3323         valueKind = VK_LValue;
3324         break;
3325       }
3326 
3327       // C99 DR 316 says that, if a function type comes from a
3328       // function definition (without a prototype), that type is only
3329       // used for checking compatibility. Therefore, when referencing
3330       // the function, we pretend that we don't have the full function
3331       // type.
3332       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3333           isa<FunctionProtoType>(fty))
3334         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3335                                               fty->getExtInfo());
3336 
3337       // Functions are r-values in C.
3338       valueKind = VK_RValue;
3339       break;
3340     }
3341 
3342     case Decl::CXXDeductionGuide:
3343       llvm_unreachable("building reference to deduction guide");
3344 
3345     case Decl::MSProperty:
3346     case Decl::MSGuid:
3347     case Decl::TemplateParamObject:
3348       // FIXME: Should MSGuidDecl and template parameter objects be subject to
3349       // capture in OpenMP, or duplicated between host and device?
3350       valueKind = VK_LValue;
3351       break;
3352 
3353     case Decl::CXXMethod:
3354       // If we're referring to a method with an __unknown_anytype
3355       // result type, make the entire expression __unknown_anytype.
3356       // This should only be possible with a type written directly.
3357       if (const FunctionProtoType *proto
3358             = dyn_cast<FunctionProtoType>(VD->getType()))
3359         if (proto->getReturnType() == Context.UnknownAnyTy) {
3360           type = Context.UnknownAnyTy;
3361           valueKind = VK_RValue;
3362           break;
3363         }
3364 
3365       // C++ methods are l-values if static, r-values if non-static.
3366       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3367         valueKind = VK_LValue;
3368         break;
3369       }
3370       LLVM_FALLTHROUGH;
3371 
3372     case Decl::CXXConversion:
3373     case Decl::CXXDestructor:
3374     case Decl::CXXConstructor:
3375       valueKind = VK_RValue;
3376       break;
3377     }
3378 
3379     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3380                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3381                             TemplateArgs);
3382   }
3383 }
3384 
3385 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3386                                     SmallString<32> &Target) {
3387   Target.resize(CharByteWidth * (Source.size() + 1));
3388   char *ResultPtr = &Target[0];
3389   const llvm::UTF8 *ErrorPtr;
3390   bool success =
3391       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3392   (void)success;
3393   assert(success);
3394   Target.resize(ResultPtr - &Target[0]);
3395 }
3396 
3397 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3398                                      PredefinedExpr::IdentKind IK) {
3399   // Pick the current block, lambda, captured statement or function.
3400   Decl *currentDecl = nullptr;
3401   if (const BlockScopeInfo *BSI = getCurBlock())
3402     currentDecl = BSI->TheDecl;
3403   else if (const LambdaScopeInfo *LSI = getCurLambda())
3404     currentDecl = LSI->CallOperator;
3405   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3406     currentDecl = CSI->TheCapturedDecl;
3407   else
3408     currentDecl = getCurFunctionOrMethodDecl();
3409 
3410   if (!currentDecl) {
3411     Diag(Loc, diag::ext_predef_outside_function);
3412     currentDecl = Context.getTranslationUnitDecl();
3413   }
3414 
3415   QualType ResTy;
3416   StringLiteral *SL = nullptr;
3417   if (cast<DeclContext>(currentDecl)->isDependentContext())
3418     ResTy = Context.DependentTy;
3419   else {
3420     // Pre-defined identifiers are of type char[x], where x is the length of
3421     // the string.
3422     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3423     unsigned Length = Str.length();
3424 
3425     llvm::APInt LengthI(32, Length + 1);
3426     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3427       ResTy =
3428           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3429       SmallString<32> RawChars;
3430       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3431                               Str, RawChars);
3432       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3433                                            ArrayType::Normal,
3434                                            /*IndexTypeQuals*/ 0);
3435       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3436                                  /*Pascal*/ false, ResTy, Loc);
3437     } else {
3438       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3439       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3440                                            ArrayType::Normal,
3441                                            /*IndexTypeQuals*/ 0);
3442       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3443                                  /*Pascal*/ false, ResTy, Loc);
3444     }
3445   }
3446 
3447   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3448 }
3449 
3450 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3451   PredefinedExpr::IdentKind IK;
3452 
3453   switch (Kind) {
3454   default: llvm_unreachable("Unknown simple primary expr!");
3455   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3456   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3457   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3458   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3459   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3460   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3461   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3462   }
3463 
3464   return BuildPredefinedExpr(Loc, IK);
3465 }
3466 
3467 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3468   SmallString<16> CharBuffer;
3469   bool Invalid = false;
3470   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3471   if (Invalid)
3472     return ExprError();
3473 
3474   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3475                             PP, Tok.getKind());
3476   if (Literal.hadError())
3477     return ExprError();
3478 
3479   QualType Ty;
3480   if (Literal.isWide())
3481     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3482   else if (Literal.isUTF8() && getLangOpts().Char8)
3483     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3484   else if (Literal.isUTF16())
3485     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3486   else if (Literal.isUTF32())
3487     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3488   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3489     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3490   else
3491     Ty = Context.CharTy;  // 'x' -> char in C++
3492 
3493   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3494   if (Literal.isWide())
3495     Kind = CharacterLiteral::Wide;
3496   else if (Literal.isUTF16())
3497     Kind = CharacterLiteral::UTF16;
3498   else if (Literal.isUTF32())
3499     Kind = CharacterLiteral::UTF32;
3500   else if (Literal.isUTF8())
3501     Kind = CharacterLiteral::UTF8;
3502 
3503   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3504                                              Tok.getLocation());
3505 
3506   if (Literal.getUDSuffix().empty())
3507     return Lit;
3508 
3509   // We're building a user-defined literal.
3510   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3511   SourceLocation UDSuffixLoc =
3512     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3513 
3514   // Make sure we're allowed user-defined literals here.
3515   if (!UDLScope)
3516     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3517 
3518   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3519   //   operator "" X (ch)
3520   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3521                                         Lit, Tok.getLocation());
3522 }
3523 
3524 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3525   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3526   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3527                                 Context.IntTy, Loc);
3528 }
3529 
3530 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3531                                   QualType Ty, SourceLocation Loc) {
3532   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3533 
3534   using llvm::APFloat;
3535   APFloat Val(Format);
3536 
3537   APFloat::opStatus result = Literal.GetFloatValue(Val);
3538 
3539   // Overflow is always an error, but underflow is only an error if
3540   // we underflowed to zero (APFloat reports denormals as underflow).
3541   if ((result & APFloat::opOverflow) ||
3542       ((result & APFloat::opUnderflow) && Val.isZero())) {
3543     unsigned diagnostic;
3544     SmallString<20> buffer;
3545     if (result & APFloat::opOverflow) {
3546       diagnostic = diag::warn_float_overflow;
3547       APFloat::getLargest(Format).toString(buffer);
3548     } else {
3549       diagnostic = diag::warn_float_underflow;
3550       APFloat::getSmallest(Format).toString(buffer);
3551     }
3552 
3553     S.Diag(Loc, diagnostic)
3554       << Ty
3555       << StringRef(buffer.data(), buffer.size());
3556   }
3557 
3558   bool isExact = (result == APFloat::opOK);
3559   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3560 }
3561 
3562 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3563   assert(E && "Invalid expression");
3564 
3565   if (E->isValueDependent())
3566     return false;
3567 
3568   QualType QT = E->getType();
3569   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3570     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3571     return true;
3572   }
3573 
3574   llvm::APSInt ValueAPS;
3575   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3576 
3577   if (R.isInvalid())
3578     return true;
3579 
3580   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3581   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3582     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3583         << ValueAPS.toString(10) << ValueIsPositive;
3584     return true;
3585   }
3586 
3587   return false;
3588 }
3589 
3590 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3591   // Fast path for a single digit (which is quite common).  A single digit
3592   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3593   if (Tok.getLength() == 1) {
3594     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3595     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3596   }
3597 
3598   SmallString<128> SpellingBuffer;
3599   // NumericLiteralParser wants to overread by one character.  Add padding to
3600   // the buffer in case the token is copied to the buffer.  If getSpelling()
3601   // returns a StringRef to the memory buffer, it should have a null char at
3602   // the EOF, so it is also safe.
3603   SpellingBuffer.resize(Tok.getLength() + 1);
3604 
3605   // Get the spelling of the token, which eliminates trigraphs, etc.
3606   bool Invalid = false;
3607   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3608   if (Invalid)
3609     return ExprError();
3610 
3611   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3612                                PP.getSourceManager(), PP.getLangOpts(),
3613                                PP.getTargetInfo(), PP.getDiagnostics());
3614   if (Literal.hadError)
3615     return ExprError();
3616 
3617   if (Literal.hasUDSuffix()) {
3618     // We're building a user-defined literal.
3619     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3620     SourceLocation UDSuffixLoc =
3621       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3622 
3623     // Make sure we're allowed user-defined literals here.
3624     if (!UDLScope)
3625       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3626 
3627     QualType CookedTy;
3628     if (Literal.isFloatingLiteral()) {
3629       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3630       // long double, the literal is treated as a call of the form
3631       //   operator "" X (f L)
3632       CookedTy = Context.LongDoubleTy;
3633     } else {
3634       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3635       // unsigned long long, the literal is treated as a call of the form
3636       //   operator "" X (n ULL)
3637       CookedTy = Context.UnsignedLongLongTy;
3638     }
3639 
3640     DeclarationName OpName =
3641       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3642     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3643     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3644 
3645     SourceLocation TokLoc = Tok.getLocation();
3646 
3647     // Perform literal operator lookup to determine if we're building a raw
3648     // literal or a cooked one.
3649     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3650     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3651                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3652                                   /*AllowStringTemplatePack*/ false,
3653                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3654     case LOLR_ErrorNoDiagnostic:
3655       // Lookup failure for imaginary constants isn't fatal, there's still the
3656       // GNU extension producing _Complex types.
3657       break;
3658     case LOLR_Error:
3659       return ExprError();
3660     case LOLR_Cooked: {
3661       Expr *Lit;
3662       if (Literal.isFloatingLiteral()) {
3663         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3664       } else {
3665         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3666         if (Literal.GetIntegerValue(ResultVal))
3667           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3668               << /* Unsigned */ 1;
3669         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3670                                      Tok.getLocation());
3671       }
3672       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3673     }
3674 
3675     case LOLR_Raw: {
3676       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3677       // literal is treated as a call of the form
3678       //   operator "" X ("n")
3679       unsigned Length = Literal.getUDSuffixOffset();
3680       QualType StrTy = Context.getConstantArrayType(
3681           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3682           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3683       Expr *Lit = StringLiteral::Create(
3684           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3685           /*Pascal*/false, StrTy, &TokLoc, 1);
3686       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3687     }
3688 
3689     case LOLR_Template: {
3690       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3691       // template), L is treated as a call fo the form
3692       //   operator "" X <'c1', 'c2', ... 'ck'>()
3693       // where n is the source character sequence c1 c2 ... ck.
3694       TemplateArgumentListInfo ExplicitArgs;
3695       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3696       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3697       llvm::APSInt Value(CharBits, CharIsUnsigned);
3698       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3699         Value = TokSpelling[I];
3700         TemplateArgument Arg(Context, Value, Context.CharTy);
3701         TemplateArgumentLocInfo ArgInfo;
3702         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3703       }
3704       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3705                                       &ExplicitArgs);
3706     }
3707     case LOLR_StringTemplatePack:
3708       llvm_unreachable("unexpected literal operator lookup result");
3709     }
3710   }
3711 
3712   Expr *Res;
3713 
3714   if (Literal.isFixedPointLiteral()) {
3715     QualType Ty;
3716 
3717     if (Literal.isAccum) {
3718       if (Literal.isHalf) {
3719         Ty = Context.ShortAccumTy;
3720       } else if (Literal.isLong) {
3721         Ty = Context.LongAccumTy;
3722       } else {
3723         Ty = Context.AccumTy;
3724       }
3725     } else if (Literal.isFract) {
3726       if (Literal.isHalf) {
3727         Ty = Context.ShortFractTy;
3728       } else if (Literal.isLong) {
3729         Ty = Context.LongFractTy;
3730       } else {
3731         Ty = Context.FractTy;
3732       }
3733     }
3734 
3735     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3736 
3737     bool isSigned = !Literal.isUnsigned;
3738     unsigned scale = Context.getFixedPointScale(Ty);
3739     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3740 
3741     llvm::APInt Val(bit_width, 0, isSigned);
3742     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3743     bool ValIsZero = Val.isNullValue() && !Overflowed;
3744 
3745     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3746     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3747       // Clause 6.4.4 - The value of a constant shall be in the range of
3748       // representable values for its type, with exception for constants of a
3749       // fract type with a value of exactly 1; such a constant shall denote
3750       // the maximal value for the type.
3751       --Val;
3752     else if (Val.ugt(MaxVal) || Overflowed)
3753       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3754 
3755     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3756                                               Tok.getLocation(), scale);
3757   } else if (Literal.isFloatingLiteral()) {
3758     QualType Ty;
3759     if (Literal.isHalf){
3760       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3761         Ty = Context.HalfTy;
3762       else {
3763         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3764         return ExprError();
3765       }
3766     } else if (Literal.isFloat)
3767       Ty = Context.FloatTy;
3768     else if (Literal.isLong)
3769       Ty = Context.LongDoubleTy;
3770     else if (Literal.isFloat16)
3771       Ty = Context.Float16Ty;
3772     else if (Literal.isFloat128)
3773       Ty = Context.Float128Ty;
3774     else
3775       Ty = Context.DoubleTy;
3776 
3777     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3778 
3779     if (Ty == Context.DoubleTy) {
3780       if (getLangOpts().SinglePrecisionConstants) {
3781         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3782         if (BTy->getKind() != BuiltinType::Float) {
3783           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3784         }
3785       } else if (getLangOpts().OpenCL &&
3786                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3787         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3788         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3789         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3790       }
3791     }
3792   } else if (!Literal.isIntegerLiteral()) {
3793     return ExprError();
3794   } else {
3795     QualType Ty;
3796 
3797     // 'long long' is a C99 or C++11 feature.
3798     if (!getLangOpts().C99 && Literal.isLongLong) {
3799       if (getLangOpts().CPlusPlus)
3800         Diag(Tok.getLocation(),
3801              getLangOpts().CPlusPlus11 ?
3802              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3803       else
3804         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3805     }
3806 
3807     // Get the value in the widest-possible width.
3808     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3809     llvm::APInt ResultVal(MaxWidth, 0);
3810 
3811     if (Literal.GetIntegerValue(ResultVal)) {
3812       // If this value didn't fit into uintmax_t, error and force to ull.
3813       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3814           << /* Unsigned */ 1;
3815       Ty = Context.UnsignedLongLongTy;
3816       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3817              "long long is not intmax_t?");
3818     } else {
3819       // If this value fits into a ULL, try to figure out what else it fits into
3820       // according to the rules of C99 6.4.4.1p5.
3821 
3822       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3823       // be an unsigned int.
3824       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3825 
3826       // Check from smallest to largest, picking the smallest type we can.
3827       unsigned Width = 0;
3828 
3829       // Microsoft specific integer suffixes are explicitly sized.
3830       if (Literal.MicrosoftInteger) {
3831         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3832           Width = 8;
3833           Ty = Context.CharTy;
3834         } else {
3835           Width = Literal.MicrosoftInteger;
3836           Ty = Context.getIntTypeForBitwidth(Width,
3837                                              /*Signed=*/!Literal.isUnsigned);
3838         }
3839       }
3840 
3841       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3842         // Are int/unsigned possibilities?
3843         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3844 
3845         // Does it fit in a unsigned int?
3846         if (ResultVal.isIntN(IntSize)) {
3847           // Does it fit in a signed int?
3848           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3849             Ty = Context.IntTy;
3850           else if (AllowUnsigned)
3851             Ty = Context.UnsignedIntTy;
3852           Width = IntSize;
3853         }
3854       }
3855 
3856       // Are long/unsigned long possibilities?
3857       if (Ty.isNull() && !Literal.isLongLong) {
3858         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3859 
3860         // Does it fit in a unsigned long?
3861         if (ResultVal.isIntN(LongSize)) {
3862           // Does it fit in a signed long?
3863           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3864             Ty = Context.LongTy;
3865           else if (AllowUnsigned)
3866             Ty = Context.UnsignedLongTy;
3867           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3868           // is compatible.
3869           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3870             const unsigned LongLongSize =
3871                 Context.getTargetInfo().getLongLongWidth();
3872             Diag(Tok.getLocation(),
3873                  getLangOpts().CPlusPlus
3874                      ? Literal.isLong
3875                            ? diag::warn_old_implicitly_unsigned_long_cxx
3876                            : /*C++98 UB*/ diag::
3877                                  ext_old_implicitly_unsigned_long_cxx
3878                      : diag::warn_old_implicitly_unsigned_long)
3879                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3880                                             : /*will be ill-formed*/ 1);
3881             Ty = Context.UnsignedLongTy;
3882           }
3883           Width = LongSize;
3884         }
3885       }
3886 
3887       // Check long long if needed.
3888       if (Ty.isNull()) {
3889         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3890 
3891         // Does it fit in a unsigned long long?
3892         if (ResultVal.isIntN(LongLongSize)) {
3893           // Does it fit in a signed long long?
3894           // To be compatible with MSVC, hex integer literals ending with the
3895           // LL or i64 suffix are always signed in Microsoft mode.
3896           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3897               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3898             Ty = Context.LongLongTy;
3899           else if (AllowUnsigned)
3900             Ty = Context.UnsignedLongLongTy;
3901           Width = LongLongSize;
3902         }
3903       }
3904 
3905       // If we still couldn't decide a type, we probably have something that
3906       // does not fit in a signed long long, but has no U suffix.
3907       if (Ty.isNull()) {
3908         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3909         Ty = Context.UnsignedLongLongTy;
3910         Width = Context.getTargetInfo().getLongLongWidth();
3911       }
3912 
3913       if (ResultVal.getBitWidth() != Width)
3914         ResultVal = ResultVal.trunc(Width);
3915     }
3916     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3917   }
3918 
3919   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3920   if (Literal.isImaginary) {
3921     Res = new (Context) ImaginaryLiteral(Res,
3922                                         Context.getComplexType(Res->getType()));
3923 
3924     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3925   }
3926   return Res;
3927 }
3928 
3929 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3930   assert(E && "ActOnParenExpr() missing expr");
3931   return new (Context) ParenExpr(L, R, E);
3932 }
3933 
3934 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3935                                          SourceLocation Loc,
3936                                          SourceRange ArgRange) {
3937   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3938   // scalar or vector data type argument..."
3939   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3940   // type (C99 6.2.5p18) or void.
3941   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3942     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3943       << T << ArgRange;
3944     return true;
3945   }
3946 
3947   assert((T->isVoidType() || !T->isIncompleteType()) &&
3948          "Scalar types should always be complete");
3949   return false;
3950 }
3951 
3952 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3953                                            SourceLocation Loc,
3954                                            SourceRange ArgRange,
3955                                            UnaryExprOrTypeTrait TraitKind) {
3956   // Invalid types must be hard errors for SFINAE in C++.
3957   if (S.LangOpts.CPlusPlus)
3958     return true;
3959 
3960   // C99 6.5.3.4p1:
3961   if (T->isFunctionType() &&
3962       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3963        TraitKind == UETT_PreferredAlignOf)) {
3964     // sizeof(function)/alignof(function) is allowed as an extension.
3965     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3966         << getTraitSpelling(TraitKind) << ArgRange;
3967     return false;
3968   }
3969 
3970   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3971   // this is an error (OpenCL v1.1 s6.3.k)
3972   if (T->isVoidType()) {
3973     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3974                                         : diag::ext_sizeof_alignof_void_type;
3975     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
3976     return false;
3977   }
3978 
3979   return true;
3980 }
3981 
3982 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3983                                              SourceLocation Loc,
3984                                              SourceRange ArgRange,
3985                                              UnaryExprOrTypeTrait TraitKind) {
3986   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3987   // runtime doesn't allow it.
3988   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3989     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3990       << T << (TraitKind == UETT_SizeOf)
3991       << ArgRange;
3992     return true;
3993   }
3994 
3995   return false;
3996 }
3997 
3998 /// Check whether E is a pointer from a decayed array type (the decayed
3999 /// pointer type is equal to T) and emit a warning if it is.
4000 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4001                                      Expr *E) {
4002   // Don't warn if the operation changed the type.
4003   if (T != E->getType())
4004     return;
4005 
4006   // Now look for array decays.
4007   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4008   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4009     return;
4010 
4011   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4012                                              << ICE->getType()
4013                                              << ICE->getSubExpr()->getType();
4014 }
4015 
4016 /// Check the constraints on expression operands to unary type expression
4017 /// and type traits.
4018 ///
4019 /// Completes any types necessary and validates the constraints on the operand
4020 /// expression. The logic mostly mirrors the type-based overload, but may modify
4021 /// the expression as it completes the type for that expression through template
4022 /// instantiation, etc.
4023 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4024                                             UnaryExprOrTypeTrait ExprKind) {
4025   QualType ExprTy = E->getType();
4026   assert(!ExprTy->isReferenceType());
4027 
4028   bool IsUnevaluatedOperand =
4029       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4030        ExprKind == UETT_PreferredAlignOf);
4031   if (IsUnevaluatedOperand) {
4032     ExprResult Result = CheckUnevaluatedOperand(E);
4033     if (Result.isInvalid())
4034       return true;
4035     E = Result.get();
4036   }
4037 
4038   if (ExprKind == UETT_VecStep)
4039     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4040                                         E->getSourceRange());
4041 
4042   // Explicitly list some types as extensions.
4043   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4044                                       E->getSourceRange(), ExprKind))
4045     return false;
4046 
4047   // 'alignof' applied to an expression only requires the base element type of
4048   // the expression to be complete. 'sizeof' requires the expression's type to
4049   // be complete (and will attempt to complete it if it's an array of unknown
4050   // bound).
4051   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4052     if (RequireCompleteSizedType(
4053             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4054             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4055             getTraitSpelling(ExprKind), E->getSourceRange()))
4056       return true;
4057   } else {
4058     if (RequireCompleteSizedExprType(
4059             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4060             getTraitSpelling(ExprKind), E->getSourceRange()))
4061       return true;
4062   }
4063 
4064   // Completing the expression's type may have changed it.
4065   ExprTy = E->getType();
4066   assert(!ExprTy->isReferenceType());
4067 
4068   if (ExprTy->isFunctionType()) {
4069     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4070         << getTraitSpelling(ExprKind) << E->getSourceRange();
4071     return true;
4072   }
4073 
4074   // The operand for sizeof and alignof is in an unevaluated expression context,
4075   // so side effects could result in unintended consequences.
4076   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4077       E->HasSideEffects(Context, false))
4078     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4079 
4080   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4081                                        E->getSourceRange(), ExprKind))
4082     return true;
4083 
4084   if (ExprKind == UETT_SizeOf) {
4085     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4086       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4087         QualType OType = PVD->getOriginalType();
4088         QualType Type = PVD->getType();
4089         if (Type->isPointerType() && OType->isArrayType()) {
4090           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4091             << Type << OType;
4092           Diag(PVD->getLocation(), diag::note_declared_at);
4093         }
4094       }
4095     }
4096 
4097     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4098     // decays into a pointer and returns an unintended result. This is most
4099     // likely a typo for "sizeof(array) op x".
4100     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4101       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4102                                BO->getLHS());
4103       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4104                                BO->getRHS());
4105     }
4106   }
4107 
4108   return false;
4109 }
4110 
4111 /// Check the constraints on operands to unary expression and type
4112 /// traits.
4113 ///
4114 /// This will complete any types necessary, and validate the various constraints
4115 /// on those operands.
4116 ///
4117 /// The UsualUnaryConversions() function is *not* called by this routine.
4118 /// C99 6.3.2.1p[2-4] all state:
4119 ///   Except when it is the operand of the sizeof operator ...
4120 ///
4121 /// C++ [expr.sizeof]p4
4122 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4123 ///   standard conversions are not applied to the operand of sizeof.
4124 ///
4125 /// This policy is followed for all of the unary trait expressions.
4126 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4127                                             SourceLocation OpLoc,
4128                                             SourceRange ExprRange,
4129                                             UnaryExprOrTypeTrait ExprKind) {
4130   if (ExprType->isDependentType())
4131     return false;
4132 
4133   // C++ [expr.sizeof]p2:
4134   //     When applied to a reference or a reference type, the result
4135   //     is the size of the referenced type.
4136   // C++11 [expr.alignof]p3:
4137   //     When alignof is applied to a reference type, the result
4138   //     shall be the alignment of the referenced type.
4139   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4140     ExprType = Ref->getPointeeType();
4141 
4142   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4143   //   When alignof or _Alignof is applied to an array type, the result
4144   //   is the alignment of the element type.
4145   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4146       ExprKind == UETT_OpenMPRequiredSimdAlign)
4147     ExprType = Context.getBaseElementType(ExprType);
4148 
4149   if (ExprKind == UETT_VecStep)
4150     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4151 
4152   // Explicitly list some types as extensions.
4153   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4154                                       ExprKind))
4155     return false;
4156 
4157   if (RequireCompleteSizedType(
4158           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4159           getTraitSpelling(ExprKind), ExprRange))
4160     return true;
4161 
4162   if (ExprType->isFunctionType()) {
4163     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4164         << getTraitSpelling(ExprKind) << ExprRange;
4165     return true;
4166   }
4167 
4168   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4169                                        ExprKind))
4170     return true;
4171 
4172   return false;
4173 }
4174 
4175 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4176   // Cannot know anything else if the expression is dependent.
4177   if (E->isTypeDependent())
4178     return false;
4179 
4180   if (E->getObjectKind() == OK_BitField) {
4181     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4182        << 1 << E->getSourceRange();
4183     return true;
4184   }
4185 
4186   ValueDecl *D = nullptr;
4187   Expr *Inner = E->IgnoreParens();
4188   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4189     D = DRE->getDecl();
4190   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4191     D = ME->getMemberDecl();
4192   }
4193 
4194   // If it's a field, require the containing struct to have a
4195   // complete definition so that we can compute the layout.
4196   //
4197   // This can happen in C++11 onwards, either by naming the member
4198   // in a way that is not transformed into a member access expression
4199   // (in an unevaluated operand, for instance), or by naming the member
4200   // in a trailing-return-type.
4201   //
4202   // For the record, since __alignof__ on expressions is a GCC
4203   // extension, GCC seems to permit this but always gives the
4204   // nonsensical answer 0.
4205   //
4206   // We don't really need the layout here --- we could instead just
4207   // directly check for all the appropriate alignment-lowing
4208   // attributes --- but that would require duplicating a lot of
4209   // logic that just isn't worth duplicating for such a marginal
4210   // use-case.
4211   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4212     // Fast path this check, since we at least know the record has a
4213     // definition if we can find a member of it.
4214     if (!FD->getParent()->isCompleteDefinition()) {
4215       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4216         << E->getSourceRange();
4217       return true;
4218     }
4219 
4220     // Otherwise, if it's a field, and the field doesn't have
4221     // reference type, then it must have a complete type (or be a
4222     // flexible array member, which we explicitly want to
4223     // white-list anyway), which makes the following checks trivial.
4224     if (!FD->getType()->isReferenceType())
4225       return false;
4226   }
4227 
4228   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4229 }
4230 
4231 bool Sema::CheckVecStepExpr(Expr *E) {
4232   E = E->IgnoreParens();
4233 
4234   // Cannot know anything else if the expression is dependent.
4235   if (E->isTypeDependent())
4236     return false;
4237 
4238   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4239 }
4240 
4241 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4242                                         CapturingScopeInfo *CSI) {
4243   assert(T->isVariablyModifiedType());
4244   assert(CSI != nullptr);
4245 
4246   // We're going to walk down into the type and look for VLA expressions.
4247   do {
4248     const Type *Ty = T.getTypePtr();
4249     switch (Ty->getTypeClass()) {
4250 #define TYPE(Class, Base)
4251 #define ABSTRACT_TYPE(Class, Base)
4252 #define NON_CANONICAL_TYPE(Class, Base)
4253 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4254 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4255 #include "clang/AST/TypeNodes.inc"
4256       T = QualType();
4257       break;
4258     // These types are never variably-modified.
4259     case Type::Builtin:
4260     case Type::Complex:
4261     case Type::Vector:
4262     case Type::ExtVector:
4263     case Type::ConstantMatrix:
4264     case Type::Record:
4265     case Type::Enum:
4266     case Type::Elaborated:
4267     case Type::TemplateSpecialization:
4268     case Type::ObjCObject:
4269     case Type::ObjCInterface:
4270     case Type::ObjCObjectPointer:
4271     case Type::ObjCTypeParam:
4272     case Type::Pipe:
4273     case Type::ExtInt:
4274       llvm_unreachable("type class is never variably-modified!");
4275     case Type::Adjusted:
4276       T = cast<AdjustedType>(Ty)->getOriginalType();
4277       break;
4278     case Type::Decayed:
4279       T = cast<DecayedType>(Ty)->getPointeeType();
4280       break;
4281     case Type::Pointer:
4282       T = cast<PointerType>(Ty)->getPointeeType();
4283       break;
4284     case Type::BlockPointer:
4285       T = cast<BlockPointerType>(Ty)->getPointeeType();
4286       break;
4287     case Type::LValueReference:
4288     case Type::RValueReference:
4289       T = cast<ReferenceType>(Ty)->getPointeeType();
4290       break;
4291     case Type::MemberPointer:
4292       T = cast<MemberPointerType>(Ty)->getPointeeType();
4293       break;
4294     case Type::ConstantArray:
4295     case Type::IncompleteArray:
4296       // Losing element qualification here is fine.
4297       T = cast<ArrayType>(Ty)->getElementType();
4298       break;
4299     case Type::VariableArray: {
4300       // Losing element qualification here is fine.
4301       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4302 
4303       // Unknown size indication requires no size computation.
4304       // Otherwise, evaluate and record it.
4305       auto Size = VAT->getSizeExpr();
4306       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4307           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4308         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4309 
4310       T = VAT->getElementType();
4311       break;
4312     }
4313     case Type::FunctionProto:
4314     case Type::FunctionNoProto:
4315       T = cast<FunctionType>(Ty)->getReturnType();
4316       break;
4317     case Type::Paren:
4318     case Type::TypeOf:
4319     case Type::UnaryTransform:
4320     case Type::Attributed:
4321     case Type::SubstTemplateTypeParm:
4322     case Type::MacroQualified:
4323       // Keep walking after single level desugaring.
4324       T = T.getSingleStepDesugaredType(Context);
4325       break;
4326     case Type::Typedef:
4327       T = cast<TypedefType>(Ty)->desugar();
4328       break;
4329     case Type::Decltype:
4330       T = cast<DecltypeType>(Ty)->desugar();
4331       break;
4332     case Type::Auto:
4333     case Type::DeducedTemplateSpecialization:
4334       T = cast<DeducedType>(Ty)->getDeducedType();
4335       break;
4336     case Type::TypeOfExpr:
4337       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4338       break;
4339     case Type::Atomic:
4340       T = cast<AtomicType>(Ty)->getValueType();
4341       break;
4342     }
4343   } while (!T.isNull() && T->isVariablyModifiedType());
4344 }
4345 
4346 /// Build a sizeof or alignof expression given a type operand.
4347 ExprResult
4348 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4349                                      SourceLocation OpLoc,
4350                                      UnaryExprOrTypeTrait ExprKind,
4351                                      SourceRange R) {
4352   if (!TInfo)
4353     return ExprError();
4354 
4355   QualType T = TInfo->getType();
4356 
4357   if (!T->isDependentType() &&
4358       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4359     return ExprError();
4360 
4361   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4362     if (auto *TT = T->getAs<TypedefType>()) {
4363       for (auto I = FunctionScopes.rbegin(),
4364                 E = std::prev(FunctionScopes.rend());
4365            I != E; ++I) {
4366         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4367         if (CSI == nullptr)
4368           break;
4369         DeclContext *DC = nullptr;
4370         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4371           DC = LSI->CallOperator;
4372         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4373           DC = CRSI->TheCapturedDecl;
4374         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4375           DC = BSI->TheDecl;
4376         if (DC) {
4377           if (DC->containsDecl(TT->getDecl()))
4378             break;
4379           captureVariablyModifiedType(Context, T, CSI);
4380         }
4381       }
4382     }
4383   }
4384 
4385   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4386   return new (Context) UnaryExprOrTypeTraitExpr(
4387       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4388 }
4389 
4390 /// Build a sizeof or alignof expression given an expression
4391 /// operand.
4392 ExprResult
4393 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4394                                      UnaryExprOrTypeTrait ExprKind) {
4395   ExprResult PE = CheckPlaceholderExpr(E);
4396   if (PE.isInvalid())
4397     return ExprError();
4398 
4399   E = PE.get();
4400 
4401   // Verify that the operand is valid.
4402   bool isInvalid = false;
4403   if (E->isTypeDependent()) {
4404     // Delay type-checking for type-dependent expressions.
4405   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4406     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4407   } else if (ExprKind == UETT_VecStep) {
4408     isInvalid = CheckVecStepExpr(E);
4409   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4410       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4411       isInvalid = true;
4412   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4413     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4414     isInvalid = true;
4415   } else {
4416     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4417   }
4418 
4419   if (isInvalid)
4420     return ExprError();
4421 
4422   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4423     PE = TransformToPotentiallyEvaluated(E);
4424     if (PE.isInvalid()) return ExprError();
4425     E = PE.get();
4426   }
4427 
4428   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4429   return new (Context) UnaryExprOrTypeTraitExpr(
4430       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4431 }
4432 
4433 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4434 /// expr and the same for @c alignof and @c __alignof
4435 /// Note that the ArgRange is invalid if isType is false.
4436 ExprResult
4437 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4438                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4439                                     void *TyOrEx, SourceRange ArgRange) {
4440   // If error parsing type, ignore.
4441   if (!TyOrEx) return ExprError();
4442 
4443   if (IsType) {
4444     TypeSourceInfo *TInfo;
4445     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4446     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4447   }
4448 
4449   Expr *ArgEx = (Expr *)TyOrEx;
4450   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4451   return Result;
4452 }
4453 
4454 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4455                                      bool IsReal) {
4456   if (V.get()->isTypeDependent())
4457     return S.Context.DependentTy;
4458 
4459   // _Real and _Imag are only l-values for normal l-values.
4460   if (V.get()->getObjectKind() != OK_Ordinary) {
4461     V = S.DefaultLvalueConversion(V.get());
4462     if (V.isInvalid())
4463       return QualType();
4464   }
4465 
4466   // These operators return the element type of a complex type.
4467   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4468     return CT->getElementType();
4469 
4470   // Otherwise they pass through real integer and floating point types here.
4471   if (V.get()->getType()->isArithmeticType())
4472     return V.get()->getType();
4473 
4474   // Test for placeholders.
4475   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4476   if (PR.isInvalid()) return QualType();
4477   if (PR.get() != V.get()) {
4478     V = PR;
4479     return CheckRealImagOperand(S, V, Loc, IsReal);
4480   }
4481 
4482   // Reject anything else.
4483   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4484     << (IsReal ? "__real" : "__imag");
4485   return QualType();
4486 }
4487 
4488 
4489 
4490 ExprResult
4491 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4492                           tok::TokenKind Kind, Expr *Input) {
4493   UnaryOperatorKind Opc;
4494   switch (Kind) {
4495   default: llvm_unreachable("Unknown unary op!");
4496   case tok::plusplus:   Opc = UO_PostInc; break;
4497   case tok::minusminus: Opc = UO_PostDec; break;
4498   }
4499 
4500   // Since this might is a postfix expression, get rid of ParenListExprs.
4501   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4502   if (Result.isInvalid()) return ExprError();
4503   Input = Result.get();
4504 
4505   return BuildUnaryOp(S, OpLoc, Opc, Input);
4506 }
4507 
4508 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4509 ///
4510 /// \return true on error
4511 static bool checkArithmeticOnObjCPointer(Sema &S,
4512                                          SourceLocation opLoc,
4513                                          Expr *op) {
4514   assert(op->getType()->isObjCObjectPointerType());
4515   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4516       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4517     return false;
4518 
4519   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4520     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4521     << op->getSourceRange();
4522   return true;
4523 }
4524 
4525 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4526   auto *BaseNoParens = Base->IgnoreParens();
4527   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4528     return MSProp->getPropertyDecl()->getType()->isArrayType();
4529   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4530 }
4531 
4532 ExprResult
4533 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4534                               Expr *idx, SourceLocation rbLoc) {
4535   if (base && !base->getType().isNull() &&
4536       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4537     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4538                                     SourceLocation(), /*Length*/ nullptr,
4539                                     /*Stride=*/nullptr, rbLoc);
4540 
4541   // Since this might be a postfix expression, get rid of ParenListExprs.
4542   if (isa<ParenListExpr>(base)) {
4543     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4544     if (result.isInvalid()) return ExprError();
4545     base = result.get();
4546   }
4547 
4548   // Check if base and idx form a MatrixSubscriptExpr.
4549   //
4550   // Helper to check for comma expressions, which are not allowed as indices for
4551   // matrix subscript expressions.
4552   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4553     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4554       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4555           << SourceRange(base->getBeginLoc(), rbLoc);
4556       return true;
4557     }
4558     return false;
4559   };
4560   // The matrix subscript operator ([][])is considered a single operator.
4561   // Separating the index expressions by parenthesis is not allowed.
4562   if (base->getType()->isSpecificPlaceholderType(
4563           BuiltinType::IncompleteMatrixIdx) &&
4564       !isa<MatrixSubscriptExpr>(base)) {
4565     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4566         << SourceRange(base->getBeginLoc(), rbLoc);
4567     return ExprError();
4568   }
4569   // If the base is a MatrixSubscriptExpr, try to create a new
4570   // MatrixSubscriptExpr.
4571   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4572   if (matSubscriptE) {
4573     if (CheckAndReportCommaError(idx))
4574       return ExprError();
4575 
4576     assert(matSubscriptE->isIncomplete() &&
4577            "base has to be an incomplete matrix subscript");
4578     return CreateBuiltinMatrixSubscriptExpr(
4579         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4580   }
4581 
4582   // Handle any non-overload placeholder types in the base and index
4583   // expressions.  We can't handle overloads here because the other
4584   // operand might be an overloadable type, in which case the overload
4585   // resolution for the operator overload should get the first crack
4586   // at the overload.
4587   bool IsMSPropertySubscript = false;
4588   if (base->getType()->isNonOverloadPlaceholderType()) {
4589     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4590     if (!IsMSPropertySubscript) {
4591       ExprResult result = CheckPlaceholderExpr(base);
4592       if (result.isInvalid())
4593         return ExprError();
4594       base = result.get();
4595     }
4596   }
4597 
4598   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4599   if (base->getType()->isMatrixType()) {
4600     if (CheckAndReportCommaError(idx))
4601       return ExprError();
4602 
4603     return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4604   }
4605 
4606   // A comma-expression as the index is deprecated in C++2a onwards.
4607   if (getLangOpts().CPlusPlus20 &&
4608       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4609        (isa<CXXOperatorCallExpr>(idx) &&
4610         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4611     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4612         << SourceRange(base->getBeginLoc(), rbLoc);
4613   }
4614 
4615   if (idx->getType()->isNonOverloadPlaceholderType()) {
4616     ExprResult result = CheckPlaceholderExpr(idx);
4617     if (result.isInvalid()) return ExprError();
4618     idx = result.get();
4619   }
4620 
4621   // Build an unanalyzed expression if either operand is type-dependent.
4622   if (getLangOpts().CPlusPlus &&
4623       (base->isTypeDependent() || idx->isTypeDependent())) {
4624     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4625                                             VK_LValue, OK_Ordinary, rbLoc);
4626   }
4627 
4628   // MSDN, property (C++)
4629   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4630   // This attribute can also be used in the declaration of an empty array in a
4631   // class or structure definition. For example:
4632   // __declspec(property(get=GetX, put=PutX)) int x[];
4633   // The above statement indicates that x[] can be used with one or more array
4634   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4635   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4636   if (IsMSPropertySubscript) {
4637     // Build MS property subscript expression if base is MS property reference
4638     // or MS property subscript.
4639     return new (Context) MSPropertySubscriptExpr(
4640         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4641   }
4642 
4643   // Use C++ overloaded-operator rules if either operand has record
4644   // type.  The spec says to do this if either type is *overloadable*,
4645   // but enum types can't declare subscript operators or conversion
4646   // operators, so there's nothing interesting for overload resolution
4647   // to do if there aren't any record types involved.
4648   //
4649   // ObjC pointers have their own subscripting logic that is not tied
4650   // to overload resolution and so should not take this path.
4651   if (getLangOpts().CPlusPlus &&
4652       (base->getType()->isRecordType() ||
4653        (!base->getType()->isObjCObjectPointerType() &&
4654         idx->getType()->isRecordType()))) {
4655     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4656   }
4657 
4658   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4659 
4660   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4661     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4662 
4663   return Res;
4664 }
4665 
4666 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4667   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4668   InitializationKind Kind =
4669       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4670   InitializationSequence InitSeq(*this, Entity, Kind, E);
4671   return InitSeq.Perform(*this, Entity, Kind, E);
4672 }
4673 
4674 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4675                                                   Expr *ColumnIdx,
4676                                                   SourceLocation RBLoc) {
4677   ExprResult BaseR = CheckPlaceholderExpr(Base);
4678   if (BaseR.isInvalid())
4679     return BaseR;
4680   Base = BaseR.get();
4681 
4682   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4683   if (RowR.isInvalid())
4684     return RowR;
4685   RowIdx = RowR.get();
4686 
4687   if (!ColumnIdx)
4688     return new (Context) MatrixSubscriptExpr(
4689         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4690 
4691   // Build an unanalyzed expression if any of the operands is type-dependent.
4692   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4693       ColumnIdx->isTypeDependent())
4694     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4695                                              Context.DependentTy, RBLoc);
4696 
4697   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4698   if (ColumnR.isInvalid())
4699     return ColumnR;
4700   ColumnIdx = ColumnR.get();
4701 
4702   // Check that IndexExpr is an integer expression. If it is a constant
4703   // expression, check that it is less than Dim (= the number of elements in the
4704   // corresponding dimension).
4705   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4706                           bool IsColumnIdx) -> Expr * {
4707     if (!IndexExpr->getType()->isIntegerType() &&
4708         !IndexExpr->isTypeDependent()) {
4709       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4710           << IsColumnIdx;
4711       return nullptr;
4712     }
4713 
4714     if (Optional<llvm::APSInt> Idx =
4715             IndexExpr->getIntegerConstantExpr(Context)) {
4716       if ((*Idx < 0 || *Idx >= Dim)) {
4717         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4718             << IsColumnIdx << Dim;
4719         return nullptr;
4720       }
4721     }
4722 
4723     ExprResult ConvExpr =
4724         tryConvertExprToType(IndexExpr, Context.getSizeType());
4725     assert(!ConvExpr.isInvalid() &&
4726            "should be able to convert any integer type to size type");
4727     return ConvExpr.get();
4728   };
4729 
4730   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4731   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4732   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4733   if (!RowIdx || !ColumnIdx)
4734     return ExprError();
4735 
4736   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4737                                            MTy->getElementType(), RBLoc);
4738 }
4739 
4740 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4741   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4742   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4743 
4744   // For expressions like `&(*s).b`, the base is recorded and what should be
4745   // checked.
4746   const MemberExpr *Member = nullptr;
4747   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4748     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4749 
4750   LastRecord.PossibleDerefs.erase(StrippedExpr);
4751 }
4752 
4753 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4754   QualType ResultTy = E->getType();
4755   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4756 
4757   // Bail if the element is an array since it is not memory access.
4758   if (isa<ArrayType>(ResultTy))
4759     return;
4760 
4761   if (ResultTy->hasAttr(attr::NoDeref)) {
4762     LastRecord.PossibleDerefs.insert(E);
4763     return;
4764   }
4765 
4766   // Check if the base type is a pointer to a member access of a struct
4767   // marked with noderef.
4768   const Expr *Base = E->getBase();
4769   QualType BaseTy = Base->getType();
4770   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4771     // Not a pointer access
4772     return;
4773 
4774   const MemberExpr *Member = nullptr;
4775   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4776          Member->isArrow())
4777     Base = Member->getBase();
4778 
4779   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4780     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4781       LastRecord.PossibleDerefs.insert(E);
4782   }
4783 }
4784 
4785 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4786                                           Expr *LowerBound,
4787                                           SourceLocation ColonLocFirst,
4788                                           SourceLocation ColonLocSecond,
4789                                           Expr *Length, Expr *Stride,
4790                                           SourceLocation RBLoc) {
4791   if (Base->getType()->isPlaceholderType() &&
4792       !Base->getType()->isSpecificPlaceholderType(
4793           BuiltinType::OMPArraySection)) {
4794     ExprResult Result = CheckPlaceholderExpr(Base);
4795     if (Result.isInvalid())
4796       return ExprError();
4797     Base = Result.get();
4798   }
4799   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4800     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4801     if (Result.isInvalid())
4802       return ExprError();
4803     Result = DefaultLvalueConversion(Result.get());
4804     if (Result.isInvalid())
4805       return ExprError();
4806     LowerBound = Result.get();
4807   }
4808   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4809     ExprResult Result = CheckPlaceholderExpr(Length);
4810     if (Result.isInvalid())
4811       return ExprError();
4812     Result = DefaultLvalueConversion(Result.get());
4813     if (Result.isInvalid())
4814       return ExprError();
4815     Length = Result.get();
4816   }
4817   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4818     ExprResult Result = CheckPlaceholderExpr(Stride);
4819     if (Result.isInvalid())
4820       return ExprError();
4821     Result = DefaultLvalueConversion(Result.get());
4822     if (Result.isInvalid())
4823       return ExprError();
4824     Stride = Result.get();
4825   }
4826 
4827   // Build an unanalyzed expression if either operand is type-dependent.
4828   if (Base->isTypeDependent() ||
4829       (LowerBound &&
4830        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4831       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4832       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4833     return new (Context) OMPArraySectionExpr(
4834         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4835         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4836   }
4837 
4838   // Perform default conversions.
4839   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4840   QualType ResultTy;
4841   if (OriginalTy->isAnyPointerType()) {
4842     ResultTy = OriginalTy->getPointeeType();
4843   } else if (OriginalTy->isArrayType()) {
4844     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4845   } else {
4846     return ExprError(
4847         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4848         << Base->getSourceRange());
4849   }
4850   // C99 6.5.2.1p1
4851   if (LowerBound) {
4852     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4853                                                       LowerBound);
4854     if (Res.isInvalid())
4855       return ExprError(Diag(LowerBound->getExprLoc(),
4856                             diag::err_omp_typecheck_section_not_integer)
4857                        << 0 << LowerBound->getSourceRange());
4858     LowerBound = Res.get();
4859 
4860     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4861         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4862       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4863           << 0 << LowerBound->getSourceRange();
4864   }
4865   if (Length) {
4866     auto Res =
4867         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4868     if (Res.isInvalid())
4869       return ExprError(Diag(Length->getExprLoc(),
4870                             diag::err_omp_typecheck_section_not_integer)
4871                        << 1 << Length->getSourceRange());
4872     Length = Res.get();
4873 
4874     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4875         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4876       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4877           << 1 << Length->getSourceRange();
4878   }
4879   if (Stride) {
4880     ExprResult Res =
4881         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4882     if (Res.isInvalid())
4883       return ExprError(Diag(Stride->getExprLoc(),
4884                             diag::err_omp_typecheck_section_not_integer)
4885                        << 1 << Stride->getSourceRange());
4886     Stride = Res.get();
4887 
4888     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4889         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4890       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4891           << 1 << Stride->getSourceRange();
4892   }
4893 
4894   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4895   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4896   // type. Note that functions are not objects, and that (in C99 parlance)
4897   // incomplete types are not object types.
4898   if (ResultTy->isFunctionType()) {
4899     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4900         << ResultTy << Base->getSourceRange();
4901     return ExprError();
4902   }
4903 
4904   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4905                           diag::err_omp_section_incomplete_type, Base))
4906     return ExprError();
4907 
4908   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4909     Expr::EvalResult Result;
4910     if (LowerBound->EvaluateAsInt(Result, Context)) {
4911       // OpenMP 5.0, [2.1.5 Array Sections]
4912       // The array section must be a subset of the original array.
4913       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4914       if (LowerBoundValue.isNegative()) {
4915         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4916             << LowerBound->getSourceRange();
4917         return ExprError();
4918       }
4919     }
4920   }
4921 
4922   if (Length) {
4923     Expr::EvalResult Result;
4924     if (Length->EvaluateAsInt(Result, Context)) {
4925       // OpenMP 5.0, [2.1.5 Array Sections]
4926       // The length must evaluate to non-negative integers.
4927       llvm::APSInt LengthValue = Result.Val.getInt();
4928       if (LengthValue.isNegative()) {
4929         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4930             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4931             << Length->getSourceRange();
4932         return ExprError();
4933       }
4934     }
4935   } else if (ColonLocFirst.isValid() &&
4936              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4937                                       !OriginalTy->isVariableArrayType()))) {
4938     // OpenMP 5.0, [2.1.5 Array Sections]
4939     // When the size of the array dimension is not known, the length must be
4940     // specified explicitly.
4941     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
4942         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4943     return ExprError();
4944   }
4945 
4946   if (Stride) {
4947     Expr::EvalResult Result;
4948     if (Stride->EvaluateAsInt(Result, Context)) {
4949       // OpenMP 5.0, [2.1.5 Array Sections]
4950       // The stride must evaluate to a positive integer.
4951       llvm::APSInt StrideValue = Result.Val.getInt();
4952       if (!StrideValue.isStrictlyPositive()) {
4953         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
4954             << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
4955             << Stride->getSourceRange();
4956         return ExprError();
4957       }
4958     }
4959   }
4960 
4961   if (!Base->getType()->isSpecificPlaceholderType(
4962           BuiltinType::OMPArraySection)) {
4963     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4964     if (Result.isInvalid())
4965       return ExprError();
4966     Base = Result.get();
4967   }
4968   return new (Context) OMPArraySectionExpr(
4969       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
4970       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4971 }
4972 
4973 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
4974                                           SourceLocation RParenLoc,
4975                                           ArrayRef<Expr *> Dims,
4976                                           ArrayRef<SourceRange> Brackets) {
4977   if (Base->getType()->isPlaceholderType()) {
4978     ExprResult Result = CheckPlaceholderExpr(Base);
4979     if (Result.isInvalid())
4980       return ExprError();
4981     Result = DefaultLvalueConversion(Result.get());
4982     if (Result.isInvalid())
4983       return ExprError();
4984     Base = Result.get();
4985   }
4986   QualType BaseTy = Base->getType();
4987   // Delay analysis of the types/expressions if instantiation/specialization is
4988   // required.
4989   if (!BaseTy->isPointerType() && Base->isTypeDependent())
4990     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
4991                                        LParenLoc, RParenLoc, Dims, Brackets);
4992   if (!BaseTy->isPointerType() ||
4993       (!Base->isTypeDependent() &&
4994        BaseTy->getPointeeType()->isIncompleteType()))
4995     return ExprError(Diag(Base->getExprLoc(),
4996                           diag::err_omp_non_pointer_type_array_shaping_base)
4997                      << Base->getSourceRange());
4998 
4999   SmallVector<Expr *, 4> NewDims;
5000   bool ErrorFound = false;
5001   for (Expr *Dim : Dims) {
5002     if (Dim->getType()->isPlaceholderType()) {
5003       ExprResult Result = CheckPlaceholderExpr(Dim);
5004       if (Result.isInvalid()) {
5005         ErrorFound = true;
5006         continue;
5007       }
5008       Result = DefaultLvalueConversion(Result.get());
5009       if (Result.isInvalid()) {
5010         ErrorFound = true;
5011         continue;
5012       }
5013       Dim = Result.get();
5014     }
5015     if (!Dim->isTypeDependent()) {
5016       ExprResult Result =
5017           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5018       if (Result.isInvalid()) {
5019         ErrorFound = true;
5020         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5021             << Dim->getSourceRange();
5022         continue;
5023       }
5024       Dim = Result.get();
5025       Expr::EvalResult EvResult;
5026       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5027         // OpenMP 5.0, [2.1.4 Array Shaping]
5028         // Each si is an integral type expression that must evaluate to a
5029         // positive integer.
5030         llvm::APSInt Value = EvResult.Val.getInt();
5031         if (!Value.isStrictlyPositive()) {
5032           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5033               << Value.toString(/*Radix=*/10, /*Signed=*/true)
5034               << Dim->getSourceRange();
5035           ErrorFound = true;
5036           continue;
5037         }
5038       }
5039     }
5040     NewDims.push_back(Dim);
5041   }
5042   if (ErrorFound)
5043     return ExprError();
5044   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5045                                      LParenLoc, RParenLoc, NewDims, Brackets);
5046 }
5047 
5048 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5049                                       SourceLocation LLoc, SourceLocation RLoc,
5050                                       ArrayRef<OMPIteratorData> Data) {
5051   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5052   bool IsCorrect = true;
5053   for (const OMPIteratorData &D : Data) {
5054     TypeSourceInfo *TInfo = nullptr;
5055     SourceLocation StartLoc;
5056     QualType DeclTy;
5057     if (!D.Type.getAsOpaquePtr()) {
5058       // OpenMP 5.0, 2.1.6 Iterators
5059       // In an iterator-specifier, if the iterator-type is not specified then
5060       // the type of that iterator is of int type.
5061       DeclTy = Context.IntTy;
5062       StartLoc = D.DeclIdentLoc;
5063     } else {
5064       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5065       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5066     }
5067 
5068     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5069                              DeclTy->containsUnexpandedParameterPack() ||
5070                              DeclTy->isInstantiationDependentType();
5071     if (!IsDeclTyDependent) {
5072       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5073         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5074         // The iterator-type must be an integral or pointer type.
5075         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5076             << DeclTy;
5077         IsCorrect = false;
5078         continue;
5079       }
5080       if (DeclTy.isConstant(Context)) {
5081         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5082         // The iterator-type must not be const qualified.
5083         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5084             << DeclTy;
5085         IsCorrect = false;
5086         continue;
5087       }
5088     }
5089 
5090     // Iterator declaration.
5091     assert(D.DeclIdent && "Identifier expected.");
5092     // Always try to create iterator declarator to avoid extra error messages
5093     // about unknown declarations use.
5094     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5095                                D.DeclIdent, DeclTy, TInfo, SC_None);
5096     VD->setImplicit();
5097     if (S) {
5098       // Check for conflicting previous declaration.
5099       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5100       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5101                             ForVisibleRedeclaration);
5102       Previous.suppressDiagnostics();
5103       LookupName(Previous, S);
5104 
5105       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5106                            /*AllowInlineNamespace=*/false);
5107       if (!Previous.empty()) {
5108         NamedDecl *Old = Previous.getRepresentativeDecl();
5109         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5110         Diag(Old->getLocation(), diag::note_previous_definition);
5111       } else {
5112         PushOnScopeChains(VD, S);
5113       }
5114     } else {
5115       CurContext->addDecl(VD);
5116     }
5117     Expr *Begin = D.Range.Begin;
5118     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5119       ExprResult BeginRes =
5120           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5121       Begin = BeginRes.get();
5122     }
5123     Expr *End = D.Range.End;
5124     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5125       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5126       End = EndRes.get();
5127     }
5128     Expr *Step = D.Range.Step;
5129     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5130       if (!Step->getType()->isIntegralType(Context)) {
5131         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5132             << Step << Step->getSourceRange();
5133         IsCorrect = false;
5134         continue;
5135       }
5136       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5137       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5138       // If the step expression of a range-specification equals zero, the
5139       // behavior is unspecified.
5140       if (Result && Result->isNullValue()) {
5141         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5142             << Step << Step->getSourceRange();
5143         IsCorrect = false;
5144         continue;
5145       }
5146     }
5147     if (!Begin || !End || !IsCorrect) {
5148       IsCorrect = false;
5149       continue;
5150     }
5151     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5152     IDElem.IteratorDecl = VD;
5153     IDElem.AssignmentLoc = D.AssignLoc;
5154     IDElem.Range.Begin = Begin;
5155     IDElem.Range.End = End;
5156     IDElem.Range.Step = Step;
5157     IDElem.ColonLoc = D.ColonLoc;
5158     IDElem.SecondColonLoc = D.SecColonLoc;
5159   }
5160   if (!IsCorrect) {
5161     // Invalidate all created iterator declarations if error is found.
5162     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5163       if (Decl *ID = D.IteratorDecl)
5164         ID->setInvalidDecl();
5165     }
5166     return ExprError();
5167   }
5168   SmallVector<OMPIteratorHelperData, 4> Helpers;
5169   if (!CurContext->isDependentContext()) {
5170     // Build number of ityeration for each iteration range.
5171     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5172     // ((Begini-Stepi-1-Endi) / -Stepi);
5173     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5174       // (Endi - Begini)
5175       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5176                                           D.Range.Begin);
5177       if(!Res.isUsable()) {
5178         IsCorrect = false;
5179         continue;
5180       }
5181       ExprResult St, St1;
5182       if (D.Range.Step) {
5183         St = D.Range.Step;
5184         // (Endi - Begini) + Stepi
5185         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5186         if (!Res.isUsable()) {
5187           IsCorrect = false;
5188           continue;
5189         }
5190         // (Endi - Begini) + Stepi - 1
5191         Res =
5192             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5193                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5194         if (!Res.isUsable()) {
5195           IsCorrect = false;
5196           continue;
5197         }
5198         // ((Endi - Begini) + Stepi - 1) / Stepi
5199         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5200         if (!Res.isUsable()) {
5201           IsCorrect = false;
5202           continue;
5203         }
5204         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5205         // (Begini - Endi)
5206         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5207                                              D.Range.Begin, D.Range.End);
5208         if (!Res1.isUsable()) {
5209           IsCorrect = false;
5210           continue;
5211         }
5212         // (Begini - Endi) - Stepi
5213         Res1 =
5214             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5215         if (!Res1.isUsable()) {
5216           IsCorrect = false;
5217           continue;
5218         }
5219         // (Begini - Endi) - Stepi - 1
5220         Res1 =
5221             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5222                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5223         if (!Res1.isUsable()) {
5224           IsCorrect = false;
5225           continue;
5226         }
5227         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5228         Res1 =
5229             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5230         if (!Res1.isUsable()) {
5231           IsCorrect = false;
5232           continue;
5233         }
5234         // Stepi > 0.
5235         ExprResult CmpRes =
5236             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5237                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5238         if (!CmpRes.isUsable()) {
5239           IsCorrect = false;
5240           continue;
5241         }
5242         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5243                                  Res.get(), Res1.get());
5244         if (!Res.isUsable()) {
5245           IsCorrect = false;
5246           continue;
5247         }
5248       }
5249       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5250       if (!Res.isUsable()) {
5251         IsCorrect = false;
5252         continue;
5253       }
5254 
5255       // Build counter update.
5256       // Build counter.
5257       auto *CounterVD =
5258           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5259                           D.IteratorDecl->getBeginLoc(), nullptr,
5260                           Res.get()->getType(), nullptr, SC_None);
5261       CounterVD->setImplicit();
5262       ExprResult RefRes =
5263           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5264                            D.IteratorDecl->getBeginLoc());
5265       // Build counter update.
5266       // I = Begini + counter * Stepi;
5267       ExprResult UpdateRes;
5268       if (D.Range.Step) {
5269         UpdateRes = CreateBuiltinBinOp(
5270             D.AssignmentLoc, BO_Mul,
5271             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5272       } else {
5273         UpdateRes = DefaultLvalueConversion(RefRes.get());
5274       }
5275       if (!UpdateRes.isUsable()) {
5276         IsCorrect = false;
5277         continue;
5278       }
5279       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5280                                      UpdateRes.get());
5281       if (!UpdateRes.isUsable()) {
5282         IsCorrect = false;
5283         continue;
5284       }
5285       ExprResult VDRes =
5286           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5287                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5288                            D.IteratorDecl->getBeginLoc());
5289       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5290                                      UpdateRes.get());
5291       if (!UpdateRes.isUsable()) {
5292         IsCorrect = false;
5293         continue;
5294       }
5295       UpdateRes =
5296           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5297       if (!UpdateRes.isUsable()) {
5298         IsCorrect = false;
5299         continue;
5300       }
5301       ExprResult CounterUpdateRes =
5302           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5303       if (!CounterUpdateRes.isUsable()) {
5304         IsCorrect = false;
5305         continue;
5306       }
5307       CounterUpdateRes =
5308           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5309       if (!CounterUpdateRes.isUsable()) {
5310         IsCorrect = false;
5311         continue;
5312       }
5313       OMPIteratorHelperData &HD = Helpers.emplace_back();
5314       HD.CounterVD = CounterVD;
5315       HD.Upper = Res.get();
5316       HD.Update = UpdateRes.get();
5317       HD.CounterUpdate = CounterUpdateRes.get();
5318     }
5319   } else {
5320     Helpers.assign(ID.size(), {});
5321   }
5322   if (!IsCorrect) {
5323     // Invalidate all created iterator declarations if error is found.
5324     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5325       if (Decl *ID = D.IteratorDecl)
5326         ID->setInvalidDecl();
5327     }
5328     return ExprError();
5329   }
5330   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5331                                  LLoc, RLoc, ID, Helpers);
5332 }
5333 
5334 ExprResult
5335 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5336                                       Expr *Idx, SourceLocation RLoc) {
5337   Expr *LHSExp = Base;
5338   Expr *RHSExp = Idx;
5339 
5340   ExprValueKind VK = VK_LValue;
5341   ExprObjectKind OK = OK_Ordinary;
5342 
5343   // Per C++ core issue 1213, the result is an xvalue if either operand is
5344   // a non-lvalue array, and an lvalue otherwise.
5345   if (getLangOpts().CPlusPlus11) {
5346     for (auto *Op : {LHSExp, RHSExp}) {
5347       Op = Op->IgnoreImplicit();
5348       if (Op->getType()->isArrayType() && !Op->isLValue())
5349         VK = VK_XValue;
5350     }
5351   }
5352 
5353   // Perform default conversions.
5354   if (!LHSExp->getType()->getAs<VectorType>()) {
5355     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5356     if (Result.isInvalid())
5357       return ExprError();
5358     LHSExp = Result.get();
5359   }
5360   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5361   if (Result.isInvalid())
5362     return ExprError();
5363   RHSExp = Result.get();
5364 
5365   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5366 
5367   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5368   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5369   // in the subscript position. As a result, we need to derive the array base
5370   // and index from the expression types.
5371   Expr *BaseExpr, *IndexExpr;
5372   QualType ResultType;
5373   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5374     BaseExpr = LHSExp;
5375     IndexExpr = RHSExp;
5376     ResultType = Context.DependentTy;
5377   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5378     BaseExpr = LHSExp;
5379     IndexExpr = RHSExp;
5380     ResultType = PTy->getPointeeType();
5381   } else if (const ObjCObjectPointerType *PTy =
5382                LHSTy->getAs<ObjCObjectPointerType>()) {
5383     BaseExpr = LHSExp;
5384     IndexExpr = RHSExp;
5385 
5386     // Use custom logic if this should be the pseudo-object subscript
5387     // expression.
5388     if (!LangOpts.isSubscriptPointerArithmetic())
5389       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5390                                           nullptr);
5391 
5392     ResultType = PTy->getPointeeType();
5393   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5394      // Handle the uncommon case of "123[Ptr]".
5395     BaseExpr = RHSExp;
5396     IndexExpr = LHSExp;
5397     ResultType = PTy->getPointeeType();
5398   } else if (const ObjCObjectPointerType *PTy =
5399                RHSTy->getAs<ObjCObjectPointerType>()) {
5400      // Handle the uncommon case of "123[Ptr]".
5401     BaseExpr = RHSExp;
5402     IndexExpr = LHSExp;
5403     ResultType = PTy->getPointeeType();
5404     if (!LangOpts.isSubscriptPointerArithmetic()) {
5405       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5406         << ResultType << BaseExpr->getSourceRange();
5407       return ExprError();
5408     }
5409   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5410     BaseExpr = LHSExp;    // vectors: V[123]
5411     IndexExpr = RHSExp;
5412     // We apply C++ DR1213 to vector subscripting too.
5413     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5414       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5415       if (Materialized.isInvalid())
5416         return ExprError();
5417       LHSExp = Materialized.get();
5418     }
5419     VK = LHSExp->getValueKind();
5420     if (VK != VK_RValue)
5421       OK = OK_VectorComponent;
5422 
5423     ResultType = VTy->getElementType();
5424     QualType BaseType = BaseExpr->getType();
5425     Qualifiers BaseQuals = BaseType.getQualifiers();
5426     Qualifiers MemberQuals = ResultType.getQualifiers();
5427     Qualifiers Combined = BaseQuals + MemberQuals;
5428     if (Combined != MemberQuals)
5429       ResultType = Context.getQualifiedType(ResultType, Combined);
5430   } else if (LHSTy->isArrayType()) {
5431     // If we see an array that wasn't promoted by
5432     // DefaultFunctionArrayLvalueConversion, it must be an array that
5433     // wasn't promoted because of the C90 rule that doesn't
5434     // allow promoting non-lvalue arrays.  Warn, then
5435     // force the promotion here.
5436     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5437         << LHSExp->getSourceRange();
5438     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5439                                CK_ArrayToPointerDecay).get();
5440     LHSTy = LHSExp->getType();
5441 
5442     BaseExpr = LHSExp;
5443     IndexExpr = RHSExp;
5444     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5445   } else if (RHSTy->isArrayType()) {
5446     // Same as previous, except for 123[f().a] case
5447     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5448         << RHSExp->getSourceRange();
5449     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5450                                CK_ArrayToPointerDecay).get();
5451     RHSTy = RHSExp->getType();
5452 
5453     BaseExpr = RHSExp;
5454     IndexExpr = LHSExp;
5455     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5456   } else {
5457     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5458        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5459   }
5460   // C99 6.5.2.1p1
5461   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5462     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5463                      << IndexExpr->getSourceRange());
5464 
5465   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5466        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5467          && !IndexExpr->isTypeDependent())
5468     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5469 
5470   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5471   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5472   // type. Note that Functions are not objects, and that (in C99 parlance)
5473   // incomplete types are not object types.
5474   if (ResultType->isFunctionType()) {
5475     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5476         << ResultType << BaseExpr->getSourceRange();
5477     return ExprError();
5478   }
5479 
5480   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5481     // GNU extension: subscripting on pointer to void
5482     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5483       << BaseExpr->getSourceRange();
5484 
5485     // C forbids expressions of unqualified void type from being l-values.
5486     // See IsCForbiddenLValueType.
5487     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5488   } else if (!ResultType->isDependentType() &&
5489              RequireCompleteSizedType(
5490                  LLoc, ResultType,
5491                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5492     return ExprError();
5493 
5494   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5495          !ResultType.isCForbiddenLValueType());
5496 
5497   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5498       FunctionScopes.size() > 1) {
5499     if (auto *TT =
5500             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5501       for (auto I = FunctionScopes.rbegin(),
5502                 E = std::prev(FunctionScopes.rend());
5503            I != E; ++I) {
5504         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5505         if (CSI == nullptr)
5506           break;
5507         DeclContext *DC = nullptr;
5508         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5509           DC = LSI->CallOperator;
5510         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5511           DC = CRSI->TheCapturedDecl;
5512         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5513           DC = BSI->TheDecl;
5514         if (DC) {
5515           if (DC->containsDecl(TT->getDecl()))
5516             break;
5517           captureVariablyModifiedType(
5518               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5519         }
5520       }
5521     }
5522   }
5523 
5524   return new (Context)
5525       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5526 }
5527 
5528 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5529                                   ParmVarDecl *Param) {
5530   if (Param->hasUnparsedDefaultArg()) {
5531     // If we've already cleared out the location for the default argument,
5532     // that means we're parsing it right now.
5533     if (!UnparsedDefaultArgLocs.count(Param)) {
5534       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5535       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5536       Param->setInvalidDecl();
5537       return true;
5538     }
5539 
5540     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5541         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5542     Diag(UnparsedDefaultArgLocs[Param],
5543          diag::note_default_argument_declared_here);
5544     return true;
5545   }
5546 
5547   if (Param->hasUninstantiatedDefaultArg() &&
5548       InstantiateDefaultArgument(CallLoc, FD, Param))
5549     return true;
5550 
5551   assert(Param->hasInit() && "default argument but no initializer?");
5552 
5553   // If the default expression creates temporaries, we need to
5554   // push them to the current stack of expression temporaries so they'll
5555   // be properly destroyed.
5556   // FIXME: We should really be rebuilding the default argument with new
5557   // bound temporaries; see the comment in PR5810.
5558   // We don't need to do that with block decls, though, because
5559   // blocks in default argument expression can never capture anything.
5560   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5561     // Set the "needs cleanups" bit regardless of whether there are
5562     // any explicit objects.
5563     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5564 
5565     // Append all the objects to the cleanup list.  Right now, this
5566     // should always be a no-op, because blocks in default argument
5567     // expressions should never be able to capture anything.
5568     assert(!Init->getNumObjects() &&
5569            "default argument expression has capturing blocks?");
5570   }
5571 
5572   // We already type-checked the argument, so we know it works.
5573   // Just mark all of the declarations in this potentially-evaluated expression
5574   // as being "referenced".
5575   EnterExpressionEvaluationContext EvalContext(
5576       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5577   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5578                                    /*SkipLocalVariables=*/true);
5579   return false;
5580 }
5581 
5582 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5583                                         FunctionDecl *FD, ParmVarDecl *Param) {
5584   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5585   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5586     return ExprError();
5587   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5588 }
5589 
5590 Sema::VariadicCallType
5591 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5592                           Expr *Fn) {
5593   if (Proto && Proto->isVariadic()) {
5594     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5595       return VariadicConstructor;
5596     else if (Fn && Fn->getType()->isBlockPointerType())
5597       return VariadicBlock;
5598     else if (FDecl) {
5599       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5600         if (Method->isInstance())
5601           return VariadicMethod;
5602     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5603       return VariadicMethod;
5604     return VariadicFunction;
5605   }
5606   return VariadicDoesNotApply;
5607 }
5608 
5609 namespace {
5610 class FunctionCallCCC final : public FunctionCallFilterCCC {
5611 public:
5612   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5613                   unsigned NumArgs, MemberExpr *ME)
5614       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5615         FunctionName(FuncName) {}
5616 
5617   bool ValidateCandidate(const TypoCorrection &candidate) override {
5618     if (!candidate.getCorrectionSpecifier() ||
5619         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5620       return false;
5621     }
5622 
5623     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5624   }
5625 
5626   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5627     return std::make_unique<FunctionCallCCC>(*this);
5628   }
5629 
5630 private:
5631   const IdentifierInfo *const FunctionName;
5632 };
5633 }
5634 
5635 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5636                                                FunctionDecl *FDecl,
5637                                                ArrayRef<Expr *> Args) {
5638   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5639   DeclarationName FuncName = FDecl->getDeclName();
5640   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5641 
5642   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5643   if (TypoCorrection Corrected = S.CorrectTypo(
5644           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5645           S.getScopeForContext(S.CurContext), nullptr, CCC,
5646           Sema::CTK_ErrorRecovery)) {
5647     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5648       if (Corrected.isOverloaded()) {
5649         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5650         OverloadCandidateSet::iterator Best;
5651         for (NamedDecl *CD : Corrected) {
5652           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5653             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5654                                    OCS);
5655         }
5656         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5657         case OR_Success:
5658           ND = Best->FoundDecl;
5659           Corrected.setCorrectionDecl(ND);
5660           break;
5661         default:
5662           break;
5663         }
5664       }
5665       ND = ND->getUnderlyingDecl();
5666       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5667         return Corrected;
5668     }
5669   }
5670   return TypoCorrection();
5671 }
5672 
5673 /// ConvertArgumentsForCall - Converts the arguments specified in
5674 /// Args/NumArgs to the parameter types of the function FDecl with
5675 /// function prototype Proto. Call is the call expression itself, and
5676 /// Fn is the function expression. For a C++ member function, this
5677 /// routine does not attempt to convert the object argument. Returns
5678 /// true if the call is ill-formed.
5679 bool
5680 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5681                               FunctionDecl *FDecl,
5682                               const FunctionProtoType *Proto,
5683                               ArrayRef<Expr *> Args,
5684                               SourceLocation RParenLoc,
5685                               bool IsExecConfig) {
5686   // Bail out early if calling a builtin with custom typechecking.
5687   if (FDecl)
5688     if (unsigned ID = FDecl->getBuiltinID())
5689       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5690         return false;
5691 
5692   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5693   // assignment, to the types of the corresponding parameter, ...
5694   unsigned NumParams = Proto->getNumParams();
5695   bool Invalid = false;
5696   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5697   unsigned FnKind = Fn->getType()->isBlockPointerType()
5698                        ? 1 /* block */
5699                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5700                                        : 0 /* function */);
5701 
5702   // If too few arguments are available (and we don't have default
5703   // arguments for the remaining parameters), don't make the call.
5704   if (Args.size() < NumParams) {
5705     if (Args.size() < MinArgs) {
5706       TypoCorrection TC;
5707       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5708         unsigned diag_id =
5709             MinArgs == NumParams && !Proto->isVariadic()
5710                 ? diag::err_typecheck_call_too_few_args_suggest
5711                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5712         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5713                                         << static_cast<unsigned>(Args.size())
5714                                         << TC.getCorrectionRange());
5715       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5716         Diag(RParenLoc,
5717              MinArgs == NumParams && !Proto->isVariadic()
5718                  ? diag::err_typecheck_call_too_few_args_one
5719                  : diag::err_typecheck_call_too_few_args_at_least_one)
5720             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5721       else
5722         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5723                             ? diag::err_typecheck_call_too_few_args
5724                             : diag::err_typecheck_call_too_few_args_at_least)
5725             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5726             << Fn->getSourceRange();
5727 
5728       // Emit the location of the prototype.
5729       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5730         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5731 
5732       return true;
5733     }
5734     // We reserve space for the default arguments when we create
5735     // the call expression, before calling ConvertArgumentsForCall.
5736     assert((Call->getNumArgs() == NumParams) &&
5737            "We should have reserved space for the default arguments before!");
5738   }
5739 
5740   // If too many are passed and not variadic, error on the extras and drop
5741   // them.
5742   if (Args.size() > NumParams) {
5743     if (!Proto->isVariadic()) {
5744       TypoCorrection TC;
5745       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5746         unsigned diag_id =
5747             MinArgs == NumParams && !Proto->isVariadic()
5748                 ? diag::err_typecheck_call_too_many_args_suggest
5749                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5750         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5751                                         << static_cast<unsigned>(Args.size())
5752                                         << TC.getCorrectionRange());
5753       } else if (NumParams == 1 && FDecl &&
5754                  FDecl->getParamDecl(0)->getDeclName())
5755         Diag(Args[NumParams]->getBeginLoc(),
5756              MinArgs == NumParams
5757                  ? diag::err_typecheck_call_too_many_args_one
5758                  : diag::err_typecheck_call_too_many_args_at_most_one)
5759             << FnKind << FDecl->getParamDecl(0)
5760             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5761             << SourceRange(Args[NumParams]->getBeginLoc(),
5762                            Args.back()->getEndLoc());
5763       else
5764         Diag(Args[NumParams]->getBeginLoc(),
5765              MinArgs == NumParams
5766                  ? diag::err_typecheck_call_too_many_args
5767                  : diag::err_typecheck_call_too_many_args_at_most)
5768             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5769             << Fn->getSourceRange()
5770             << SourceRange(Args[NumParams]->getBeginLoc(),
5771                            Args.back()->getEndLoc());
5772 
5773       // Emit the location of the prototype.
5774       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5775         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5776 
5777       // This deletes the extra arguments.
5778       Call->shrinkNumArgs(NumParams);
5779       return true;
5780     }
5781   }
5782   SmallVector<Expr *, 8> AllArgs;
5783   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5784 
5785   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5786                                    AllArgs, CallType);
5787   if (Invalid)
5788     return true;
5789   unsigned TotalNumArgs = AllArgs.size();
5790   for (unsigned i = 0; i < TotalNumArgs; ++i)
5791     Call->setArg(i, AllArgs[i]);
5792 
5793   return false;
5794 }
5795 
5796 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5797                                   const FunctionProtoType *Proto,
5798                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5799                                   SmallVectorImpl<Expr *> &AllArgs,
5800                                   VariadicCallType CallType, bool AllowExplicit,
5801                                   bool IsListInitialization) {
5802   unsigned NumParams = Proto->getNumParams();
5803   bool Invalid = false;
5804   size_t ArgIx = 0;
5805   // Continue to check argument types (even if we have too few/many args).
5806   for (unsigned i = FirstParam; i < NumParams; i++) {
5807     QualType ProtoArgType = Proto->getParamType(i);
5808 
5809     Expr *Arg;
5810     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5811     if (ArgIx < Args.size()) {
5812       Arg = Args[ArgIx++];
5813 
5814       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5815                               diag::err_call_incomplete_argument, Arg))
5816         return true;
5817 
5818       // Strip the unbridged-cast placeholder expression off, if applicable.
5819       bool CFAudited = false;
5820       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5821           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5822           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5823         Arg = stripARCUnbridgedCast(Arg);
5824       else if (getLangOpts().ObjCAutoRefCount &&
5825                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5826                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5827         CFAudited = true;
5828 
5829       if (Proto->getExtParameterInfo(i).isNoEscape())
5830         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5831           BE->getBlockDecl()->setDoesNotEscape();
5832 
5833       InitializedEntity Entity =
5834           Param ? InitializedEntity::InitializeParameter(Context, Param,
5835                                                          ProtoArgType)
5836                 : InitializedEntity::InitializeParameter(
5837                       Context, ProtoArgType, Proto->isParamConsumed(i));
5838 
5839       // Remember that parameter belongs to a CF audited API.
5840       if (CFAudited)
5841         Entity.setParameterCFAudited();
5842 
5843       ExprResult ArgE = PerformCopyInitialization(
5844           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5845       if (ArgE.isInvalid())
5846         return true;
5847 
5848       Arg = ArgE.getAs<Expr>();
5849     } else {
5850       assert(Param && "can't use default arguments without a known callee");
5851 
5852       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5853       if (ArgExpr.isInvalid())
5854         return true;
5855 
5856       Arg = ArgExpr.getAs<Expr>();
5857     }
5858 
5859     // Check for array bounds violations for each argument to the call. This
5860     // check only triggers warnings when the argument isn't a more complex Expr
5861     // with its own checking, such as a BinaryOperator.
5862     CheckArrayAccess(Arg);
5863 
5864     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5865     CheckStaticArrayArgument(CallLoc, Param, Arg);
5866 
5867     AllArgs.push_back(Arg);
5868   }
5869 
5870   // If this is a variadic call, handle args passed through "...".
5871   if (CallType != VariadicDoesNotApply) {
5872     // Assume that extern "C" functions with variadic arguments that
5873     // return __unknown_anytype aren't *really* variadic.
5874     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5875         FDecl->isExternC()) {
5876       for (Expr *A : Args.slice(ArgIx)) {
5877         QualType paramType; // ignored
5878         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5879         Invalid |= arg.isInvalid();
5880         AllArgs.push_back(arg.get());
5881       }
5882 
5883     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5884     } else {
5885       for (Expr *A : Args.slice(ArgIx)) {
5886         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5887         Invalid |= Arg.isInvalid();
5888         AllArgs.push_back(Arg.get());
5889       }
5890     }
5891 
5892     // Check for array bounds violations.
5893     for (Expr *A : Args.slice(ArgIx))
5894       CheckArrayAccess(A);
5895   }
5896   return Invalid;
5897 }
5898 
5899 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5900   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5901   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5902     TL = DTL.getOriginalLoc();
5903   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5904     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5905       << ATL.getLocalSourceRange();
5906 }
5907 
5908 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5909 /// array parameter, check that it is non-null, and that if it is formed by
5910 /// array-to-pointer decay, the underlying array is sufficiently large.
5911 ///
5912 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5913 /// array type derivation, then for each call to the function, the value of the
5914 /// corresponding actual argument shall provide access to the first element of
5915 /// an array with at least as many elements as specified by the size expression.
5916 void
5917 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5918                                ParmVarDecl *Param,
5919                                const Expr *ArgExpr) {
5920   // Static array parameters are not supported in C++.
5921   if (!Param || getLangOpts().CPlusPlus)
5922     return;
5923 
5924   QualType OrigTy = Param->getOriginalType();
5925 
5926   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5927   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5928     return;
5929 
5930   if (ArgExpr->isNullPointerConstant(Context,
5931                                      Expr::NPC_NeverValueDependent)) {
5932     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5933     DiagnoseCalleeStaticArrayParam(*this, Param);
5934     return;
5935   }
5936 
5937   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5938   if (!CAT)
5939     return;
5940 
5941   const ConstantArrayType *ArgCAT =
5942     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5943   if (!ArgCAT)
5944     return;
5945 
5946   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5947                                              ArgCAT->getElementType())) {
5948     if (ArgCAT->getSize().ult(CAT->getSize())) {
5949       Diag(CallLoc, diag::warn_static_array_too_small)
5950           << ArgExpr->getSourceRange()
5951           << (unsigned)ArgCAT->getSize().getZExtValue()
5952           << (unsigned)CAT->getSize().getZExtValue() << 0;
5953       DiagnoseCalleeStaticArrayParam(*this, Param);
5954     }
5955     return;
5956   }
5957 
5958   Optional<CharUnits> ArgSize =
5959       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5960   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5961   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5962     Diag(CallLoc, diag::warn_static_array_too_small)
5963         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5964         << (unsigned)ParmSize->getQuantity() << 1;
5965     DiagnoseCalleeStaticArrayParam(*this, Param);
5966   }
5967 }
5968 
5969 /// Given a function expression of unknown-any type, try to rebuild it
5970 /// to have a function type.
5971 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5972 
5973 /// Is the given type a placeholder that we need to lower out
5974 /// immediately during argument processing?
5975 static bool isPlaceholderToRemoveAsArg(QualType type) {
5976   // Placeholders are never sugared.
5977   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5978   if (!placeholder) return false;
5979 
5980   switch (placeholder->getKind()) {
5981   // Ignore all the non-placeholder types.
5982 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5983   case BuiltinType::Id:
5984 #include "clang/Basic/OpenCLImageTypes.def"
5985 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5986   case BuiltinType::Id:
5987 #include "clang/Basic/OpenCLExtensionTypes.def"
5988   // In practice we'll never use this, since all SVE types are sugared
5989   // via TypedefTypes rather than exposed directly as BuiltinTypes.
5990 #define SVE_TYPE(Name, Id, SingletonId) \
5991   case BuiltinType::Id:
5992 #include "clang/Basic/AArch64SVEACLETypes.def"
5993 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \
5994   case BuiltinType::Id:
5995 #include "clang/Basic/PPCTypes.def"
5996 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5997 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5998 #include "clang/AST/BuiltinTypes.def"
5999     return false;
6000 
6001   // We cannot lower out overload sets; they might validly be resolved
6002   // by the call machinery.
6003   case BuiltinType::Overload:
6004     return false;
6005 
6006   // Unbridged casts in ARC can be handled in some call positions and
6007   // should be left in place.
6008   case BuiltinType::ARCUnbridgedCast:
6009     return false;
6010 
6011   // Pseudo-objects should be converted as soon as possible.
6012   case BuiltinType::PseudoObject:
6013     return true;
6014 
6015   // The debugger mode could theoretically but currently does not try
6016   // to resolve unknown-typed arguments based on known parameter types.
6017   case BuiltinType::UnknownAny:
6018     return true;
6019 
6020   // These are always invalid as call arguments and should be reported.
6021   case BuiltinType::BoundMember:
6022   case BuiltinType::BuiltinFn:
6023   case BuiltinType::IncompleteMatrixIdx:
6024   case BuiltinType::OMPArraySection:
6025   case BuiltinType::OMPArrayShaping:
6026   case BuiltinType::OMPIterator:
6027     return true;
6028 
6029   }
6030   llvm_unreachable("bad builtin type kind");
6031 }
6032 
6033 /// Check an argument list for placeholders that we won't try to
6034 /// handle later.
6035 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6036   // Apply this processing to all the arguments at once instead of
6037   // dying at the first failure.
6038   bool hasInvalid = false;
6039   for (size_t i = 0, e = args.size(); i != e; i++) {
6040     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6041       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6042       if (result.isInvalid()) hasInvalid = true;
6043       else args[i] = result.get();
6044     }
6045   }
6046   return hasInvalid;
6047 }
6048 
6049 /// If a builtin function has a pointer argument with no explicit address
6050 /// space, then it should be able to accept a pointer to any address
6051 /// space as input.  In order to do this, we need to replace the
6052 /// standard builtin declaration with one that uses the same address space
6053 /// as the call.
6054 ///
6055 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6056 ///                  it does not contain any pointer arguments without
6057 ///                  an address space qualifer.  Otherwise the rewritten
6058 ///                  FunctionDecl is returned.
6059 /// TODO: Handle pointer return types.
6060 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6061                                                 FunctionDecl *FDecl,
6062                                                 MultiExprArg ArgExprs) {
6063 
6064   QualType DeclType = FDecl->getType();
6065   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6066 
6067   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6068       ArgExprs.size() < FT->getNumParams())
6069     return nullptr;
6070 
6071   bool NeedsNewDecl = false;
6072   unsigned i = 0;
6073   SmallVector<QualType, 8> OverloadParams;
6074 
6075   for (QualType ParamType : FT->param_types()) {
6076 
6077     // Convert array arguments to pointer to simplify type lookup.
6078     ExprResult ArgRes =
6079         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6080     if (ArgRes.isInvalid())
6081       return nullptr;
6082     Expr *Arg = ArgRes.get();
6083     QualType ArgType = Arg->getType();
6084     if (!ParamType->isPointerType() ||
6085         ParamType.hasAddressSpace() ||
6086         !ArgType->isPointerType() ||
6087         !ArgType->getPointeeType().hasAddressSpace()) {
6088       OverloadParams.push_back(ParamType);
6089       continue;
6090     }
6091 
6092     QualType PointeeType = ParamType->getPointeeType();
6093     if (PointeeType.hasAddressSpace())
6094       continue;
6095 
6096     NeedsNewDecl = true;
6097     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6098 
6099     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6100     OverloadParams.push_back(Context.getPointerType(PointeeType));
6101   }
6102 
6103   if (!NeedsNewDecl)
6104     return nullptr;
6105 
6106   FunctionProtoType::ExtProtoInfo EPI;
6107   EPI.Variadic = FT->isVariadic();
6108   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6109                                                 OverloadParams, EPI);
6110   DeclContext *Parent = FDecl->getParent();
6111   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6112                                                     FDecl->getLocation(),
6113                                                     FDecl->getLocation(),
6114                                                     FDecl->getIdentifier(),
6115                                                     OverloadTy,
6116                                                     /*TInfo=*/nullptr,
6117                                                     SC_Extern, false,
6118                                                     /*hasPrototype=*/true);
6119   SmallVector<ParmVarDecl*, 16> Params;
6120   FT = cast<FunctionProtoType>(OverloadTy);
6121   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6122     QualType ParamType = FT->getParamType(i);
6123     ParmVarDecl *Parm =
6124         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6125                                 SourceLocation(), nullptr, ParamType,
6126                                 /*TInfo=*/nullptr, SC_None, nullptr);
6127     Parm->setScopeInfo(0, i);
6128     Params.push_back(Parm);
6129   }
6130   OverloadDecl->setParams(Params);
6131   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6132   return OverloadDecl;
6133 }
6134 
6135 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6136                                     FunctionDecl *Callee,
6137                                     MultiExprArg ArgExprs) {
6138   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6139   // similar attributes) really don't like it when functions are called with an
6140   // invalid number of args.
6141   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6142                          /*PartialOverloading=*/false) &&
6143       !Callee->isVariadic())
6144     return;
6145   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6146     return;
6147 
6148   if (const EnableIfAttr *Attr =
6149           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6150     S.Diag(Fn->getBeginLoc(),
6151            isa<CXXMethodDecl>(Callee)
6152                ? diag::err_ovl_no_viable_member_function_in_call
6153                : diag::err_ovl_no_viable_function_in_call)
6154         << Callee << Callee->getSourceRange();
6155     S.Diag(Callee->getLocation(),
6156            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6157         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6158     return;
6159   }
6160 }
6161 
6162 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6163     const UnresolvedMemberExpr *const UME, Sema &S) {
6164 
6165   const auto GetFunctionLevelDCIfCXXClass =
6166       [](Sema &S) -> const CXXRecordDecl * {
6167     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6168     if (!DC || !DC->getParent())
6169       return nullptr;
6170 
6171     // If the call to some member function was made from within a member
6172     // function body 'M' return return 'M's parent.
6173     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6174       return MD->getParent()->getCanonicalDecl();
6175     // else the call was made from within a default member initializer of a
6176     // class, so return the class.
6177     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6178       return RD->getCanonicalDecl();
6179     return nullptr;
6180   };
6181   // If our DeclContext is neither a member function nor a class (in the
6182   // case of a lambda in a default member initializer), we can't have an
6183   // enclosing 'this'.
6184 
6185   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6186   if (!CurParentClass)
6187     return false;
6188 
6189   // The naming class for implicit member functions call is the class in which
6190   // name lookup starts.
6191   const CXXRecordDecl *const NamingClass =
6192       UME->getNamingClass()->getCanonicalDecl();
6193   assert(NamingClass && "Must have naming class even for implicit access");
6194 
6195   // If the unresolved member functions were found in a 'naming class' that is
6196   // related (either the same or derived from) to the class that contains the
6197   // member function that itself contained the implicit member access.
6198 
6199   return CurParentClass == NamingClass ||
6200          CurParentClass->isDerivedFrom(NamingClass);
6201 }
6202 
6203 static void
6204 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6205     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6206 
6207   if (!UME)
6208     return;
6209 
6210   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6211   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6212   // already been captured, or if this is an implicit member function call (if
6213   // it isn't, an attempt to capture 'this' should already have been made).
6214   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6215       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6216     return;
6217 
6218   // Check if the naming class in which the unresolved members were found is
6219   // related (same as or is a base of) to the enclosing class.
6220 
6221   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6222     return;
6223 
6224 
6225   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6226   // If the enclosing function is not dependent, then this lambda is
6227   // capture ready, so if we can capture this, do so.
6228   if (!EnclosingFunctionCtx->isDependentContext()) {
6229     // If the current lambda and all enclosing lambdas can capture 'this' -
6230     // then go ahead and capture 'this' (since our unresolved overload set
6231     // contains at least one non-static member function).
6232     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6233       S.CheckCXXThisCapture(CallLoc);
6234   } else if (S.CurContext->isDependentContext()) {
6235     // ... since this is an implicit member reference, that might potentially
6236     // involve a 'this' capture, mark 'this' for potential capture in
6237     // enclosing lambdas.
6238     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6239       CurLSI->addPotentialThisCapture(CallLoc);
6240   }
6241 }
6242 
6243 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6244                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6245                                Expr *ExecConfig) {
6246   ExprResult Call =
6247       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6248   if (Call.isInvalid())
6249     return Call;
6250 
6251   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6252   // language modes.
6253   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6254     if (ULE->hasExplicitTemplateArgs() &&
6255         ULE->decls_begin() == ULE->decls_end()) {
6256       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6257                                  ? diag::warn_cxx17_compat_adl_only_template_id
6258                                  : diag::ext_adl_only_template_id)
6259           << ULE->getName();
6260     }
6261   }
6262 
6263   if (LangOpts.OpenMP)
6264     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6265                            ExecConfig);
6266 
6267   return Call;
6268 }
6269 
6270 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6271 /// This provides the location of the left/right parens and a list of comma
6272 /// locations.
6273 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6274                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6275                                Expr *ExecConfig, bool IsExecConfig) {
6276   // Since this might be a postfix expression, get rid of ParenListExprs.
6277   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6278   if (Result.isInvalid()) return ExprError();
6279   Fn = Result.get();
6280 
6281   if (checkArgsForPlaceholders(*this, ArgExprs))
6282     return ExprError();
6283 
6284   if (getLangOpts().CPlusPlus) {
6285     // If this is a pseudo-destructor expression, build the call immediately.
6286     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6287       if (!ArgExprs.empty()) {
6288         // Pseudo-destructor calls should not have any arguments.
6289         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6290             << FixItHint::CreateRemoval(
6291                    SourceRange(ArgExprs.front()->getBeginLoc(),
6292                                ArgExprs.back()->getEndLoc()));
6293       }
6294 
6295       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6296                               VK_RValue, RParenLoc, CurFPFeatureOverrides());
6297     }
6298     if (Fn->getType() == Context.PseudoObjectTy) {
6299       ExprResult result = CheckPlaceholderExpr(Fn);
6300       if (result.isInvalid()) return ExprError();
6301       Fn = result.get();
6302     }
6303 
6304     // Determine whether this is a dependent call inside a C++ template,
6305     // in which case we won't do any semantic analysis now.
6306     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6307       if (ExecConfig) {
6308         return CUDAKernelCallExpr::Create(
6309             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6310             Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides());
6311       } else {
6312 
6313         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6314             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6315             Fn->getBeginLoc());
6316 
6317         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6318                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6319       }
6320     }
6321 
6322     // Determine whether this is a call to an object (C++ [over.call.object]).
6323     if (Fn->getType()->isRecordType())
6324       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6325                                           RParenLoc);
6326 
6327     if (Fn->getType() == Context.UnknownAnyTy) {
6328       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6329       if (result.isInvalid()) return ExprError();
6330       Fn = result.get();
6331     }
6332 
6333     if (Fn->getType() == Context.BoundMemberTy) {
6334       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6335                                        RParenLoc);
6336     }
6337   }
6338 
6339   // Check for overloaded calls.  This can happen even in C due to extensions.
6340   if (Fn->getType() == Context.OverloadTy) {
6341     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6342 
6343     // We aren't supposed to apply this logic if there's an '&' involved.
6344     if (!find.HasFormOfMemberPointer) {
6345       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6346         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6347                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6348       OverloadExpr *ovl = find.Expression;
6349       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6350         return BuildOverloadedCallExpr(
6351             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6352             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6353       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6354                                        RParenLoc);
6355     }
6356   }
6357 
6358   // If we're directly calling a function, get the appropriate declaration.
6359   if (Fn->getType() == Context.UnknownAnyTy) {
6360     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6361     if (result.isInvalid()) return ExprError();
6362     Fn = result.get();
6363   }
6364 
6365   Expr *NakedFn = Fn->IgnoreParens();
6366 
6367   bool CallingNDeclIndirectly = false;
6368   NamedDecl *NDecl = nullptr;
6369   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6370     if (UnOp->getOpcode() == UO_AddrOf) {
6371       CallingNDeclIndirectly = true;
6372       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6373     }
6374   }
6375 
6376   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6377     NDecl = DRE->getDecl();
6378 
6379     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6380     if (FDecl && FDecl->getBuiltinID()) {
6381       // Rewrite the function decl for this builtin by replacing parameters
6382       // with no explicit address space with the address space of the arguments
6383       // in ArgExprs.
6384       if ((FDecl =
6385                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6386         NDecl = FDecl;
6387         Fn = DeclRefExpr::Create(
6388             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6389             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6390             nullptr, DRE->isNonOdrUse());
6391       }
6392     }
6393   } else if (isa<MemberExpr>(NakedFn))
6394     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6395 
6396   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6397     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6398                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6399       return ExprError();
6400 
6401     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6402       return ExprError();
6403 
6404     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6405   }
6406 
6407   if (Context.isDependenceAllowed() &&
6408       (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6409     assert(!getLangOpts().CPlusPlus);
6410     assert((Fn->containsErrors() ||
6411             llvm::any_of(ArgExprs,
6412                          [](clang::Expr *E) { return E->containsErrors(); })) &&
6413            "should only occur in error-recovery path.");
6414     QualType ReturnType =
6415         llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6416             ? dyn_cast<FunctionDecl>(NDecl)->getCallResultType()
6417             : Context.DependentTy;
6418     return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6419                             Expr::getValueKindForType(ReturnType), RParenLoc,
6420                             CurFPFeatureOverrides());
6421   }
6422   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6423                                ExecConfig, IsExecConfig);
6424 }
6425 
6426 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6427 ///
6428 /// __builtin_astype( value, dst type )
6429 ///
6430 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6431                                  SourceLocation BuiltinLoc,
6432                                  SourceLocation RParenLoc) {
6433   ExprValueKind VK = VK_RValue;
6434   ExprObjectKind OK = OK_Ordinary;
6435   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6436   QualType SrcTy = E->getType();
6437   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6438     return ExprError(Diag(BuiltinLoc,
6439                           diag::err_invalid_astype_of_different_size)
6440                      << DstTy
6441                      << SrcTy
6442                      << E->getSourceRange());
6443   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6444 }
6445 
6446 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6447 /// provided arguments.
6448 ///
6449 /// __builtin_convertvector( value, dst type )
6450 ///
6451 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6452                                         SourceLocation BuiltinLoc,
6453                                         SourceLocation RParenLoc) {
6454   TypeSourceInfo *TInfo;
6455   GetTypeFromParser(ParsedDestTy, &TInfo);
6456   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6457 }
6458 
6459 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6460 /// i.e. an expression not of \p OverloadTy.  The expression should
6461 /// unary-convert to an expression of function-pointer or
6462 /// block-pointer type.
6463 ///
6464 /// \param NDecl the declaration being called, if available
6465 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6466                                        SourceLocation LParenLoc,
6467                                        ArrayRef<Expr *> Args,
6468                                        SourceLocation RParenLoc, Expr *Config,
6469                                        bool IsExecConfig, ADLCallKind UsesADL) {
6470   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6471   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6472 
6473   // Functions with 'interrupt' attribute cannot be called directly.
6474   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6475     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6476     return ExprError();
6477   }
6478 
6479   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6480   // so there's some risk when calling out to non-interrupt handler functions
6481   // that the callee might not preserve them. This is easy to diagnose here,
6482   // but can be very challenging to debug.
6483   if (auto *Caller = getCurFunctionDecl())
6484     if (Caller->hasAttr<ARMInterruptAttr>()) {
6485       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6486       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6487         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6488     }
6489 
6490   // Promote the function operand.
6491   // We special-case function promotion here because we only allow promoting
6492   // builtin functions to function pointers in the callee of a call.
6493   ExprResult Result;
6494   QualType ResultTy;
6495   if (BuiltinID &&
6496       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6497     // Extract the return type from the (builtin) function pointer type.
6498     // FIXME Several builtins still have setType in
6499     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6500     // Builtins.def to ensure they are correct before removing setType calls.
6501     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6502     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6503     ResultTy = FDecl->getCallResultType();
6504   } else {
6505     Result = CallExprUnaryConversions(Fn);
6506     ResultTy = Context.BoolTy;
6507   }
6508   if (Result.isInvalid())
6509     return ExprError();
6510   Fn = Result.get();
6511 
6512   // Check for a valid function type, but only if it is not a builtin which
6513   // requires custom type checking. These will be handled by
6514   // CheckBuiltinFunctionCall below just after creation of the call expression.
6515   const FunctionType *FuncT = nullptr;
6516   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6517   retry:
6518     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6519       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6520       // have type pointer to function".
6521       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6522       if (!FuncT)
6523         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6524                          << Fn->getType() << Fn->getSourceRange());
6525     } else if (const BlockPointerType *BPT =
6526                    Fn->getType()->getAs<BlockPointerType>()) {
6527       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6528     } else {
6529       // Handle calls to expressions of unknown-any type.
6530       if (Fn->getType() == Context.UnknownAnyTy) {
6531         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6532         if (rewrite.isInvalid())
6533           return ExprError();
6534         Fn = rewrite.get();
6535         goto retry;
6536       }
6537 
6538       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6539                        << Fn->getType() << Fn->getSourceRange());
6540     }
6541   }
6542 
6543   // Get the number of parameters in the function prototype, if any.
6544   // We will allocate space for max(Args.size(), NumParams) arguments
6545   // in the call expression.
6546   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6547   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6548 
6549   CallExpr *TheCall;
6550   if (Config) {
6551     assert(UsesADL == ADLCallKind::NotADL &&
6552            "CUDAKernelCallExpr should not use ADL");
6553     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6554                                          Args, ResultTy, VK_RValue, RParenLoc,
6555                                          CurFPFeatureOverrides(), NumParams);
6556   } else {
6557     TheCall =
6558         CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6559                          CurFPFeatureOverrides(), NumParams, UsesADL);
6560   }
6561 
6562   if (!Context.isDependenceAllowed()) {
6563     // Forget about the nulled arguments since typo correction
6564     // do not handle them well.
6565     TheCall->shrinkNumArgs(Args.size());
6566     // C cannot always handle TypoExpr nodes in builtin calls and direct
6567     // function calls as their argument checking don't necessarily handle
6568     // dependent types properly, so make sure any TypoExprs have been
6569     // dealt with.
6570     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6571     if (!Result.isUsable()) return ExprError();
6572     CallExpr *TheOldCall = TheCall;
6573     TheCall = dyn_cast<CallExpr>(Result.get());
6574     bool CorrectedTypos = TheCall != TheOldCall;
6575     if (!TheCall) return Result;
6576     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6577 
6578     // A new call expression node was created if some typos were corrected.
6579     // However it may not have been constructed with enough storage. In this
6580     // case, rebuild the node with enough storage. The waste of space is
6581     // immaterial since this only happens when some typos were corrected.
6582     if (CorrectedTypos && Args.size() < NumParams) {
6583       if (Config)
6584         TheCall = CUDAKernelCallExpr::Create(
6585             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6586             RParenLoc, CurFPFeatureOverrides(), NumParams);
6587       else
6588         TheCall =
6589             CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6590                              CurFPFeatureOverrides(), NumParams, UsesADL);
6591     }
6592     // We can now handle the nulled arguments for the default arguments.
6593     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6594   }
6595 
6596   // Bail out early if calling a builtin with custom type checking.
6597   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6598     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6599 
6600   if (getLangOpts().CUDA) {
6601     if (Config) {
6602       // CUDA: Kernel calls must be to global functions
6603       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6604         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6605             << FDecl << Fn->getSourceRange());
6606 
6607       // CUDA: Kernel function must have 'void' return type
6608       if (!FuncT->getReturnType()->isVoidType() &&
6609           !FuncT->getReturnType()->getAs<AutoType>() &&
6610           !FuncT->getReturnType()->isInstantiationDependentType())
6611         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6612             << Fn->getType() << Fn->getSourceRange());
6613     } else {
6614       // CUDA: Calls to global functions must be configured
6615       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6616         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6617             << FDecl << Fn->getSourceRange());
6618     }
6619   }
6620 
6621   // Check for a valid return type
6622   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6623                           FDecl))
6624     return ExprError();
6625 
6626   // We know the result type of the call, set it.
6627   TheCall->setType(FuncT->getCallResultType(Context));
6628   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6629 
6630   if (Proto) {
6631     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6632                                 IsExecConfig))
6633       return ExprError();
6634   } else {
6635     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6636 
6637     if (FDecl) {
6638       // Check if we have too few/too many template arguments, based
6639       // on our knowledge of the function definition.
6640       const FunctionDecl *Def = nullptr;
6641       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6642         Proto = Def->getType()->getAs<FunctionProtoType>();
6643        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6644           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6645           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6646       }
6647 
6648       // If the function we're calling isn't a function prototype, but we have
6649       // a function prototype from a prior declaratiom, use that prototype.
6650       if (!FDecl->hasPrototype())
6651         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6652     }
6653 
6654     // Promote the arguments (C99 6.5.2.2p6).
6655     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6656       Expr *Arg = Args[i];
6657 
6658       if (Proto && i < Proto->getNumParams()) {
6659         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6660             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6661         ExprResult ArgE =
6662             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6663         if (ArgE.isInvalid())
6664           return true;
6665 
6666         Arg = ArgE.getAs<Expr>();
6667 
6668       } else {
6669         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6670 
6671         if (ArgE.isInvalid())
6672           return true;
6673 
6674         Arg = ArgE.getAs<Expr>();
6675       }
6676 
6677       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6678                               diag::err_call_incomplete_argument, Arg))
6679         return ExprError();
6680 
6681       TheCall->setArg(i, Arg);
6682     }
6683   }
6684 
6685   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6686     if (!Method->isStatic())
6687       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6688         << Fn->getSourceRange());
6689 
6690   // Check for sentinels
6691   if (NDecl)
6692     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6693 
6694   // Warn for unions passing across security boundary (CMSE).
6695   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6696     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6697       if (const auto *RT =
6698               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6699         if (RT->getDecl()->isOrContainsUnion())
6700           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6701               << 0 << i;
6702       }
6703     }
6704   }
6705 
6706   // Do special checking on direct calls to functions.
6707   if (FDecl) {
6708     if (CheckFunctionCall(FDecl, TheCall, Proto))
6709       return ExprError();
6710 
6711     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6712 
6713     if (BuiltinID)
6714       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6715   } else if (NDecl) {
6716     if (CheckPointerCall(NDecl, TheCall, Proto))
6717       return ExprError();
6718   } else {
6719     if (CheckOtherCall(TheCall, Proto))
6720       return ExprError();
6721   }
6722 
6723   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6724 }
6725 
6726 ExprResult
6727 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6728                            SourceLocation RParenLoc, Expr *InitExpr) {
6729   assert(Ty && "ActOnCompoundLiteral(): missing type");
6730   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6731 
6732   TypeSourceInfo *TInfo;
6733   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6734   if (!TInfo)
6735     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6736 
6737   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6738 }
6739 
6740 ExprResult
6741 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6742                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6743   QualType literalType = TInfo->getType();
6744 
6745   if (literalType->isArrayType()) {
6746     if (RequireCompleteSizedType(
6747             LParenLoc, Context.getBaseElementType(literalType),
6748             diag::err_array_incomplete_or_sizeless_type,
6749             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6750       return ExprError();
6751     if (literalType->isVariableArrayType())
6752       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6753         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6754   } else if (!literalType->isDependentType() &&
6755              RequireCompleteType(LParenLoc, literalType,
6756                diag::err_typecheck_decl_incomplete_type,
6757                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6758     return ExprError();
6759 
6760   InitializedEntity Entity
6761     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6762   InitializationKind Kind
6763     = InitializationKind::CreateCStyleCast(LParenLoc,
6764                                            SourceRange(LParenLoc, RParenLoc),
6765                                            /*InitList=*/true);
6766   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6767   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6768                                       &literalType);
6769   if (Result.isInvalid())
6770     return ExprError();
6771   LiteralExpr = Result.get();
6772 
6773   bool isFileScope = !CurContext->isFunctionOrMethod();
6774 
6775   // In C, compound literals are l-values for some reason.
6776   // For GCC compatibility, in C++, file-scope array compound literals with
6777   // constant initializers are also l-values, and compound literals are
6778   // otherwise prvalues.
6779   //
6780   // (GCC also treats C++ list-initialized file-scope array prvalues with
6781   // constant initializers as l-values, but that's non-conforming, so we don't
6782   // follow it there.)
6783   //
6784   // FIXME: It would be better to handle the lvalue cases as materializing and
6785   // lifetime-extending a temporary object, but our materialized temporaries
6786   // representation only supports lifetime extension from a variable, not "out
6787   // of thin air".
6788   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6789   // is bound to the result of applying array-to-pointer decay to the compound
6790   // literal.
6791   // FIXME: GCC supports compound literals of reference type, which should
6792   // obviously have a value kind derived from the kind of reference involved.
6793   ExprValueKind VK =
6794       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6795           ? VK_RValue
6796           : VK_LValue;
6797 
6798   if (isFileScope)
6799     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6800       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6801         Expr *Init = ILE->getInit(i);
6802         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6803       }
6804 
6805   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6806                                               VK, LiteralExpr, isFileScope);
6807   if (isFileScope) {
6808     if (!LiteralExpr->isTypeDependent() &&
6809         !LiteralExpr->isValueDependent() &&
6810         !literalType->isDependentType()) // C99 6.5.2.5p3
6811       if (CheckForConstantInitializer(LiteralExpr, literalType))
6812         return ExprError();
6813   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6814              literalType.getAddressSpace() != LangAS::Default) {
6815     // Embedded-C extensions to C99 6.5.2.5:
6816     //   "If the compound literal occurs inside the body of a function, the
6817     //   type name shall not be qualified by an address-space qualifier."
6818     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6819       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6820     return ExprError();
6821   }
6822 
6823   if (!isFileScope && !getLangOpts().CPlusPlus) {
6824     // Compound literals that have automatic storage duration are destroyed at
6825     // the end of the scope in C; in C++, they're just temporaries.
6826 
6827     // Emit diagnostics if it is or contains a C union type that is non-trivial
6828     // to destruct.
6829     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6830       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6831                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6832 
6833     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6834     if (literalType.isDestructedType()) {
6835       Cleanup.setExprNeedsCleanups(true);
6836       ExprCleanupObjects.push_back(E);
6837       getCurFunction()->setHasBranchProtectedScope();
6838     }
6839   }
6840 
6841   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6842       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6843     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6844                                        E->getInitializer()->getExprLoc());
6845 
6846   return MaybeBindToTemporary(E);
6847 }
6848 
6849 ExprResult
6850 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6851                     SourceLocation RBraceLoc) {
6852   // Only produce each kind of designated initialization diagnostic once.
6853   SourceLocation FirstDesignator;
6854   bool DiagnosedArrayDesignator = false;
6855   bool DiagnosedNestedDesignator = false;
6856   bool DiagnosedMixedDesignator = false;
6857 
6858   // Check that any designated initializers are syntactically valid in the
6859   // current language mode.
6860   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6861     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6862       if (FirstDesignator.isInvalid())
6863         FirstDesignator = DIE->getBeginLoc();
6864 
6865       if (!getLangOpts().CPlusPlus)
6866         break;
6867 
6868       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6869         DiagnosedNestedDesignator = true;
6870         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6871           << DIE->getDesignatorsSourceRange();
6872       }
6873 
6874       for (auto &Desig : DIE->designators()) {
6875         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6876           DiagnosedArrayDesignator = true;
6877           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6878             << Desig.getSourceRange();
6879         }
6880       }
6881 
6882       if (!DiagnosedMixedDesignator &&
6883           !isa<DesignatedInitExpr>(InitArgList[0])) {
6884         DiagnosedMixedDesignator = true;
6885         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6886           << DIE->getSourceRange();
6887         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6888           << InitArgList[0]->getSourceRange();
6889       }
6890     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6891                isa<DesignatedInitExpr>(InitArgList[0])) {
6892       DiagnosedMixedDesignator = true;
6893       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6894       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6895         << DIE->getSourceRange();
6896       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6897         << InitArgList[I]->getSourceRange();
6898     }
6899   }
6900 
6901   if (FirstDesignator.isValid()) {
6902     // Only diagnose designated initiaization as a C++20 extension if we didn't
6903     // already diagnose use of (non-C++20) C99 designator syntax.
6904     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6905         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6906       Diag(FirstDesignator, getLangOpts().CPlusPlus20
6907                                 ? diag::warn_cxx17_compat_designated_init
6908                                 : diag::ext_cxx_designated_init);
6909     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6910       Diag(FirstDesignator, diag::ext_designated_init);
6911     }
6912   }
6913 
6914   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6915 }
6916 
6917 ExprResult
6918 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6919                     SourceLocation RBraceLoc) {
6920   // Semantic analysis for initializers is done by ActOnDeclarator() and
6921   // CheckInitializer() - it requires knowledge of the object being initialized.
6922 
6923   // Immediately handle non-overload placeholders.  Overloads can be
6924   // resolved contextually, but everything else here can't.
6925   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6926     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6927       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6928 
6929       // Ignore failures; dropping the entire initializer list because
6930       // of one failure would be terrible for indexing/etc.
6931       if (result.isInvalid()) continue;
6932 
6933       InitArgList[I] = result.get();
6934     }
6935   }
6936 
6937   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6938                                                RBraceLoc);
6939   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6940   return E;
6941 }
6942 
6943 /// Do an explicit extend of the given block pointer if we're in ARC.
6944 void Sema::maybeExtendBlockObject(ExprResult &E) {
6945   assert(E.get()->getType()->isBlockPointerType());
6946   assert(E.get()->isRValue());
6947 
6948   // Only do this in an r-value context.
6949   if (!getLangOpts().ObjCAutoRefCount) return;
6950 
6951   E = ImplicitCastExpr::Create(
6952       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
6953       /*base path*/ nullptr, VK_RValue, FPOptionsOverride());
6954   Cleanup.setExprNeedsCleanups(true);
6955 }
6956 
6957 /// Prepare a conversion of the given expression to an ObjC object
6958 /// pointer type.
6959 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6960   QualType type = E.get()->getType();
6961   if (type->isObjCObjectPointerType()) {
6962     return CK_BitCast;
6963   } else if (type->isBlockPointerType()) {
6964     maybeExtendBlockObject(E);
6965     return CK_BlockPointerToObjCPointerCast;
6966   } else {
6967     assert(type->isPointerType());
6968     return CK_CPointerToObjCPointerCast;
6969   }
6970 }
6971 
6972 /// Prepares for a scalar cast, performing all the necessary stages
6973 /// except the final cast and returning the kind required.
6974 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6975   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6976   // Also, callers should have filtered out the invalid cases with
6977   // pointers.  Everything else should be possible.
6978 
6979   QualType SrcTy = Src.get()->getType();
6980   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6981     return CK_NoOp;
6982 
6983   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6984   case Type::STK_MemberPointer:
6985     llvm_unreachable("member pointer type in C");
6986 
6987   case Type::STK_CPointer:
6988   case Type::STK_BlockPointer:
6989   case Type::STK_ObjCObjectPointer:
6990     switch (DestTy->getScalarTypeKind()) {
6991     case Type::STK_CPointer: {
6992       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6993       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6994       if (SrcAS != DestAS)
6995         return CK_AddressSpaceConversion;
6996       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6997         return CK_NoOp;
6998       return CK_BitCast;
6999     }
7000     case Type::STK_BlockPointer:
7001       return (SrcKind == Type::STK_BlockPointer
7002                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7003     case Type::STK_ObjCObjectPointer:
7004       if (SrcKind == Type::STK_ObjCObjectPointer)
7005         return CK_BitCast;
7006       if (SrcKind == Type::STK_CPointer)
7007         return CK_CPointerToObjCPointerCast;
7008       maybeExtendBlockObject(Src);
7009       return CK_BlockPointerToObjCPointerCast;
7010     case Type::STK_Bool:
7011       return CK_PointerToBoolean;
7012     case Type::STK_Integral:
7013       return CK_PointerToIntegral;
7014     case Type::STK_Floating:
7015     case Type::STK_FloatingComplex:
7016     case Type::STK_IntegralComplex:
7017     case Type::STK_MemberPointer:
7018     case Type::STK_FixedPoint:
7019       llvm_unreachable("illegal cast from pointer");
7020     }
7021     llvm_unreachable("Should have returned before this");
7022 
7023   case Type::STK_FixedPoint:
7024     switch (DestTy->getScalarTypeKind()) {
7025     case Type::STK_FixedPoint:
7026       return CK_FixedPointCast;
7027     case Type::STK_Bool:
7028       return CK_FixedPointToBoolean;
7029     case Type::STK_Integral:
7030       return CK_FixedPointToIntegral;
7031     case Type::STK_Floating:
7032       return CK_FixedPointToFloating;
7033     case Type::STK_IntegralComplex:
7034     case Type::STK_FloatingComplex:
7035       Diag(Src.get()->getExprLoc(),
7036            diag::err_unimplemented_conversion_with_fixed_point_type)
7037           << DestTy;
7038       return CK_IntegralCast;
7039     case Type::STK_CPointer:
7040     case Type::STK_ObjCObjectPointer:
7041     case Type::STK_BlockPointer:
7042     case Type::STK_MemberPointer:
7043       llvm_unreachable("illegal cast to pointer type");
7044     }
7045     llvm_unreachable("Should have returned before this");
7046 
7047   case Type::STK_Bool: // casting from bool is like casting from an integer
7048   case Type::STK_Integral:
7049     switch (DestTy->getScalarTypeKind()) {
7050     case Type::STK_CPointer:
7051     case Type::STK_ObjCObjectPointer:
7052     case Type::STK_BlockPointer:
7053       if (Src.get()->isNullPointerConstant(Context,
7054                                            Expr::NPC_ValueDependentIsNull))
7055         return CK_NullToPointer;
7056       return CK_IntegralToPointer;
7057     case Type::STK_Bool:
7058       return CK_IntegralToBoolean;
7059     case Type::STK_Integral:
7060       return CK_IntegralCast;
7061     case Type::STK_Floating:
7062       return CK_IntegralToFloating;
7063     case Type::STK_IntegralComplex:
7064       Src = ImpCastExprToType(Src.get(),
7065                       DestTy->castAs<ComplexType>()->getElementType(),
7066                       CK_IntegralCast);
7067       return CK_IntegralRealToComplex;
7068     case Type::STK_FloatingComplex:
7069       Src = ImpCastExprToType(Src.get(),
7070                       DestTy->castAs<ComplexType>()->getElementType(),
7071                       CK_IntegralToFloating);
7072       return CK_FloatingRealToComplex;
7073     case Type::STK_MemberPointer:
7074       llvm_unreachable("member pointer type in C");
7075     case Type::STK_FixedPoint:
7076       return CK_IntegralToFixedPoint;
7077     }
7078     llvm_unreachable("Should have returned before this");
7079 
7080   case Type::STK_Floating:
7081     switch (DestTy->getScalarTypeKind()) {
7082     case Type::STK_Floating:
7083       return CK_FloatingCast;
7084     case Type::STK_Bool:
7085       return CK_FloatingToBoolean;
7086     case Type::STK_Integral:
7087       return CK_FloatingToIntegral;
7088     case Type::STK_FloatingComplex:
7089       Src = ImpCastExprToType(Src.get(),
7090                               DestTy->castAs<ComplexType>()->getElementType(),
7091                               CK_FloatingCast);
7092       return CK_FloatingRealToComplex;
7093     case Type::STK_IntegralComplex:
7094       Src = ImpCastExprToType(Src.get(),
7095                               DestTy->castAs<ComplexType>()->getElementType(),
7096                               CK_FloatingToIntegral);
7097       return CK_IntegralRealToComplex;
7098     case Type::STK_CPointer:
7099     case Type::STK_ObjCObjectPointer:
7100     case Type::STK_BlockPointer:
7101       llvm_unreachable("valid float->pointer cast?");
7102     case Type::STK_MemberPointer:
7103       llvm_unreachable("member pointer type in C");
7104     case Type::STK_FixedPoint:
7105       return CK_FloatingToFixedPoint;
7106     }
7107     llvm_unreachable("Should have returned before this");
7108 
7109   case Type::STK_FloatingComplex:
7110     switch (DestTy->getScalarTypeKind()) {
7111     case Type::STK_FloatingComplex:
7112       return CK_FloatingComplexCast;
7113     case Type::STK_IntegralComplex:
7114       return CK_FloatingComplexToIntegralComplex;
7115     case Type::STK_Floating: {
7116       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7117       if (Context.hasSameType(ET, DestTy))
7118         return CK_FloatingComplexToReal;
7119       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7120       return CK_FloatingCast;
7121     }
7122     case Type::STK_Bool:
7123       return CK_FloatingComplexToBoolean;
7124     case Type::STK_Integral:
7125       Src = ImpCastExprToType(Src.get(),
7126                               SrcTy->castAs<ComplexType>()->getElementType(),
7127                               CK_FloatingComplexToReal);
7128       return CK_FloatingToIntegral;
7129     case Type::STK_CPointer:
7130     case Type::STK_ObjCObjectPointer:
7131     case Type::STK_BlockPointer:
7132       llvm_unreachable("valid complex float->pointer cast?");
7133     case Type::STK_MemberPointer:
7134       llvm_unreachable("member pointer type in C");
7135     case Type::STK_FixedPoint:
7136       Diag(Src.get()->getExprLoc(),
7137            diag::err_unimplemented_conversion_with_fixed_point_type)
7138           << SrcTy;
7139       return CK_IntegralCast;
7140     }
7141     llvm_unreachable("Should have returned before this");
7142 
7143   case Type::STK_IntegralComplex:
7144     switch (DestTy->getScalarTypeKind()) {
7145     case Type::STK_FloatingComplex:
7146       return CK_IntegralComplexToFloatingComplex;
7147     case Type::STK_IntegralComplex:
7148       return CK_IntegralComplexCast;
7149     case Type::STK_Integral: {
7150       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7151       if (Context.hasSameType(ET, DestTy))
7152         return CK_IntegralComplexToReal;
7153       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7154       return CK_IntegralCast;
7155     }
7156     case Type::STK_Bool:
7157       return CK_IntegralComplexToBoolean;
7158     case Type::STK_Floating:
7159       Src = ImpCastExprToType(Src.get(),
7160                               SrcTy->castAs<ComplexType>()->getElementType(),
7161                               CK_IntegralComplexToReal);
7162       return CK_IntegralToFloating;
7163     case Type::STK_CPointer:
7164     case Type::STK_ObjCObjectPointer:
7165     case Type::STK_BlockPointer:
7166       llvm_unreachable("valid complex int->pointer cast?");
7167     case Type::STK_MemberPointer:
7168       llvm_unreachable("member pointer type in C");
7169     case Type::STK_FixedPoint:
7170       Diag(Src.get()->getExprLoc(),
7171            diag::err_unimplemented_conversion_with_fixed_point_type)
7172           << SrcTy;
7173       return CK_IntegralCast;
7174     }
7175     llvm_unreachable("Should have returned before this");
7176   }
7177 
7178   llvm_unreachable("Unhandled scalar cast");
7179 }
7180 
7181 static bool breakDownVectorType(QualType type, uint64_t &len,
7182                                 QualType &eltType) {
7183   // Vectors are simple.
7184   if (const VectorType *vecType = type->getAs<VectorType>()) {
7185     len = vecType->getNumElements();
7186     eltType = vecType->getElementType();
7187     assert(eltType->isScalarType());
7188     return true;
7189   }
7190 
7191   // We allow lax conversion to and from non-vector types, but only if
7192   // they're real types (i.e. non-complex, non-pointer scalar types).
7193   if (!type->isRealType()) return false;
7194 
7195   len = 1;
7196   eltType = type;
7197   return true;
7198 }
7199 
7200 /// Are the two types lax-compatible vector types?  That is, given
7201 /// that one of them is a vector, do they have equal storage sizes,
7202 /// where the storage size is the number of elements times the element
7203 /// size?
7204 ///
7205 /// This will also return false if either of the types is neither a
7206 /// vector nor a real type.
7207 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7208   assert(destTy->isVectorType() || srcTy->isVectorType());
7209 
7210   // Disallow lax conversions between scalars and ExtVectors (these
7211   // conversions are allowed for other vector types because common headers
7212   // depend on them).  Most scalar OP ExtVector cases are handled by the
7213   // splat path anyway, which does what we want (convert, not bitcast).
7214   // What this rules out for ExtVectors is crazy things like char4*float.
7215   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7216   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7217 
7218   uint64_t srcLen, destLen;
7219   QualType srcEltTy, destEltTy;
7220   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7221   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7222 
7223   // ASTContext::getTypeSize will return the size rounded up to a
7224   // power of 2, so instead of using that, we need to use the raw
7225   // element size multiplied by the element count.
7226   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7227   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7228 
7229   return (srcLen * srcEltSize == destLen * destEltSize);
7230 }
7231 
7232 /// Is this a legal conversion between two types, one of which is
7233 /// known to be a vector type?
7234 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7235   assert(destTy->isVectorType() || srcTy->isVectorType());
7236 
7237   switch (Context.getLangOpts().getLaxVectorConversions()) {
7238   case LangOptions::LaxVectorConversionKind::None:
7239     return false;
7240 
7241   case LangOptions::LaxVectorConversionKind::Integer:
7242     if (!srcTy->isIntegralOrEnumerationType()) {
7243       auto *Vec = srcTy->getAs<VectorType>();
7244       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7245         return false;
7246     }
7247     if (!destTy->isIntegralOrEnumerationType()) {
7248       auto *Vec = destTy->getAs<VectorType>();
7249       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7250         return false;
7251     }
7252     // OK, integer (vector) -> integer (vector) bitcast.
7253     break;
7254 
7255     case LangOptions::LaxVectorConversionKind::All:
7256     break;
7257   }
7258 
7259   return areLaxCompatibleVectorTypes(srcTy, destTy);
7260 }
7261 
7262 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7263                            CastKind &Kind) {
7264   assert(VectorTy->isVectorType() && "Not a vector type!");
7265 
7266   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7267     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7268       return Diag(R.getBegin(),
7269                   Ty->isVectorType() ?
7270                   diag::err_invalid_conversion_between_vectors :
7271                   diag::err_invalid_conversion_between_vector_and_integer)
7272         << VectorTy << Ty << R;
7273   } else
7274     return Diag(R.getBegin(),
7275                 diag::err_invalid_conversion_between_vector_and_scalar)
7276       << VectorTy << Ty << R;
7277 
7278   Kind = CK_BitCast;
7279   return false;
7280 }
7281 
7282 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7283   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7284 
7285   if (DestElemTy == SplattedExpr->getType())
7286     return SplattedExpr;
7287 
7288   assert(DestElemTy->isFloatingType() ||
7289          DestElemTy->isIntegralOrEnumerationType());
7290 
7291   CastKind CK;
7292   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7293     // OpenCL requires that we convert `true` boolean expressions to -1, but
7294     // only when splatting vectors.
7295     if (DestElemTy->isFloatingType()) {
7296       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7297       // in two steps: boolean to signed integral, then to floating.
7298       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7299                                                  CK_BooleanToSignedIntegral);
7300       SplattedExpr = CastExprRes.get();
7301       CK = CK_IntegralToFloating;
7302     } else {
7303       CK = CK_BooleanToSignedIntegral;
7304     }
7305   } else {
7306     ExprResult CastExprRes = SplattedExpr;
7307     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7308     if (CastExprRes.isInvalid())
7309       return ExprError();
7310     SplattedExpr = CastExprRes.get();
7311   }
7312   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7313 }
7314 
7315 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7316                                     Expr *CastExpr, CastKind &Kind) {
7317   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7318 
7319   QualType SrcTy = CastExpr->getType();
7320 
7321   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7322   // an ExtVectorType.
7323   // In OpenCL, casts between vectors of different types are not allowed.
7324   // (See OpenCL 6.2).
7325   if (SrcTy->isVectorType()) {
7326     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7327         (getLangOpts().OpenCL &&
7328          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7329       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7330         << DestTy << SrcTy << R;
7331       return ExprError();
7332     }
7333     Kind = CK_BitCast;
7334     return CastExpr;
7335   }
7336 
7337   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7338   // conversion will take place first from scalar to elt type, and then
7339   // splat from elt type to vector.
7340   if (SrcTy->isPointerType())
7341     return Diag(R.getBegin(),
7342                 diag::err_invalid_conversion_between_vector_and_scalar)
7343       << DestTy << SrcTy << R;
7344 
7345   Kind = CK_VectorSplat;
7346   return prepareVectorSplat(DestTy, CastExpr);
7347 }
7348 
7349 ExprResult
7350 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7351                     Declarator &D, ParsedType &Ty,
7352                     SourceLocation RParenLoc, Expr *CastExpr) {
7353   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7354          "ActOnCastExpr(): missing type or expr");
7355 
7356   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7357   if (D.isInvalidType())
7358     return ExprError();
7359 
7360   if (getLangOpts().CPlusPlus) {
7361     // Check that there are no default arguments (C++ only).
7362     CheckExtraCXXDefaultArguments(D);
7363   } else {
7364     // Make sure any TypoExprs have been dealt with.
7365     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7366     if (!Res.isUsable())
7367       return ExprError();
7368     CastExpr = Res.get();
7369   }
7370 
7371   checkUnusedDeclAttributes(D);
7372 
7373   QualType castType = castTInfo->getType();
7374   Ty = CreateParsedType(castType, castTInfo);
7375 
7376   bool isVectorLiteral = false;
7377 
7378   // Check for an altivec or OpenCL literal,
7379   // i.e. all the elements are integer constants.
7380   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7381   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7382   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7383        && castType->isVectorType() && (PE || PLE)) {
7384     if (PLE && PLE->getNumExprs() == 0) {
7385       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7386       return ExprError();
7387     }
7388     if (PE || PLE->getNumExprs() == 1) {
7389       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7390       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7391         isVectorLiteral = true;
7392     }
7393     else
7394       isVectorLiteral = true;
7395   }
7396 
7397   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7398   // then handle it as such.
7399   if (isVectorLiteral)
7400     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7401 
7402   // If the Expr being casted is a ParenListExpr, handle it specially.
7403   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7404   // sequence of BinOp comma operators.
7405   if (isa<ParenListExpr>(CastExpr)) {
7406     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7407     if (Result.isInvalid()) return ExprError();
7408     CastExpr = Result.get();
7409   }
7410 
7411   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7412       !getSourceManager().isInSystemMacro(LParenLoc))
7413     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7414 
7415   CheckTollFreeBridgeCast(castType, CastExpr);
7416 
7417   CheckObjCBridgeRelatedCast(castType, CastExpr);
7418 
7419   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7420 
7421   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7422 }
7423 
7424 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7425                                     SourceLocation RParenLoc, Expr *E,
7426                                     TypeSourceInfo *TInfo) {
7427   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7428          "Expected paren or paren list expression");
7429 
7430   Expr **exprs;
7431   unsigned numExprs;
7432   Expr *subExpr;
7433   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7434   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7435     LiteralLParenLoc = PE->getLParenLoc();
7436     LiteralRParenLoc = PE->getRParenLoc();
7437     exprs = PE->getExprs();
7438     numExprs = PE->getNumExprs();
7439   } else { // isa<ParenExpr> by assertion at function entrance
7440     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7441     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7442     subExpr = cast<ParenExpr>(E)->getSubExpr();
7443     exprs = &subExpr;
7444     numExprs = 1;
7445   }
7446 
7447   QualType Ty = TInfo->getType();
7448   assert(Ty->isVectorType() && "Expected vector type");
7449 
7450   SmallVector<Expr *, 8> initExprs;
7451   const VectorType *VTy = Ty->castAs<VectorType>();
7452   unsigned numElems = VTy->getNumElements();
7453 
7454   // '(...)' form of vector initialization in AltiVec: the number of
7455   // initializers must be one or must match the size of the vector.
7456   // If a single value is specified in the initializer then it will be
7457   // replicated to all the components of the vector
7458   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7459     // The number of initializers must be one or must match the size of the
7460     // vector. If a single value is specified in the initializer then it will
7461     // be replicated to all the components of the vector
7462     if (numExprs == 1) {
7463       QualType ElemTy = VTy->getElementType();
7464       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7465       if (Literal.isInvalid())
7466         return ExprError();
7467       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7468                                   PrepareScalarCast(Literal, ElemTy));
7469       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7470     }
7471     else if (numExprs < numElems) {
7472       Diag(E->getExprLoc(),
7473            diag::err_incorrect_number_of_vector_initializers);
7474       return ExprError();
7475     }
7476     else
7477       initExprs.append(exprs, exprs + numExprs);
7478   }
7479   else {
7480     // For OpenCL, when the number of initializers is a single value,
7481     // it will be replicated to all components of the vector.
7482     if (getLangOpts().OpenCL &&
7483         VTy->getVectorKind() == VectorType::GenericVector &&
7484         numExprs == 1) {
7485         QualType ElemTy = VTy->getElementType();
7486         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7487         if (Literal.isInvalid())
7488           return ExprError();
7489         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7490                                     PrepareScalarCast(Literal, ElemTy));
7491         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7492     }
7493 
7494     initExprs.append(exprs, exprs + numExprs);
7495   }
7496   // FIXME: This means that pretty-printing the final AST will produce curly
7497   // braces instead of the original commas.
7498   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7499                                                    initExprs, LiteralRParenLoc);
7500   initE->setType(Ty);
7501   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7502 }
7503 
7504 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7505 /// the ParenListExpr into a sequence of comma binary operators.
7506 ExprResult
7507 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7508   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7509   if (!E)
7510     return OrigExpr;
7511 
7512   ExprResult Result(E->getExpr(0));
7513 
7514   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7515     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7516                         E->getExpr(i));
7517 
7518   if (Result.isInvalid()) return ExprError();
7519 
7520   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7521 }
7522 
7523 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7524                                     SourceLocation R,
7525                                     MultiExprArg Val) {
7526   return ParenListExpr::Create(Context, L, Val, R);
7527 }
7528 
7529 /// Emit a specialized diagnostic when one expression is a null pointer
7530 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7531 /// emitted.
7532 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7533                                       SourceLocation QuestionLoc) {
7534   Expr *NullExpr = LHSExpr;
7535   Expr *NonPointerExpr = RHSExpr;
7536   Expr::NullPointerConstantKind NullKind =
7537       NullExpr->isNullPointerConstant(Context,
7538                                       Expr::NPC_ValueDependentIsNotNull);
7539 
7540   if (NullKind == Expr::NPCK_NotNull) {
7541     NullExpr = RHSExpr;
7542     NonPointerExpr = LHSExpr;
7543     NullKind =
7544         NullExpr->isNullPointerConstant(Context,
7545                                         Expr::NPC_ValueDependentIsNotNull);
7546   }
7547 
7548   if (NullKind == Expr::NPCK_NotNull)
7549     return false;
7550 
7551   if (NullKind == Expr::NPCK_ZeroExpression)
7552     return false;
7553 
7554   if (NullKind == Expr::NPCK_ZeroLiteral) {
7555     // In this case, check to make sure that we got here from a "NULL"
7556     // string in the source code.
7557     NullExpr = NullExpr->IgnoreParenImpCasts();
7558     SourceLocation loc = NullExpr->getExprLoc();
7559     if (!findMacroSpelling(loc, "NULL"))
7560       return false;
7561   }
7562 
7563   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7564   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7565       << NonPointerExpr->getType() << DiagType
7566       << NonPointerExpr->getSourceRange();
7567   return true;
7568 }
7569 
7570 /// Return false if the condition expression is valid, true otherwise.
7571 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7572   QualType CondTy = Cond->getType();
7573 
7574   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7575   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7576     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7577       << CondTy << Cond->getSourceRange();
7578     return true;
7579   }
7580 
7581   // C99 6.5.15p2
7582   if (CondTy->isScalarType()) return false;
7583 
7584   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7585     << CondTy << Cond->getSourceRange();
7586   return true;
7587 }
7588 
7589 /// Handle when one or both operands are void type.
7590 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7591                                          ExprResult &RHS) {
7592     Expr *LHSExpr = LHS.get();
7593     Expr *RHSExpr = RHS.get();
7594 
7595     if (!LHSExpr->getType()->isVoidType())
7596       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7597           << RHSExpr->getSourceRange();
7598     if (!RHSExpr->getType()->isVoidType())
7599       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7600           << LHSExpr->getSourceRange();
7601     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7602     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7603     return S.Context.VoidTy;
7604 }
7605 
7606 /// Return false if the NullExpr can be promoted to PointerTy,
7607 /// true otherwise.
7608 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7609                                         QualType PointerTy) {
7610   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7611       !NullExpr.get()->isNullPointerConstant(S.Context,
7612                                             Expr::NPC_ValueDependentIsNull))
7613     return true;
7614 
7615   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7616   return false;
7617 }
7618 
7619 /// Checks compatibility between two pointers and return the resulting
7620 /// type.
7621 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7622                                                      ExprResult &RHS,
7623                                                      SourceLocation Loc) {
7624   QualType LHSTy = LHS.get()->getType();
7625   QualType RHSTy = RHS.get()->getType();
7626 
7627   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7628     // Two identical pointers types are always compatible.
7629     return LHSTy;
7630   }
7631 
7632   QualType lhptee, rhptee;
7633 
7634   // Get the pointee types.
7635   bool IsBlockPointer = false;
7636   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7637     lhptee = LHSBTy->getPointeeType();
7638     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7639     IsBlockPointer = true;
7640   } else {
7641     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7642     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7643   }
7644 
7645   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7646   // differently qualified versions of compatible types, the result type is
7647   // a pointer to an appropriately qualified version of the composite
7648   // type.
7649 
7650   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7651   // clause doesn't make sense for our extensions. E.g. address space 2 should
7652   // be incompatible with address space 3: they may live on different devices or
7653   // anything.
7654   Qualifiers lhQual = lhptee.getQualifiers();
7655   Qualifiers rhQual = rhptee.getQualifiers();
7656 
7657   LangAS ResultAddrSpace = LangAS::Default;
7658   LangAS LAddrSpace = lhQual.getAddressSpace();
7659   LangAS RAddrSpace = rhQual.getAddressSpace();
7660 
7661   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7662   // spaces is disallowed.
7663   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7664     ResultAddrSpace = LAddrSpace;
7665   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7666     ResultAddrSpace = RAddrSpace;
7667   else {
7668     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7669         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7670         << RHS.get()->getSourceRange();
7671     return QualType();
7672   }
7673 
7674   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7675   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7676   lhQual.removeCVRQualifiers();
7677   rhQual.removeCVRQualifiers();
7678 
7679   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7680   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7681   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7682   // qual types are compatible iff
7683   //  * corresponded types are compatible
7684   //  * CVR qualifiers are equal
7685   //  * address spaces are equal
7686   // Thus for conditional operator we merge CVR and address space unqualified
7687   // pointees and if there is a composite type we return a pointer to it with
7688   // merged qualifiers.
7689   LHSCastKind =
7690       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7691   RHSCastKind =
7692       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7693   lhQual.removeAddressSpace();
7694   rhQual.removeAddressSpace();
7695 
7696   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7697   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7698 
7699   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7700 
7701   if (CompositeTy.isNull()) {
7702     // In this situation, we assume void* type. No especially good
7703     // reason, but this is what gcc does, and we do have to pick
7704     // to get a consistent AST.
7705     QualType incompatTy;
7706     incompatTy = S.Context.getPointerType(
7707         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7708     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7709     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7710 
7711     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7712     // for casts between types with incompatible address space qualifiers.
7713     // For the following code the compiler produces casts between global and
7714     // local address spaces of the corresponded innermost pointees:
7715     // local int *global *a;
7716     // global int *global *b;
7717     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7718     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7719         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7720         << RHS.get()->getSourceRange();
7721 
7722     return incompatTy;
7723   }
7724 
7725   // The pointer types are compatible.
7726   // In case of OpenCL ResultTy should have the address space qualifier
7727   // which is a superset of address spaces of both the 2nd and the 3rd
7728   // operands of the conditional operator.
7729   QualType ResultTy = [&, ResultAddrSpace]() {
7730     if (S.getLangOpts().OpenCL) {
7731       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7732       CompositeQuals.setAddressSpace(ResultAddrSpace);
7733       return S.Context
7734           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7735           .withCVRQualifiers(MergedCVRQual);
7736     }
7737     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7738   }();
7739   if (IsBlockPointer)
7740     ResultTy = S.Context.getBlockPointerType(ResultTy);
7741   else
7742     ResultTy = S.Context.getPointerType(ResultTy);
7743 
7744   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7745   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7746   return ResultTy;
7747 }
7748 
7749 /// Return the resulting type when the operands are both block pointers.
7750 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7751                                                           ExprResult &LHS,
7752                                                           ExprResult &RHS,
7753                                                           SourceLocation Loc) {
7754   QualType LHSTy = LHS.get()->getType();
7755   QualType RHSTy = RHS.get()->getType();
7756 
7757   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7758     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7759       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7760       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7761       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7762       return destType;
7763     }
7764     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7765       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7766       << RHS.get()->getSourceRange();
7767     return QualType();
7768   }
7769 
7770   // We have 2 block pointer types.
7771   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7772 }
7773 
7774 /// Return the resulting type when the operands are both pointers.
7775 static QualType
7776 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7777                                             ExprResult &RHS,
7778                                             SourceLocation Loc) {
7779   // get the pointer types
7780   QualType LHSTy = LHS.get()->getType();
7781   QualType RHSTy = RHS.get()->getType();
7782 
7783   // get the "pointed to" types
7784   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7785   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7786 
7787   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7788   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7789     // Figure out necessary qualifiers (C99 6.5.15p6)
7790     QualType destPointee
7791       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7792     QualType destType = S.Context.getPointerType(destPointee);
7793     // Add qualifiers if necessary.
7794     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7795     // Promote to void*.
7796     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7797     return destType;
7798   }
7799   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7800     QualType destPointee
7801       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7802     QualType destType = S.Context.getPointerType(destPointee);
7803     // Add qualifiers if necessary.
7804     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7805     // Promote to void*.
7806     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7807     return destType;
7808   }
7809 
7810   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7811 }
7812 
7813 /// Return false if the first expression is not an integer and the second
7814 /// expression is not a pointer, true otherwise.
7815 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7816                                         Expr* PointerExpr, SourceLocation Loc,
7817                                         bool IsIntFirstExpr) {
7818   if (!PointerExpr->getType()->isPointerType() ||
7819       !Int.get()->getType()->isIntegerType())
7820     return false;
7821 
7822   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7823   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7824 
7825   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7826     << Expr1->getType() << Expr2->getType()
7827     << Expr1->getSourceRange() << Expr2->getSourceRange();
7828   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7829                             CK_IntegralToPointer);
7830   return true;
7831 }
7832 
7833 /// Simple conversion between integer and floating point types.
7834 ///
7835 /// Used when handling the OpenCL conditional operator where the
7836 /// condition is a vector while the other operands are scalar.
7837 ///
7838 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7839 /// types are either integer or floating type. Between the two
7840 /// operands, the type with the higher rank is defined as the "result
7841 /// type". The other operand needs to be promoted to the same type. No
7842 /// other type promotion is allowed. We cannot use
7843 /// UsualArithmeticConversions() for this purpose, since it always
7844 /// promotes promotable types.
7845 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7846                                             ExprResult &RHS,
7847                                             SourceLocation QuestionLoc) {
7848   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7849   if (LHS.isInvalid())
7850     return QualType();
7851   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7852   if (RHS.isInvalid())
7853     return QualType();
7854 
7855   // For conversion purposes, we ignore any qualifiers.
7856   // For example, "const float" and "float" are equivalent.
7857   QualType LHSType =
7858     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7859   QualType RHSType =
7860     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7861 
7862   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7863     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7864       << LHSType << LHS.get()->getSourceRange();
7865     return QualType();
7866   }
7867 
7868   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7869     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7870       << RHSType << RHS.get()->getSourceRange();
7871     return QualType();
7872   }
7873 
7874   // If both types are identical, no conversion is needed.
7875   if (LHSType == RHSType)
7876     return LHSType;
7877 
7878   // Now handle "real" floating types (i.e. float, double, long double).
7879   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7880     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7881                                  /*IsCompAssign = */ false);
7882 
7883   // Finally, we have two differing integer types.
7884   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7885   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7886 }
7887 
7888 /// Convert scalar operands to a vector that matches the
7889 ///        condition in length.
7890 ///
7891 /// Used when handling the OpenCL conditional operator where the
7892 /// condition is a vector while the other operands are scalar.
7893 ///
7894 /// We first compute the "result type" for the scalar operands
7895 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7896 /// into a vector of that type where the length matches the condition
7897 /// vector type. s6.11.6 requires that the element types of the result
7898 /// and the condition must have the same number of bits.
7899 static QualType
7900 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7901                               QualType CondTy, SourceLocation QuestionLoc) {
7902   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7903   if (ResTy.isNull()) return QualType();
7904 
7905   const VectorType *CV = CondTy->getAs<VectorType>();
7906   assert(CV);
7907 
7908   // Determine the vector result type
7909   unsigned NumElements = CV->getNumElements();
7910   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7911 
7912   // Ensure that all types have the same number of bits
7913   if (S.Context.getTypeSize(CV->getElementType())
7914       != S.Context.getTypeSize(ResTy)) {
7915     // Since VectorTy is created internally, it does not pretty print
7916     // with an OpenCL name. Instead, we just print a description.
7917     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7918     SmallString<64> Str;
7919     llvm::raw_svector_ostream OS(Str);
7920     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7921     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7922       << CondTy << OS.str();
7923     return QualType();
7924   }
7925 
7926   // Convert operands to the vector result type
7927   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7928   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7929 
7930   return VectorTy;
7931 }
7932 
7933 /// Return false if this is a valid OpenCL condition vector
7934 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7935                                        SourceLocation QuestionLoc) {
7936   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7937   // integral type.
7938   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7939   assert(CondTy);
7940   QualType EleTy = CondTy->getElementType();
7941   if (EleTy->isIntegerType()) return false;
7942 
7943   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7944     << Cond->getType() << Cond->getSourceRange();
7945   return true;
7946 }
7947 
7948 /// Return false if the vector condition type and the vector
7949 ///        result type are compatible.
7950 ///
7951 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7952 /// number of elements, and their element types have the same number
7953 /// of bits.
7954 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7955                               SourceLocation QuestionLoc) {
7956   const VectorType *CV = CondTy->getAs<VectorType>();
7957   const VectorType *RV = VecResTy->getAs<VectorType>();
7958   assert(CV && RV);
7959 
7960   if (CV->getNumElements() != RV->getNumElements()) {
7961     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7962       << CondTy << VecResTy;
7963     return true;
7964   }
7965 
7966   QualType CVE = CV->getElementType();
7967   QualType RVE = RV->getElementType();
7968 
7969   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7970     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7971       << CondTy << VecResTy;
7972     return true;
7973   }
7974 
7975   return false;
7976 }
7977 
7978 /// Return the resulting type for the conditional operator in
7979 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7980 ///        s6.3.i) when the condition is a vector type.
7981 static QualType
7982 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7983                              ExprResult &LHS, ExprResult &RHS,
7984                              SourceLocation QuestionLoc) {
7985   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7986   if (Cond.isInvalid())
7987     return QualType();
7988   QualType CondTy = Cond.get()->getType();
7989 
7990   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7991     return QualType();
7992 
7993   // If either operand is a vector then find the vector type of the
7994   // result as specified in OpenCL v1.1 s6.3.i.
7995   if (LHS.get()->getType()->isVectorType() ||
7996       RHS.get()->getType()->isVectorType()) {
7997     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7998                                               /*isCompAssign*/false,
7999                                               /*AllowBothBool*/true,
8000                                               /*AllowBoolConversions*/false);
8001     if (VecResTy.isNull()) return QualType();
8002     // The result type must match the condition type as specified in
8003     // OpenCL v1.1 s6.11.6.
8004     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8005       return QualType();
8006     return VecResTy;
8007   }
8008 
8009   // Both operands are scalar.
8010   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8011 }
8012 
8013 /// Return true if the Expr is block type
8014 static bool checkBlockType(Sema &S, const Expr *E) {
8015   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8016     QualType Ty = CE->getCallee()->getType();
8017     if (Ty->isBlockPointerType()) {
8018       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8019       return true;
8020     }
8021   }
8022   return false;
8023 }
8024 
8025 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8026 /// In that case, LHS = cond.
8027 /// C99 6.5.15
8028 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8029                                         ExprResult &RHS, ExprValueKind &VK,
8030                                         ExprObjectKind &OK,
8031                                         SourceLocation QuestionLoc) {
8032 
8033   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8034   if (!LHSResult.isUsable()) return QualType();
8035   LHS = LHSResult;
8036 
8037   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8038   if (!RHSResult.isUsable()) return QualType();
8039   RHS = RHSResult;
8040 
8041   // C++ is sufficiently different to merit its own checker.
8042   if (getLangOpts().CPlusPlus)
8043     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8044 
8045   VK = VK_RValue;
8046   OK = OK_Ordinary;
8047 
8048   if (Context.isDependenceAllowed() &&
8049       (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8050        RHS.get()->isTypeDependent())) {
8051     assert(!getLangOpts().CPlusPlus);
8052     assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8053             RHS.get()->containsErrors()) &&
8054            "should only occur in error-recovery path.");
8055     return Context.DependentTy;
8056   }
8057 
8058   // The OpenCL operator with a vector condition is sufficiently
8059   // different to merit its own checker.
8060   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8061       Cond.get()->getType()->isExtVectorType())
8062     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8063 
8064   // First, check the condition.
8065   Cond = UsualUnaryConversions(Cond.get());
8066   if (Cond.isInvalid())
8067     return QualType();
8068   if (checkCondition(*this, Cond.get(), QuestionLoc))
8069     return QualType();
8070 
8071   // Now check the two expressions.
8072   if (LHS.get()->getType()->isVectorType() ||
8073       RHS.get()->getType()->isVectorType())
8074     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8075                                /*AllowBothBool*/true,
8076                                /*AllowBoolConversions*/false);
8077 
8078   QualType ResTy =
8079       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8080   if (LHS.isInvalid() || RHS.isInvalid())
8081     return QualType();
8082 
8083   QualType LHSTy = LHS.get()->getType();
8084   QualType RHSTy = RHS.get()->getType();
8085 
8086   // Diagnose attempts to convert between __float128 and long double where
8087   // such conversions currently can't be handled.
8088   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8089     Diag(QuestionLoc,
8090          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8091       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8092     return QualType();
8093   }
8094 
8095   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8096   // selection operator (?:).
8097   if (getLangOpts().OpenCL &&
8098       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8099     return QualType();
8100   }
8101 
8102   // If both operands have arithmetic type, do the usual arithmetic conversions
8103   // to find a common type: C99 6.5.15p3,5.
8104   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8105     // Disallow invalid arithmetic conversions, such as those between ExtInts of
8106     // different sizes, or between ExtInts and other types.
8107     if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8108       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8109           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8110           << RHS.get()->getSourceRange();
8111       return QualType();
8112     }
8113 
8114     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8115     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8116 
8117     return ResTy;
8118   }
8119 
8120   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8121   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8122     return LHSTy;
8123   }
8124 
8125   // If both operands are the same structure or union type, the result is that
8126   // type.
8127   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8128     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8129       if (LHSRT->getDecl() == RHSRT->getDecl())
8130         // "If both the operands have structure or union type, the result has
8131         // that type."  This implies that CV qualifiers are dropped.
8132         return LHSTy.getUnqualifiedType();
8133     // FIXME: Type of conditional expression must be complete in C mode.
8134   }
8135 
8136   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8137   // The following || allows only one side to be void (a GCC-ism).
8138   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8139     return checkConditionalVoidType(*this, LHS, RHS);
8140   }
8141 
8142   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8143   // the type of the other operand."
8144   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8145   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8146 
8147   // All objective-c pointer type analysis is done here.
8148   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8149                                                         QuestionLoc);
8150   if (LHS.isInvalid() || RHS.isInvalid())
8151     return QualType();
8152   if (!compositeType.isNull())
8153     return compositeType;
8154 
8155 
8156   // Handle block pointer types.
8157   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8158     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8159                                                      QuestionLoc);
8160 
8161   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8162   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8163     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8164                                                        QuestionLoc);
8165 
8166   // GCC compatibility: soften pointer/integer mismatch.  Note that
8167   // null pointers have been filtered out by this point.
8168   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8169       /*IsIntFirstExpr=*/true))
8170     return RHSTy;
8171   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8172       /*IsIntFirstExpr=*/false))
8173     return LHSTy;
8174 
8175   // Allow ?: operations in which both operands have the same
8176   // built-in sizeless type.
8177   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8178     return LHSTy;
8179 
8180   // Emit a better diagnostic if one of the expressions is a null pointer
8181   // constant and the other is not a pointer type. In this case, the user most
8182   // likely forgot to take the address of the other expression.
8183   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8184     return QualType();
8185 
8186   // Otherwise, the operands are not compatible.
8187   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8188     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8189     << RHS.get()->getSourceRange();
8190   return QualType();
8191 }
8192 
8193 /// FindCompositeObjCPointerType - Helper method to find composite type of
8194 /// two objective-c pointer types of the two input expressions.
8195 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8196                                             SourceLocation QuestionLoc) {
8197   QualType LHSTy = LHS.get()->getType();
8198   QualType RHSTy = RHS.get()->getType();
8199 
8200   // Handle things like Class and struct objc_class*.  Here we case the result
8201   // to the pseudo-builtin, because that will be implicitly cast back to the
8202   // redefinition type if an attempt is made to access its fields.
8203   if (LHSTy->isObjCClassType() &&
8204       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8205     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8206     return LHSTy;
8207   }
8208   if (RHSTy->isObjCClassType() &&
8209       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8210     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8211     return RHSTy;
8212   }
8213   // And the same for struct objc_object* / id
8214   if (LHSTy->isObjCIdType() &&
8215       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8216     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8217     return LHSTy;
8218   }
8219   if (RHSTy->isObjCIdType() &&
8220       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8221     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8222     return RHSTy;
8223   }
8224   // And the same for struct objc_selector* / SEL
8225   if (Context.isObjCSelType(LHSTy) &&
8226       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8227     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8228     return LHSTy;
8229   }
8230   if (Context.isObjCSelType(RHSTy) &&
8231       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8232     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8233     return RHSTy;
8234   }
8235   // Check constraints for Objective-C object pointers types.
8236   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8237 
8238     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8239       // Two identical object pointer types are always compatible.
8240       return LHSTy;
8241     }
8242     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8243     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8244     QualType compositeType = LHSTy;
8245 
8246     // If both operands are interfaces and either operand can be
8247     // assigned to the other, use that type as the composite
8248     // type. This allows
8249     //   xxx ? (A*) a : (B*) b
8250     // where B is a subclass of A.
8251     //
8252     // Additionally, as for assignment, if either type is 'id'
8253     // allow silent coercion. Finally, if the types are
8254     // incompatible then make sure to use 'id' as the composite
8255     // type so the result is acceptable for sending messages to.
8256 
8257     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8258     // It could return the composite type.
8259     if (!(compositeType =
8260           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8261       // Nothing more to do.
8262     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8263       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8264     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8265       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8266     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8267                 RHSOPT->isObjCQualifiedIdType()) &&
8268                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8269                                                          true)) {
8270       // Need to handle "id<xx>" explicitly.
8271       // GCC allows qualified id and any Objective-C type to devolve to
8272       // id. Currently localizing to here until clear this should be
8273       // part of ObjCQualifiedIdTypesAreCompatible.
8274       compositeType = Context.getObjCIdType();
8275     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8276       compositeType = Context.getObjCIdType();
8277     } else {
8278       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8279       << LHSTy << RHSTy
8280       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8281       QualType incompatTy = Context.getObjCIdType();
8282       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8283       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8284       return incompatTy;
8285     }
8286     // The object pointer types are compatible.
8287     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8288     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8289     return compositeType;
8290   }
8291   // Check Objective-C object pointer types and 'void *'
8292   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8293     if (getLangOpts().ObjCAutoRefCount) {
8294       // ARC forbids the implicit conversion of object pointers to 'void *',
8295       // so these types are not compatible.
8296       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8297           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8298       LHS = RHS = true;
8299       return QualType();
8300     }
8301     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8302     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8303     QualType destPointee
8304     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8305     QualType destType = Context.getPointerType(destPointee);
8306     // Add qualifiers if necessary.
8307     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8308     // Promote to void*.
8309     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8310     return destType;
8311   }
8312   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8313     if (getLangOpts().ObjCAutoRefCount) {
8314       // ARC forbids the implicit conversion of object pointers to 'void *',
8315       // so these types are not compatible.
8316       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8317           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8318       LHS = RHS = true;
8319       return QualType();
8320     }
8321     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8322     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8323     QualType destPointee
8324     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8325     QualType destType = Context.getPointerType(destPointee);
8326     // Add qualifiers if necessary.
8327     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8328     // Promote to void*.
8329     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8330     return destType;
8331   }
8332   return QualType();
8333 }
8334 
8335 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8336 /// ParenRange in parentheses.
8337 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8338                                const PartialDiagnostic &Note,
8339                                SourceRange ParenRange) {
8340   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8341   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8342       EndLoc.isValid()) {
8343     Self.Diag(Loc, Note)
8344       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8345       << FixItHint::CreateInsertion(EndLoc, ")");
8346   } else {
8347     // We can't display the parentheses, so just show the bare note.
8348     Self.Diag(Loc, Note) << ParenRange;
8349   }
8350 }
8351 
8352 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8353   return BinaryOperator::isAdditiveOp(Opc) ||
8354          BinaryOperator::isMultiplicativeOp(Opc) ||
8355          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8356   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8357   // not any of the logical operators.  Bitwise-xor is commonly used as a
8358   // logical-xor because there is no logical-xor operator.  The logical
8359   // operators, including uses of xor, have a high false positive rate for
8360   // precedence warnings.
8361 }
8362 
8363 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8364 /// expression, either using a built-in or overloaded operator,
8365 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8366 /// expression.
8367 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8368                                    Expr **RHSExprs) {
8369   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8370   E = E->IgnoreImpCasts();
8371   E = E->IgnoreConversionOperatorSingleStep();
8372   E = E->IgnoreImpCasts();
8373   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8374     E = MTE->getSubExpr();
8375     E = E->IgnoreImpCasts();
8376   }
8377 
8378   // Built-in binary operator.
8379   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8380     if (IsArithmeticOp(OP->getOpcode())) {
8381       *Opcode = OP->getOpcode();
8382       *RHSExprs = OP->getRHS();
8383       return true;
8384     }
8385   }
8386 
8387   // Overloaded operator.
8388   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8389     if (Call->getNumArgs() != 2)
8390       return false;
8391 
8392     // Make sure this is really a binary operator that is safe to pass into
8393     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8394     OverloadedOperatorKind OO = Call->getOperator();
8395     if (OO < OO_Plus || OO > OO_Arrow ||
8396         OO == OO_PlusPlus || OO == OO_MinusMinus)
8397       return false;
8398 
8399     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8400     if (IsArithmeticOp(OpKind)) {
8401       *Opcode = OpKind;
8402       *RHSExprs = Call->getArg(1);
8403       return true;
8404     }
8405   }
8406 
8407   return false;
8408 }
8409 
8410 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8411 /// or is a logical expression such as (x==y) which has int type, but is
8412 /// commonly interpreted as boolean.
8413 static bool ExprLooksBoolean(Expr *E) {
8414   E = E->IgnoreParenImpCasts();
8415 
8416   if (E->getType()->isBooleanType())
8417     return true;
8418   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8419     return OP->isComparisonOp() || OP->isLogicalOp();
8420   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8421     return OP->getOpcode() == UO_LNot;
8422   if (E->getType()->isPointerType())
8423     return true;
8424   // FIXME: What about overloaded operator calls returning "unspecified boolean
8425   // type"s (commonly pointer-to-members)?
8426 
8427   return false;
8428 }
8429 
8430 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8431 /// and binary operator are mixed in a way that suggests the programmer assumed
8432 /// the conditional operator has higher precedence, for example:
8433 /// "int x = a + someBinaryCondition ? 1 : 2".
8434 static void DiagnoseConditionalPrecedence(Sema &Self,
8435                                           SourceLocation OpLoc,
8436                                           Expr *Condition,
8437                                           Expr *LHSExpr,
8438                                           Expr *RHSExpr) {
8439   BinaryOperatorKind CondOpcode;
8440   Expr *CondRHS;
8441 
8442   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8443     return;
8444   if (!ExprLooksBoolean(CondRHS))
8445     return;
8446 
8447   // The condition is an arithmetic binary expression, with a right-
8448   // hand side that looks boolean, so warn.
8449 
8450   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8451                         ? diag::warn_precedence_bitwise_conditional
8452                         : diag::warn_precedence_conditional;
8453 
8454   Self.Diag(OpLoc, DiagID)
8455       << Condition->getSourceRange()
8456       << BinaryOperator::getOpcodeStr(CondOpcode);
8457 
8458   SuggestParentheses(
8459       Self, OpLoc,
8460       Self.PDiag(diag::note_precedence_silence)
8461           << BinaryOperator::getOpcodeStr(CondOpcode),
8462       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8463 
8464   SuggestParentheses(Self, OpLoc,
8465                      Self.PDiag(diag::note_precedence_conditional_first),
8466                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8467 }
8468 
8469 /// Compute the nullability of a conditional expression.
8470 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8471                                               QualType LHSTy, QualType RHSTy,
8472                                               ASTContext &Ctx) {
8473   if (!ResTy->isAnyPointerType())
8474     return ResTy;
8475 
8476   auto GetNullability = [&Ctx](QualType Ty) {
8477     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8478     if (Kind)
8479       return *Kind;
8480     return NullabilityKind::Unspecified;
8481   };
8482 
8483   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8484   NullabilityKind MergedKind;
8485 
8486   // Compute nullability of a binary conditional expression.
8487   if (IsBin) {
8488     if (LHSKind == NullabilityKind::NonNull)
8489       MergedKind = NullabilityKind::NonNull;
8490     else
8491       MergedKind = RHSKind;
8492   // Compute nullability of a normal conditional expression.
8493   } else {
8494     if (LHSKind == NullabilityKind::Nullable ||
8495         RHSKind == NullabilityKind::Nullable)
8496       MergedKind = NullabilityKind::Nullable;
8497     else if (LHSKind == NullabilityKind::NonNull)
8498       MergedKind = RHSKind;
8499     else if (RHSKind == NullabilityKind::NonNull)
8500       MergedKind = LHSKind;
8501     else
8502       MergedKind = NullabilityKind::Unspecified;
8503   }
8504 
8505   // Return if ResTy already has the correct nullability.
8506   if (GetNullability(ResTy) == MergedKind)
8507     return ResTy;
8508 
8509   // Strip all nullability from ResTy.
8510   while (ResTy->getNullability(Ctx))
8511     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8512 
8513   // Create a new AttributedType with the new nullability kind.
8514   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8515   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8516 }
8517 
8518 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8519 /// in the case of a the GNU conditional expr extension.
8520 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8521                                     SourceLocation ColonLoc,
8522                                     Expr *CondExpr, Expr *LHSExpr,
8523                                     Expr *RHSExpr) {
8524   if (!Context.isDependenceAllowed()) {
8525     // C cannot handle TypoExpr nodes in the condition because it
8526     // doesn't handle dependent types properly, so make sure any TypoExprs have
8527     // been dealt with before checking the operands.
8528     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8529     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8530     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8531 
8532     if (!CondResult.isUsable())
8533       return ExprError();
8534 
8535     if (LHSExpr) {
8536       if (!LHSResult.isUsable())
8537         return ExprError();
8538     }
8539 
8540     if (!RHSResult.isUsable())
8541       return ExprError();
8542 
8543     CondExpr = CondResult.get();
8544     LHSExpr = LHSResult.get();
8545     RHSExpr = RHSResult.get();
8546   }
8547 
8548   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8549   // was the condition.
8550   OpaqueValueExpr *opaqueValue = nullptr;
8551   Expr *commonExpr = nullptr;
8552   if (!LHSExpr) {
8553     commonExpr = CondExpr;
8554     // Lower out placeholder types first.  This is important so that we don't
8555     // try to capture a placeholder. This happens in few cases in C++; such
8556     // as Objective-C++'s dictionary subscripting syntax.
8557     if (commonExpr->hasPlaceholderType()) {
8558       ExprResult result = CheckPlaceholderExpr(commonExpr);
8559       if (!result.isUsable()) return ExprError();
8560       commonExpr = result.get();
8561     }
8562     // We usually want to apply unary conversions *before* saving, except
8563     // in the special case of a C++ l-value conditional.
8564     if (!(getLangOpts().CPlusPlus
8565           && !commonExpr->isTypeDependent()
8566           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8567           && commonExpr->isGLValue()
8568           && commonExpr->isOrdinaryOrBitFieldObject()
8569           && RHSExpr->isOrdinaryOrBitFieldObject()
8570           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8571       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8572       if (commonRes.isInvalid())
8573         return ExprError();
8574       commonExpr = commonRes.get();
8575     }
8576 
8577     // If the common expression is a class or array prvalue, materialize it
8578     // so that we can safely refer to it multiple times.
8579     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8580                                    commonExpr->getType()->isArrayType())) {
8581       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8582       if (MatExpr.isInvalid())
8583         return ExprError();
8584       commonExpr = MatExpr.get();
8585     }
8586 
8587     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8588                                                 commonExpr->getType(),
8589                                                 commonExpr->getValueKind(),
8590                                                 commonExpr->getObjectKind(),
8591                                                 commonExpr);
8592     LHSExpr = CondExpr = opaqueValue;
8593   }
8594 
8595   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8596   ExprValueKind VK = VK_RValue;
8597   ExprObjectKind OK = OK_Ordinary;
8598   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8599   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8600                                              VK, OK, QuestionLoc);
8601   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8602       RHS.isInvalid())
8603     return ExprError();
8604 
8605   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8606                                 RHS.get());
8607 
8608   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8609 
8610   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8611                                          Context);
8612 
8613   if (!commonExpr)
8614     return new (Context)
8615         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8616                             RHS.get(), result, VK, OK);
8617 
8618   return new (Context) BinaryConditionalOperator(
8619       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8620       ColonLoc, result, VK, OK);
8621 }
8622 
8623 // Check if we have a conversion between incompatible cmse function pointer
8624 // types, that is, a conversion between a function pointer with the
8625 // cmse_nonsecure_call attribute and one without.
8626 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8627                                           QualType ToType) {
8628   if (const auto *ToFn =
8629           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8630     if (const auto *FromFn =
8631             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8632       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8633       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8634 
8635       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8636     }
8637   }
8638   return false;
8639 }
8640 
8641 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8642 // being closely modeled after the C99 spec:-). The odd characteristic of this
8643 // routine is it effectively iqnores the qualifiers on the top level pointee.
8644 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8645 // FIXME: add a couple examples in this comment.
8646 static Sema::AssignConvertType
8647 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8648   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8649   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8650 
8651   // get the "pointed to" type (ignoring qualifiers at the top level)
8652   const Type *lhptee, *rhptee;
8653   Qualifiers lhq, rhq;
8654   std::tie(lhptee, lhq) =
8655       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8656   std::tie(rhptee, rhq) =
8657       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8658 
8659   Sema::AssignConvertType ConvTy = Sema::Compatible;
8660 
8661   // C99 6.5.16.1p1: This following citation is common to constraints
8662   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8663   // qualifiers of the type *pointed to* by the right;
8664 
8665   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8666   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8667       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8668     // Ignore lifetime for further calculation.
8669     lhq.removeObjCLifetime();
8670     rhq.removeObjCLifetime();
8671   }
8672 
8673   if (!lhq.compatiblyIncludes(rhq)) {
8674     // Treat address-space mismatches as fatal.
8675     if (!lhq.isAddressSpaceSupersetOf(rhq))
8676       return Sema::IncompatiblePointerDiscardsQualifiers;
8677 
8678     // It's okay to add or remove GC or lifetime qualifiers when converting to
8679     // and from void*.
8680     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8681                         .compatiblyIncludes(
8682                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8683              && (lhptee->isVoidType() || rhptee->isVoidType()))
8684       ; // keep old
8685 
8686     // Treat lifetime mismatches as fatal.
8687     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8688       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8689 
8690     // For GCC/MS compatibility, other qualifier mismatches are treated
8691     // as still compatible in C.
8692     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8693   }
8694 
8695   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8696   // incomplete type and the other is a pointer to a qualified or unqualified
8697   // version of void...
8698   if (lhptee->isVoidType()) {
8699     if (rhptee->isIncompleteOrObjectType())
8700       return ConvTy;
8701 
8702     // As an extension, we allow cast to/from void* to function pointer.
8703     assert(rhptee->isFunctionType());
8704     return Sema::FunctionVoidPointer;
8705   }
8706 
8707   if (rhptee->isVoidType()) {
8708     if (lhptee->isIncompleteOrObjectType())
8709       return ConvTy;
8710 
8711     // As an extension, we allow cast to/from void* to function pointer.
8712     assert(lhptee->isFunctionType());
8713     return Sema::FunctionVoidPointer;
8714   }
8715 
8716   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8717   // unqualified versions of compatible types, ...
8718   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8719   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8720     // Check if the pointee types are compatible ignoring the sign.
8721     // We explicitly check for char so that we catch "char" vs
8722     // "unsigned char" on systems where "char" is unsigned.
8723     if (lhptee->isCharType())
8724       ltrans = S.Context.UnsignedCharTy;
8725     else if (lhptee->hasSignedIntegerRepresentation())
8726       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8727 
8728     if (rhptee->isCharType())
8729       rtrans = S.Context.UnsignedCharTy;
8730     else if (rhptee->hasSignedIntegerRepresentation())
8731       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8732 
8733     if (ltrans == rtrans) {
8734       // Types are compatible ignoring the sign. Qualifier incompatibility
8735       // takes priority over sign incompatibility because the sign
8736       // warning can be disabled.
8737       if (ConvTy != Sema::Compatible)
8738         return ConvTy;
8739 
8740       return Sema::IncompatiblePointerSign;
8741     }
8742 
8743     // If we are a multi-level pointer, it's possible that our issue is simply
8744     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8745     // the eventual target type is the same and the pointers have the same
8746     // level of indirection, this must be the issue.
8747     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8748       do {
8749         std::tie(lhptee, lhq) =
8750           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8751         std::tie(rhptee, rhq) =
8752           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8753 
8754         // Inconsistent address spaces at this point is invalid, even if the
8755         // address spaces would be compatible.
8756         // FIXME: This doesn't catch address space mismatches for pointers of
8757         // different nesting levels, like:
8758         //   __local int *** a;
8759         //   int ** b = a;
8760         // It's not clear how to actually determine when such pointers are
8761         // invalidly incompatible.
8762         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8763           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8764 
8765       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8766 
8767       if (lhptee == rhptee)
8768         return Sema::IncompatibleNestedPointerQualifiers;
8769     }
8770 
8771     // General pointer incompatibility takes priority over qualifiers.
8772     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8773       return Sema::IncompatibleFunctionPointer;
8774     return Sema::IncompatiblePointer;
8775   }
8776   if (!S.getLangOpts().CPlusPlus &&
8777       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8778     return Sema::IncompatibleFunctionPointer;
8779   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8780     return Sema::IncompatibleFunctionPointer;
8781   return ConvTy;
8782 }
8783 
8784 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8785 /// block pointer types are compatible or whether a block and normal pointer
8786 /// are compatible. It is more restrict than comparing two function pointer
8787 // types.
8788 static Sema::AssignConvertType
8789 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8790                                     QualType RHSType) {
8791   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8792   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8793 
8794   QualType lhptee, rhptee;
8795 
8796   // get the "pointed to" type (ignoring qualifiers at the top level)
8797   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8798   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8799 
8800   // In C++, the types have to match exactly.
8801   if (S.getLangOpts().CPlusPlus)
8802     return Sema::IncompatibleBlockPointer;
8803 
8804   Sema::AssignConvertType ConvTy = Sema::Compatible;
8805 
8806   // For blocks we enforce that qualifiers are identical.
8807   Qualifiers LQuals = lhptee.getLocalQualifiers();
8808   Qualifiers RQuals = rhptee.getLocalQualifiers();
8809   if (S.getLangOpts().OpenCL) {
8810     LQuals.removeAddressSpace();
8811     RQuals.removeAddressSpace();
8812   }
8813   if (LQuals != RQuals)
8814     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8815 
8816   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8817   // assignment.
8818   // The current behavior is similar to C++ lambdas. A block might be
8819   // assigned to a variable iff its return type and parameters are compatible
8820   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8821   // an assignment. Presumably it should behave in way that a function pointer
8822   // assignment does in C, so for each parameter and return type:
8823   //  * CVR and address space of LHS should be a superset of CVR and address
8824   //  space of RHS.
8825   //  * unqualified types should be compatible.
8826   if (S.getLangOpts().OpenCL) {
8827     if (!S.Context.typesAreBlockPointerCompatible(
8828             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8829             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8830       return Sema::IncompatibleBlockPointer;
8831   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8832     return Sema::IncompatibleBlockPointer;
8833 
8834   return ConvTy;
8835 }
8836 
8837 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8838 /// for assignment compatibility.
8839 static Sema::AssignConvertType
8840 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8841                                    QualType RHSType) {
8842   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8843   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8844 
8845   if (LHSType->isObjCBuiltinType()) {
8846     // Class is not compatible with ObjC object pointers.
8847     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8848         !RHSType->isObjCQualifiedClassType())
8849       return Sema::IncompatiblePointer;
8850     return Sema::Compatible;
8851   }
8852   if (RHSType->isObjCBuiltinType()) {
8853     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8854         !LHSType->isObjCQualifiedClassType())
8855       return Sema::IncompatiblePointer;
8856     return Sema::Compatible;
8857   }
8858   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8859   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8860 
8861   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8862       // make an exception for id<P>
8863       !LHSType->isObjCQualifiedIdType())
8864     return Sema::CompatiblePointerDiscardsQualifiers;
8865 
8866   if (S.Context.typesAreCompatible(LHSType, RHSType))
8867     return Sema::Compatible;
8868   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8869     return Sema::IncompatibleObjCQualifiedId;
8870   return Sema::IncompatiblePointer;
8871 }
8872 
8873 Sema::AssignConvertType
8874 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8875                                  QualType LHSType, QualType RHSType) {
8876   // Fake up an opaque expression.  We don't actually care about what
8877   // cast operations are required, so if CheckAssignmentConstraints
8878   // adds casts to this they'll be wasted, but fortunately that doesn't
8879   // usually happen on valid code.
8880   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8881   ExprResult RHSPtr = &RHSExpr;
8882   CastKind K;
8883 
8884   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8885 }
8886 
8887 /// This helper function returns true if QT is a vector type that has element
8888 /// type ElementType.
8889 static bool isVector(QualType QT, QualType ElementType) {
8890   if (const VectorType *VT = QT->getAs<VectorType>())
8891     return VT->getElementType().getCanonicalType() == ElementType;
8892   return false;
8893 }
8894 
8895 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8896 /// has code to accommodate several GCC extensions when type checking
8897 /// pointers. Here are some objectionable examples that GCC considers warnings:
8898 ///
8899 ///  int a, *pint;
8900 ///  short *pshort;
8901 ///  struct foo *pfoo;
8902 ///
8903 ///  pint = pshort; // warning: assignment from incompatible pointer type
8904 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8905 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8906 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8907 ///
8908 /// As a result, the code for dealing with pointers is more complex than the
8909 /// C99 spec dictates.
8910 ///
8911 /// Sets 'Kind' for any result kind except Incompatible.
8912 Sema::AssignConvertType
8913 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8914                                  CastKind &Kind, bool ConvertRHS) {
8915   QualType RHSType = RHS.get()->getType();
8916   QualType OrigLHSType = LHSType;
8917 
8918   // Get canonical types.  We're not formatting these types, just comparing
8919   // them.
8920   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8921   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8922 
8923   // Common case: no conversion required.
8924   if (LHSType == RHSType) {
8925     Kind = CK_NoOp;
8926     return Compatible;
8927   }
8928 
8929   // If we have an atomic type, try a non-atomic assignment, then just add an
8930   // atomic qualification step.
8931   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8932     Sema::AssignConvertType result =
8933       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8934     if (result != Compatible)
8935       return result;
8936     if (Kind != CK_NoOp && ConvertRHS)
8937       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8938     Kind = CK_NonAtomicToAtomic;
8939     return Compatible;
8940   }
8941 
8942   // If the left-hand side is a reference type, then we are in a
8943   // (rare!) case where we've allowed the use of references in C,
8944   // e.g., as a parameter type in a built-in function. In this case,
8945   // just make sure that the type referenced is compatible with the
8946   // right-hand side type. The caller is responsible for adjusting
8947   // LHSType so that the resulting expression does not have reference
8948   // type.
8949   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8950     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8951       Kind = CK_LValueBitCast;
8952       return Compatible;
8953     }
8954     return Incompatible;
8955   }
8956 
8957   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8958   // to the same ExtVector type.
8959   if (LHSType->isExtVectorType()) {
8960     if (RHSType->isExtVectorType())
8961       return Incompatible;
8962     if (RHSType->isArithmeticType()) {
8963       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8964       if (ConvertRHS)
8965         RHS = prepareVectorSplat(LHSType, RHS.get());
8966       Kind = CK_VectorSplat;
8967       return Compatible;
8968     }
8969   }
8970 
8971   // Conversions to or from vector type.
8972   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8973     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8974       // Allow assignments of an AltiVec vector type to an equivalent GCC
8975       // vector type and vice versa
8976       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8977         Kind = CK_BitCast;
8978         return Compatible;
8979       }
8980 
8981       // If we are allowing lax vector conversions, and LHS and RHS are both
8982       // vectors, the total size only needs to be the same. This is a bitcast;
8983       // no bits are changed but the result type is different.
8984       if (isLaxVectorConversion(RHSType, LHSType)) {
8985         Kind = CK_BitCast;
8986         return IncompatibleVectors;
8987       }
8988     }
8989 
8990     // When the RHS comes from another lax conversion (e.g. binops between
8991     // scalars and vectors) the result is canonicalized as a vector. When the
8992     // LHS is also a vector, the lax is allowed by the condition above. Handle
8993     // the case where LHS is a scalar.
8994     if (LHSType->isScalarType()) {
8995       const VectorType *VecType = RHSType->getAs<VectorType>();
8996       if (VecType && VecType->getNumElements() == 1 &&
8997           isLaxVectorConversion(RHSType, LHSType)) {
8998         ExprResult *VecExpr = &RHS;
8999         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9000         Kind = CK_BitCast;
9001         return Compatible;
9002       }
9003     }
9004 
9005     // Allow assignments between fixed-length and sizeless SVE vectors.
9006     if (((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9007          (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) &&
9008         Context.areCompatibleSveTypes(LHSType, RHSType)) {
9009       Kind = CK_BitCast;
9010       return Compatible;
9011     }
9012 
9013     return Incompatible;
9014   }
9015 
9016   // Diagnose attempts to convert between __float128 and long double where
9017   // such conversions currently can't be handled.
9018   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9019     return Incompatible;
9020 
9021   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9022   // discards the imaginary part.
9023   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9024       !LHSType->getAs<ComplexType>())
9025     return Incompatible;
9026 
9027   // Arithmetic conversions.
9028   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9029       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9030     if (ConvertRHS)
9031       Kind = PrepareScalarCast(RHS, LHSType);
9032     return Compatible;
9033   }
9034 
9035   // Conversions to normal pointers.
9036   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9037     // U* -> T*
9038     if (isa<PointerType>(RHSType)) {
9039       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9040       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9041       if (AddrSpaceL != AddrSpaceR)
9042         Kind = CK_AddressSpaceConversion;
9043       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9044         Kind = CK_NoOp;
9045       else
9046         Kind = CK_BitCast;
9047       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9048     }
9049 
9050     // int -> T*
9051     if (RHSType->isIntegerType()) {
9052       Kind = CK_IntegralToPointer; // FIXME: null?
9053       return IntToPointer;
9054     }
9055 
9056     // C pointers are not compatible with ObjC object pointers,
9057     // with two exceptions:
9058     if (isa<ObjCObjectPointerType>(RHSType)) {
9059       //  - conversions to void*
9060       if (LHSPointer->getPointeeType()->isVoidType()) {
9061         Kind = CK_BitCast;
9062         return Compatible;
9063       }
9064 
9065       //  - conversions from 'Class' to the redefinition type
9066       if (RHSType->isObjCClassType() &&
9067           Context.hasSameType(LHSType,
9068                               Context.getObjCClassRedefinitionType())) {
9069         Kind = CK_BitCast;
9070         return Compatible;
9071       }
9072 
9073       Kind = CK_BitCast;
9074       return IncompatiblePointer;
9075     }
9076 
9077     // U^ -> void*
9078     if (RHSType->getAs<BlockPointerType>()) {
9079       if (LHSPointer->getPointeeType()->isVoidType()) {
9080         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9081         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9082                                 ->getPointeeType()
9083                                 .getAddressSpace();
9084         Kind =
9085             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9086         return Compatible;
9087       }
9088     }
9089 
9090     return Incompatible;
9091   }
9092 
9093   // Conversions to block pointers.
9094   if (isa<BlockPointerType>(LHSType)) {
9095     // U^ -> T^
9096     if (RHSType->isBlockPointerType()) {
9097       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9098                               ->getPointeeType()
9099                               .getAddressSpace();
9100       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9101                               ->getPointeeType()
9102                               .getAddressSpace();
9103       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9104       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9105     }
9106 
9107     // int or null -> T^
9108     if (RHSType->isIntegerType()) {
9109       Kind = CK_IntegralToPointer; // FIXME: null
9110       return IntToBlockPointer;
9111     }
9112 
9113     // id -> T^
9114     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9115       Kind = CK_AnyPointerToBlockPointerCast;
9116       return Compatible;
9117     }
9118 
9119     // void* -> T^
9120     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9121       if (RHSPT->getPointeeType()->isVoidType()) {
9122         Kind = CK_AnyPointerToBlockPointerCast;
9123         return Compatible;
9124       }
9125 
9126     return Incompatible;
9127   }
9128 
9129   // Conversions to Objective-C pointers.
9130   if (isa<ObjCObjectPointerType>(LHSType)) {
9131     // A* -> B*
9132     if (RHSType->isObjCObjectPointerType()) {
9133       Kind = CK_BitCast;
9134       Sema::AssignConvertType result =
9135         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9136       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9137           result == Compatible &&
9138           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9139         result = IncompatibleObjCWeakRef;
9140       return result;
9141     }
9142 
9143     // int or null -> A*
9144     if (RHSType->isIntegerType()) {
9145       Kind = CK_IntegralToPointer; // FIXME: null
9146       return IntToPointer;
9147     }
9148 
9149     // In general, C pointers are not compatible with ObjC object pointers,
9150     // with two exceptions:
9151     if (isa<PointerType>(RHSType)) {
9152       Kind = CK_CPointerToObjCPointerCast;
9153 
9154       //  - conversions from 'void*'
9155       if (RHSType->isVoidPointerType()) {
9156         return Compatible;
9157       }
9158 
9159       //  - conversions to 'Class' from its redefinition type
9160       if (LHSType->isObjCClassType() &&
9161           Context.hasSameType(RHSType,
9162                               Context.getObjCClassRedefinitionType())) {
9163         return Compatible;
9164       }
9165 
9166       return IncompatiblePointer;
9167     }
9168 
9169     // Only under strict condition T^ is compatible with an Objective-C pointer.
9170     if (RHSType->isBlockPointerType() &&
9171         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9172       if (ConvertRHS)
9173         maybeExtendBlockObject(RHS);
9174       Kind = CK_BlockPointerToObjCPointerCast;
9175       return Compatible;
9176     }
9177 
9178     return Incompatible;
9179   }
9180 
9181   // Conversions from pointers that are not covered by the above.
9182   if (isa<PointerType>(RHSType)) {
9183     // T* -> _Bool
9184     if (LHSType == Context.BoolTy) {
9185       Kind = CK_PointerToBoolean;
9186       return Compatible;
9187     }
9188 
9189     // T* -> int
9190     if (LHSType->isIntegerType()) {
9191       Kind = CK_PointerToIntegral;
9192       return PointerToInt;
9193     }
9194 
9195     return Incompatible;
9196   }
9197 
9198   // Conversions from Objective-C pointers that are not covered by the above.
9199   if (isa<ObjCObjectPointerType>(RHSType)) {
9200     // T* -> _Bool
9201     if (LHSType == Context.BoolTy) {
9202       Kind = CK_PointerToBoolean;
9203       return Compatible;
9204     }
9205 
9206     // T* -> int
9207     if (LHSType->isIntegerType()) {
9208       Kind = CK_PointerToIntegral;
9209       return PointerToInt;
9210     }
9211 
9212     return Incompatible;
9213   }
9214 
9215   // struct A -> struct B
9216   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9217     if (Context.typesAreCompatible(LHSType, RHSType)) {
9218       Kind = CK_NoOp;
9219       return Compatible;
9220     }
9221   }
9222 
9223   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9224     Kind = CK_IntToOCLSampler;
9225     return Compatible;
9226   }
9227 
9228   return Incompatible;
9229 }
9230 
9231 /// Constructs a transparent union from an expression that is
9232 /// used to initialize the transparent union.
9233 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9234                                       ExprResult &EResult, QualType UnionType,
9235                                       FieldDecl *Field) {
9236   // Build an initializer list that designates the appropriate member
9237   // of the transparent union.
9238   Expr *E = EResult.get();
9239   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9240                                                    E, SourceLocation());
9241   Initializer->setType(UnionType);
9242   Initializer->setInitializedFieldInUnion(Field);
9243 
9244   // Build a compound literal constructing a value of the transparent
9245   // union type from this initializer list.
9246   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9247   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9248                                         VK_RValue, Initializer, false);
9249 }
9250 
9251 Sema::AssignConvertType
9252 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9253                                                ExprResult &RHS) {
9254   QualType RHSType = RHS.get()->getType();
9255 
9256   // If the ArgType is a Union type, we want to handle a potential
9257   // transparent_union GCC extension.
9258   const RecordType *UT = ArgType->getAsUnionType();
9259   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9260     return Incompatible;
9261 
9262   // The field to initialize within the transparent union.
9263   RecordDecl *UD = UT->getDecl();
9264   FieldDecl *InitField = nullptr;
9265   // It's compatible if the expression matches any of the fields.
9266   for (auto *it : UD->fields()) {
9267     if (it->getType()->isPointerType()) {
9268       // If the transparent union contains a pointer type, we allow:
9269       // 1) void pointer
9270       // 2) null pointer constant
9271       if (RHSType->isPointerType())
9272         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9273           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9274           InitField = it;
9275           break;
9276         }
9277 
9278       if (RHS.get()->isNullPointerConstant(Context,
9279                                            Expr::NPC_ValueDependentIsNull)) {
9280         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9281                                 CK_NullToPointer);
9282         InitField = it;
9283         break;
9284       }
9285     }
9286 
9287     CastKind Kind;
9288     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9289           == Compatible) {
9290       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9291       InitField = it;
9292       break;
9293     }
9294   }
9295 
9296   if (!InitField)
9297     return Incompatible;
9298 
9299   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9300   return Compatible;
9301 }
9302 
9303 Sema::AssignConvertType
9304 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9305                                        bool Diagnose,
9306                                        bool DiagnoseCFAudited,
9307                                        bool ConvertRHS) {
9308   // We need to be able to tell the caller whether we diagnosed a problem, if
9309   // they ask us to issue diagnostics.
9310   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9311 
9312   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9313   // we can't avoid *all* modifications at the moment, so we need some somewhere
9314   // to put the updated value.
9315   ExprResult LocalRHS = CallerRHS;
9316   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9317 
9318   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9319     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9320       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9321           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9322         Diag(RHS.get()->getExprLoc(),
9323              diag::warn_noderef_to_dereferenceable_pointer)
9324             << RHS.get()->getSourceRange();
9325       }
9326     }
9327   }
9328 
9329   if (getLangOpts().CPlusPlus) {
9330     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9331       // C++ 5.17p3: If the left operand is not of class type, the
9332       // expression is implicitly converted (C++ 4) to the
9333       // cv-unqualified type of the left operand.
9334       QualType RHSType = RHS.get()->getType();
9335       if (Diagnose) {
9336         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9337                                         AA_Assigning);
9338       } else {
9339         ImplicitConversionSequence ICS =
9340             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9341                                   /*SuppressUserConversions=*/false,
9342                                   AllowedExplicit::None,
9343                                   /*InOverloadResolution=*/false,
9344                                   /*CStyle=*/false,
9345                                   /*AllowObjCWritebackConversion=*/false);
9346         if (ICS.isFailure())
9347           return Incompatible;
9348         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9349                                         ICS, AA_Assigning);
9350       }
9351       if (RHS.isInvalid())
9352         return Incompatible;
9353       Sema::AssignConvertType result = Compatible;
9354       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9355           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9356         result = IncompatibleObjCWeakRef;
9357       return result;
9358     }
9359 
9360     // FIXME: Currently, we fall through and treat C++ classes like C
9361     // structures.
9362     // FIXME: We also fall through for atomics; not sure what should
9363     // happen there, though.
9364   } else if (RHS.get()->getType() == Context.OverloadTy) {
9365     // As a set of extensions to C, we support overloading on functions. These
9366     // functions need to be resolved here.
9367     DeclAccessPair DAP;
9368     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9369             RHS.get(), LHSType, /*Complain=*/false, DAP))
9370       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9371     else
9372       return Incompatible;
9373   }
9374 
9375   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9376   // a null pointer constant.
9377   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9378        LHSType->isBlockPointerType()) &&
9379       RHS.get()->isNullPointerConstant(Context,
9380                                        Expr::NPC_ValueDependentIsNull)) {
9381     if (Diagnose || ConvertRHS) {
9382       CastKind Kind;
9383       CXXCastPath Path;
9384       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9385                              /*IgnoreBaseAccess=*/false, Diagnose);
9386       if (ConvertRHS)
9387         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9388     }
9389     return Compatible;
9390   }
9391 
9392   // OpenCL queue_t type assignment.
9393   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9394                                  Context, Expr::NPC_ValueDependentIsNull)) {
9395     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9396     return Compatible;
9397   }
9398 
9399   // This check seems unnatural, however it is necessary to ensure the proper
9400   // conversion of functions/arrays. If the conversion were done for all
9401   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9402   // expressions that suppress this implicit conversion (&, sizeof).
9403   //
9404   // Suppress this for references: C++ 8.5.3p5.
9405   if (!LHSType->isReferenceType()) {
9406     // FIXME: We potentially allocate here even if ConvertRHS is false.
9407     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9408     if (RHS.isInvalid())
9409       return Incompatible;
9410   }
9411   CastKind Kind;
9412   Sema::AssignConvertType result =
9413     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9414 
9415   // C99 6.5.16.1p2: The value of the right operand is converted to the
9416   // type of the assignment expression.
9417   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9418   // so that we can use references in built-in functions even in C.
9419   // The getNonReferenceType() call makes sure that the resulting expression
9420   // does not have reference type.
9421   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9422     QualType Ty = LHSType.getNonLValueExprType(Context);
9423     Expr *E = RHS.get();
9424 
9425     // Check for various Objective-C errors. If we are not reporting
9426     // diagnostics and just checking for errors, e.g., during overload
9427     // resolution, return Incompatible to indicate the failure.
9428     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9429         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9430                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9431       if (!Diagnose)
9432         return Incompatible;
9433     }
9434     if (getLangOpts().ObjC &&
9435         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9436                                            E->getType(), E, Diagnose) ||
9437          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9438       if (!Diagnose)
9439         return Incompatible;
9440       // Replace the expression with a corrected version and continue so we
9441       // can find further errors.
9442       RHS = E;
9443       return Compatible;
9444     }
9445 
9446     if (ConvertRHS)
9447       RHS = ImpCastExprToType(E, Ty, Kind);
9448   }
9449 
9450   return result;
9451 }
9452 
9453 namespace {
9454 /// The original operand to an operator, prior to the application of the usual
9455 /// arithmetic conversions and converting the arguments of a builtin operator
9456 /// candidate.
9457 struct OriginalOperand {
9458   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9459     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9460       Op = MTE->getSubExpr();
9461     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9462       Op = BTE->getSubExpr();
9463     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9464       Orig = ICE->getSubExprAsWritten();
9465       Conversion = ICE->getConversionFunction();
9466     }
9467   }
9468 
9469   QualType getType() const { return Orig->getType(); }
9470 
9471   Expr *Orig;
9472   NamedDecl *Conversion;
9473 };
9474 }
9475 
9476 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9477                                ExprResult &RHS) {
9478   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9479 
9480   Diag(Loc, diag::err_typecheck_invalid_operands)
9481     << OrigLHS.getType() << OrigRHS.getType()
9482     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9483 
9484   // If a user-defined conversion was applied to either of the operands prior
9485   // to applying the built-in operator rules, tell the user about it.
9486   if (OrigLHS.Conversion) {
9487     Diag(OrigLHS.Conversion->getLocation(),
9488          diag::note_typecheck_invalid_operands_converted)
9489       << 0 << LHS.get()->getType();
9490   }
9491   if (OrigRHS.Conversion) {
9492     Diag(OrigRHS.Conversion->getLocation(),
9493          diag::note_typecheck_invalid_operands_converted)
9494       << 1 << RHS.get()->getType();
9495   }
9496 
9497   return QualType();
9498 }
9499 
9500 // Diagnose cases where a scalar was implicitly converted to a vector and
9501 // diagnose the underlying types. Otherwise, diagnose the error
9502 // as invalid vector logical operands for non-C++ cases.
9503 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9504                                             ExprResult &RHS) {
9505   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9506   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9507 
9508   bool LHSNatVec = LHSType->isVectorType();
9509   bool RHSNatVec = RHSType->isVectorType();
9510 
9511   if (!(LHSNatVec && RHSNatVec)) {
9512     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9513     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9514     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9515         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9516         << Vector->getSourceRange();
9517     return QualType();
9518   }
9519 
9520   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9521       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9522       << RHS.get()->getSourceRange();
9523 
9524   return QualType();
9525 }
9526 
9527 /// Try to convert a value of non-vector type to a vector type by converting
9528 /// the type to the element type of the vector and then performing a splat.
9529 /// If the language is OpenCL, we only use conversions that promote scalar
9530 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9531 /// for float->int.
9532 ///
9533 /// OpenCL V2.0 6.2.6.p2:
9534 /// An error shall occur if any scalar operand type has greater rank
9535 /// than the type of the vector element.
9536 ///
9537 /// \param scalar - if non-null, actually perform the conversions
9538 /// \return true if the operation fails (but without diagnosing the failure)
9539 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9540                                      QualType scalarTy,
9541                                      QualType vectorEltTy,
9542                                      QualType vectorTy,
9543                                      unsigned &DiagID) {
9544   // The conversion to apply to the scalar before splatting it,
9545   // if necessary.
9546   CastKind scalarCast = CK_NoOp;
9547 
9548   if (vectorEltTy->isIntegralType(S.Context)) {
9549     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9550         (scalarTy->isIntegerType() &&
9551          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9552       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9553       return true;
9554     }
9555     if (!scalarTy->isIntegralType(S.Context))
9556       return true;
9557     scalarCast = CK_IntegralCast;
9558   } else if (vectorEltTy->isRealFloatingType()) {
9559     if (scalarTy->isRealFloatingType()) {
9560       if (S.getLangOpts().OpenCL &&
9561           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9562         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9563         return true;
9564       }
9565       scalarCast = CK_FloatingCast;
9566     }
9567     else if (scalarTy->isIntegralType(S.Context))
9568       scalarCast = CK_IntegralToFloating;
9569     else
9570       return true;
9571   } else {
9572     return true;
9573   }
9574 
9575   // Adjust scalar if desired.
9576   if (scalar) {
9577     if (scalarCast != CK_NoOp)
9578       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9579     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9580   }
9581   return false;
9582 }
9583 
9584 /// Convert vector E to a vector with the same number of elements but different
9585 /// element type.
9586 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9587   const auto *VecTy = E->getType()->getAs<VectorType>();
9588   assert(VecTy && "Expression E must be a vector");
9589   QualType NewVecTy = S.Context.getVectorType(ElementType,
9590                                               VecTy->getNumElements(),
9591                                               VecTy->getVectorKind());
9592 
9593   // Look through the implicit cast. Return the subexpression if its type is
9594   // NewVecTy.
9595   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9596     if (ICE->getSubExpr()->getType() == NewVecTy)
9597       return ICE->getSubExpr();
9598 
9599   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9600   return S.ImpCastExprToType(E, NewVecTy, Cast);
9601 }
9602 
9603 /// Test if a (constant) integer Int can be casted to another integer type
9604 /// IntTy without losing precision.
9605 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9606                                       QualType OtherIntTy) {
9607   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9608 
9609   // Reject cases where the value of the Int is unknown as that would
9610   // possibly cause truncation, but accept cases where the scalar can be
9611   // demoted without loss of precision.
9612   Expr::EvalResult EVResult;
9613   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9614   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9615   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9616   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9617 
9618   if (CstInt) {
9619     // If the scalar is constant and is of a higher order and has more active
9620     // bits that the vector element type, reject it.
9621     llvm::APSInt Result = EVResult.Val.getInt();
9622     unsigned NumBits = IntSigned
9623                            ? (Result.isNegative() ? Result.getMinSignedBits()
9624                                                   : Result.getActiveBits())
9625                            : Result.getActiveBits();
9626     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9627       return true;
9628 
9629     // If the signedness of the scalar type and the vector element type
9630     // differs and the number of bits is greater than that of the vector
9631     // element reject it.
9632     return (IntSigned != OtherIntSigned &&
9633             NumBits > S.Context.getIntWidth(OtherIntTy));
9634   }
9635 
9636   // Reject cases where the value of the scalar is not constant and it's
9637   // order is greater than that of the vector element type.
9638   return (Order < 0);
9639 }
9640 
9641 /// Test if a (constant) integer Int can be casted to floating point type
9642 /// FloatTy without losing precision.
9643 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9644                                      QualType FloatTy) {
9645   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9646 
9647   // Determine if the integer constant can be expressed as a floating point
9648   // number of the appropriate type.
9649   Expr::EvalResult EVResult;
9650   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9651 
9652   uint64_t Bits = 0;
9653   if (CstInt) {
9654     // Reject constants that would be truncated if they were converted to
9655     // the floating point type. Test by simple to/from conversion.
9656     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9657     //        could be avoided if there was a convertFromAPInt method
9658     //        which could signal back if implicit truncation occurred.
9659     llvm::APSInt Result = EVResult.Val.getInt();
9660     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9661     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9662                            llvm::APFloat::rmTowardZero);
9663     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9664                              !IntTy->hasSignedIntegerRepresentation());
9665     bool Ignored = false;
9666     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9667                            &Ignored);
9668     if (Result != ConvertBack)
9669       return true;
9670   } else {
9671     // Reject types that cannot be fully encoded into the mantissa of
9672     // the float.
9673     Bits = S.Context.getTypeSize(IntTy);
9674     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9675         S.Context.getFloatTypeSemantics(FloatTy));
9676     if (Bits > FloatPrec)
9677       return true;
9678   }
9679 
9680   return false;
9681 }
9682 
9683 /// Attempt to convert and splat Scalar into a vector whose types matches
9684 /// Vector following GCC conversion rules. The rule is that implicit
9685 /// conversion can occur when Scalar can be casted to match Vector's element
9686 /// type without causing truncation of Scalar.
9687 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9688                                         ExprResult *Vector) {
9689   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9690   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9691   const VectorType *VT = VectorTy->getAs<VectorType>();
9692 
9693   assert(!isa<ExtVectorType>(VT) &&
9694          "ExtVectorTypes should not be handled here!");
9695 
9696   QualType VectorEltTy = VT->getElementType();
9697 
9698   // Reject cases where the vector element type or the scalar element type are
9699   // not integral or floating point types.
9700   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9701     return true;
9702 
9703   // The conversion to apply to the scalar before splatting it,
9704   // if necessary.
9705   CastKind ScalarCast = CK_NoOp;
9706 
9707   // Accept cases where the vector elements are integers and the scalar is
9708   // an integer.
9709   // FIXME: Notionally if the scalar was a floating point value with a precise
9710   //        integral representation, we could cast it to an appropriate integer
9711   //        type and then perform the rest of the checks here. GCC will perform
9712   //        this conversion in some cases as determined by the input language.
9713   //        We should accept it on a language independent basis.
9714   if (VectorEltTy->isIntegralType(S.Context) &&
9715       ScalarTy->isIntegralType(S.Context) &&
9716       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9717 
9718     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9719       return true;
9720 
9721     ScalarCast = CK_IntegralCast;
9722   } else if (VectorEltTy->isIntegralType(S.Context) &&
9723              ScalarTy->isRealFloatingType()) {
9724     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9725       ScalarCast = CK_FloatingToIntegral;
9726     else
9727       return true;
9728   } else if (VectorEltTy->isRealFloatingType()) {
9729     if (ScalarTy->isRealFloatingType()) {
9730 
9731       // Reject cases where the scalar type is not a constant and has a higher
9732       // Order than the vector element type.
9733       llvm::APFloat Result(0.0);
9734 
9735       // Determine whether this is a constant scalar. In the event that the
9736       // value is dependent (and thus cannot be evaluated by the constant
9737       // evaluator), skip the evaluation. This will then diagnose once the
9738       // expression is instantiated.
9739       bool CstScalar = Scalar->get()->isValueDependent() ||
9740                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9741       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9742       if (!CstScalar && Order < 0)
9743         return true;
9744 
9745       // If the scalar cannot be safely casted to the vector element type,
9746       // reject it.
9747       if (CstScalar) {
9748         bool Truncated = false;
9749         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9750                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9751         if (Truncated)
9752           return true;
9753       }
9754 
9755       ScalarCast = CK_FloatingCast;
9756     } else if (ScalarTy->isIntegralType(S.Context)) {
9757       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9758         return true;
9759 
9760       ScalarCast = CK_IntegralToFloating;
9761     } else
9762       return true;
9763   } else if (ScalarTy->isEnumeralType())
9764     return true;
9765 
9766   // Adjust scalar if desired.
9767   if (Scalar) {
9768     if (ScalarCast != CK_NoOp)
9769       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9770     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9771   }
9772   return false;
9773 }
9774 
9775 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9776                                    SourceLocation Loc, bool IsCompAssign,
9777                                    bool AllowBothBool,
9778                                    bool AllowBoolConversions) {
9779   if (!IsCompAssign) {
9780     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9781     if (LHS.isInvalid())
9782       return QualType();
9783   }
9784   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9785   if (RHS.isInvalid())
9786     return QualType();
9787 
9788   // For conversion purposes, we ignore any qualifiers.
9789   // For example, "const float" and "float" are equivalent.
9790   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9791   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9792 
9793   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9794   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9795   assert(LHSVecType || RHSVecType);
9796 
9797   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
9798       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
9799     return InvalidOperands(Loc, LHS, RHS);
9800 
9801   // AltiVec-style "vector bool op vector bool" combinations are allowed
9802   // for some operators but not others.
9803   if (!AllowBothBool &&
9804       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9805       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9806     return InvalidOperands(Loc, LHS, RHS);
9807 
9808   // If the vector types are identical, return.
9809   if (Context.hasSameType(LHSType, RHSType))
9810     return LHSType;
9811 
9812   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9813   if (LHSVecType && RHSVecType &&
9814       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9815     if (isa<ExtVectorType>(LHSVecType)) {
9816       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9817       return LHSType;
9818     }
9819 
9820     if (!IsCompAssign)
9821       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9822     return RHSType;
9823   }
9824 
9825   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9826   // can be mixed, with the result being the non-bool type.  The non-bool
9827   // operand must have integer element type.
9828   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9829       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9830       (Context.getTypeSize(LHSVecType->getElementType()) ==
9831        Context.getTypeSize(RHSVecType->getElementType()))) {
9832     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9833         LHSVecType->getElementType()->isIntegerType() &&
9834         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9835       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9836       return LHSType;
9837     }
9838     if (!IsCompAssign &&
9839         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9840         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9841         RHSVecType->getElementType()->isIntegerType()) {
9842       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9843       return RHSType;
9844     }
9845   }
9846 
9847   // Expressions containing fixed-length and sizeless SVE vectors are invalid
9848   // since the ambiguity can affect the ABI.
9849   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
9850     const VectorType *VecType = SecondType->getAs<VectorType>();
9851     return FirstType->isSizelessBuiltinType() && VecType &&
9852            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
9853             VecType->getVectorKind() ==
9854                 VectorType::SveFixedLengthPredicateVector);
9855   };
9856 
9857   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
9858     Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
9859     return QualType();
9860   }
9861 
9862   // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
9863   // since the ambiguity can affect the ABI.
9864   auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
9865     const VectorType *FirstVecType = FirstType->getAs<VectorType>();
9866     const VectorType *SecondVecType = SecondType->getAs<VectorType>();
9867 
9868     if (FirstVecType && SecondVecType)
9869       return FirstVecType->getVectorKind() == VectorType::GenericVector &&
9870              (SecondVecType->getVectorKind() ==
9871                   VectorType::SveFixedLengthDataVector ||
9872               SecondVecType->getVectorKind() ==
9873                   VectorType::SveFixedLengthPredicateVector);
9874 
9875     return FirstType->isSizelessBuiltinType() && SecondVecType &&
9876            SecondVecType->getVectorKind() == VectorType::GenericVector;
9877   };
9878 
9879   if (IsSveGnuConversion(LHSType, RHSType) ||
9880       IsSveGnuConversion(RHSType, LHSType)) {
9881     Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
9882     return QualType();
9883   }
9884 
9885   // If there's a vector type and a scalar, try to convert the scalar to
9886   // the vector element type and splat.
9887   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9888   if (!RHSVecType) {
9889     if (isa<ExtVectorType>(LHSVecType)) {
9890       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9891                                     LHSVecType->getElementType(), LHSType,
9892                                     DiagID))
9893         return LHSType;
9894     } else {
9895       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9896         return LHSType;
9897     }
9898   }
9899   if (!LHSVecType) {
9900     if (isa<ExtVectorType>(RHSVecType)) {
9901       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9902                                     LHSType, RHSVecType->getElementType(),
9903                                     RHSType, DiagID))
9904         return RHSType;
9905     } else {
9906       if (LHS.get()->getValueKind() == VK_LValue ||
9907           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9908         return RHSType;
9909     }
9910   }
9911 
9912   // FIXME: The code below also handles conversion between vectors and
9913   // non-scalars, we should break this down into fine grained specific checks
9914   // and emit proper diagnostics.
9915   QualType VecType = LHSVecType ? LHSType : RHSType;
9916   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9917   QualType OtherType = LHSVecType ? RHSType : LHSType;
9918   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9919   if (isLaxVectorConversion(OtherType, VecType)) {
9920     // If we're allowing lax vector conversions, only the total (data) size
9921     // needs to be the same. For non compound assignment, if one of the types is
9922     // scalar, the result is always the vector type.
9923     if (!IsCompAssign) {
9924       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9925       return VecType;
9926     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9927     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9928     // type. Note that this is already done by non-compound assignments in
9929     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9930     // <1 x T> -> T. The result is also a vector type.
9931     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9932                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9933       ExprResult *RHSExpr = &RHS;
9934       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9935       return VecType;
9936     }
9937   }
9938 
9939   // Okay, the expression is invalid.
9940 
9941   // If there's a non-vector, non-real operand, diagnose that.
9942   if ((!RHSVecType && !RHSType->isRealType()) ||
9943       (!LHSVecType && !LHSType->isRealType())) {
9944     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9945       << LHSType << RHSType
9946       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9947     return QualType();
9948   }
9949 
9950   // OpenCL V1.1 6.2.6.p1:
9951   // If the operands are of more than one vector type, then an error shall
9952   // occur. Implicit conversions between vector types are not permitted, per
9953   // section 6.2.1.
9954   if (getLangOpts().OpenCL &&
9955       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9956       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9957     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9958                                                            << RHSType;
9959     return QualType();
9960   }
9961 
9962 
9963   // If there is a vector type that is not a ExtVector and a scalar, we reach
9964   // this point if scalar could not be converted to the vector's element type
9965   // without truncation.
9966   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9967       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9968     QualType Scalar = LHSVecType ? RHSType : LHSType;
9969     QualType Vector = LHSVecType ? LHSType : RHSType;
9970     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9971     Diag(Loc,
9972          diag::err_typecheck_vector_not_convertable_implict_truncation)
9973         << ScalarOrVector << Scalar << Vector;
9974 
9975     return QualType();
9976   }
9977 
9978   // Otherwise, use the generic diagnostic.
9979   Diag(Loc, DiagID)
9980     << LHSType << RHSType
9981     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9982   return QualType();
9983 }
9984 
9985 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9986 // expression.  These are mainly cases where the null pointer is used as an
9987 // integer instead of a pointer.
9988 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9989                                 SourceLocation Loc, bool IsCompare) {
9990   // The canonical way to check for a GNU null is with isNullPointerConstant,
9991   // but we use a bit of a hack here for speed; this is a relatively
9992   // hot path, and isNullPointerConstant is slow.
9993   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9994   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9995 
9996   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9997 
9998   // Avoid analyzing cases where the result will either be invalid (and
9999   // diagnosed as such) or entirely valid and not something to warn about.
10000   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10001       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10002     return;
10003 
10004   // Comparison operations would not make sense with a null pointer no matter
10005   // what the other expression is.
10006   if (!IsCompare) {
10007     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10008         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10009         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10010     return;
10011   }
10012 
10013   // The rest of the operations only make sense with a null pointer
10014   // if the other expression is a pointer.
10015   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10016       NonNullType->canDecayToPointerType())
10017     return;
10018 
10019   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10020       << LHSNull /* LHS is NULL */ << NonNullType
10021       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10022 }
10023 
10024 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10025                                           SourceLocation Loc) {
10026   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10027   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10028   if (!LUE || !RUE)
10029     return;
10030   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10031       RUE->getKind() != UETT_SizeOf)
10032     return;
10033 
10034   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10035   QualType LHSTy = LHSArg->getType();
10036   QualType RHSTy;
10037 
10038   if (RUE->isArgumentType())
10039     RHSTy = RUE->getArgumentType().getNonReferenceType();
10040   else
10041     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10042 
10043   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10044     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10045       return;
10046 
10047     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10048     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10049       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10050         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10051             << LHSArgDecl;
10052     }
10053   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10054     QualType ArrayElemTy = ArrayTy->getElementType();
10055     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10056         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10057         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10058         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10059       return;
10060     S.Diag(Loc, diag::warn_division_sizeof_array)
10061         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10062     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10063       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10064         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10065             << LHSArgDecl;
10066     }
10067 
10068     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10069   }
10070 }
10071 
10072 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10073                                                ExprResult &RHS,
10074                                                SourceLocation Loc, bool IsDiv) {
10075   // Check for division/remainder by zero.
10076   Expr::EvalResult RHSValue;
10077   if (!RHS.get()->isValueDependent() &&
10078       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10079       RHSValue.Val.getInt() == 0)
10080     S.DiagRuntimeBehavior(Loc, RHS.get(),
10081                           S.PDiag(diag::warn_remainder_division_by_zero)
10082                             << IsDiv << RHS.get()->getSourceRange());
10083 }
10084 
10085 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10086                                            SourceLocation Loc,
10087                                            bool IsCompAssign, bool IsDiv) {
10088   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10089 
10090   if (LHS.get()->getType()->isVectorType() ||
10091       RHS.get()->getType()->isVectorType())
10092     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10093                                /*AllowBothBool*/getLangOpts().AltiVec,
10094                                /*AllowBoolConversions*/false);
10095   if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10096                  RHS.get()->getType()->isConstantMatrixType()))
10097     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10098 
10099   QualType compType = UsualArithmeticConversions(
10100       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10101   if (LHS.isInvalid() || RHS.isInvalid())
10102     return QualType();
10103 
10104 
10105   if (compType.isNull() || !compType->isArithmeticType())
10106     return InvalidOperands(Loc, LHS, RHS);
10107   if (IsDiv) {
10108     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10109     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10110   }
10111   return compType;
10112 }
10113 
10114 QualType Sema::CheckRemainderOperands(
10115   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10116   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10117 
10118   if (LHS.get()->getType()->isVectorType() ||
10119       RHS.get()->getType()->isVectorType()) {
10120     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10121         RHS.get()->getType()->hasIntegerRepresentation())
10122       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10123                                  /*AllowBothBool*/getLangOpts().AltiVec,
10124                                  /*AllowBoolConversions*/false);
10125     return InvalidOperands(Loc, LHS, RHS);
10126   }
10127 
10128   QualType compType = UsualArithmeticConversions(
10129       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10130   if (LHS.isInvalid() || RHS.isInvalid())
10131     return QualType();
10132 
10133   if (compType.isNull() || !compType->isIntegerType())
10134     return InvalidOperands(Loc, LHS, RHS);
10135   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10136   return compType;
10137 }
10138 
10139 /// Diagnose invalid arithmetic on two void pointers.
10140 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10141                                                 Expr *LHSExpr, Expr *RHSExpr) {
10142   S.Diag(Loc, S.getLangOpts().CPlusPlus
10143                 ? diag::err_typecheck_pointer_arith_void_type
10144                 : diag::ext_gnu_void_ptr)
10145     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10146                             << RHSExpr->getSourceRange();
10147 }
10148 
10149 /// Diagnose invalid arithmetic on a void pointer.
10150 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10151                                             Expr *Pointer) {
10152   S.Diag(Loc, S.getLangOpts().CPlusPlus
10153                 ? diag::err_typecheck_pointer_arith_void_type
10154                 : diag::ext_gnu_void_ptr)
10155     << 0 /* one pointer */ << Pointer->getSourceRange();
10156 }
10157 
10158 /// Diagnose invalid arithmetic on a null pointer.
10159 ///
10160 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10161 /// idiom, which we recognize as a GNU extension.
10162 ///
10163 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10164                                             Expr *Pointer, bool IsGNUIdiom) {
10165   if (IsGNUIdiom)
10166     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10167       << Pointer->getSourceRange();
10168   else
10169     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10170       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10171 }
10172 
10173 /// Diagnose invalid arithmetic on two function pointers.
10174 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10175                                                     Expr *LHS, Expr *RHS) {
10176   assert(LHS->getType()->isAnyPointerType());
10177   assert(RHS->getType()->isAnyPointerType());
10178   S.Diag(Loc, S.getLangOpts().CPlusPlus
10179                 ? diag::err_typecheck_pointer_arith_function_type
10180                 : diag::ext_gnu_ptr_func_arith)
10181     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10182     // We only show the second type if it differs from the first.
10183     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10184                                                    RHS->getType())
10185     << RHS->getType()->getPointeeType()
10186     << LHS->getSourceRange() << RHS->getSourceRange();
10187 }
10188 
10189 /// Diagnose invalid arithmetic on a function pointer.
10190 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10191                                                 Expr *Pointer) {
10192   assert(Pointer->getType()->isAnyPointerType());
10193   S.Diag(Loc, S.getLangOpts().CPlusPlus
10194                 ? diag::err_typecheck_pointer_arith_function_type
10195                 : diag::ext_gnu_ptr_func_arith)
10196     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10197     << 0 /* one pointer, so only one type */
10198     << Pointer->getSourceRange();
10199 }
10200 
10201 /// Emit error if Operand is incomplete pointer type
10202 ///
10203 /// \returns True if pointer has incomplete type
10204 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10205                                                  Expr *Operand) {
10206   QualType ResType = Operand->getType();
10207   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10208     ResType = ResAtomicType->getValueType();
10209 
10210   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10211   QualType PointeeTy = ResType->getPointeeType();
10212   return S.RequireCompleteSizedType(
10213       Loc, PointeeTy,
10214       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10215       Operand->getSourceRange());
10216 }
10217 
10218 /// Check the validity of an arithmetic pointer operand.
10219 ///
10220 /// If the operand has pointer type, this code will check for pointer types
10221 /// which are invalid in arithmetic operations. These will be diagnosed
10222 /// appropriately, including whether or not the use is supported as an
10223 /// extension.
10224 ///
10225 /// \returns True when the operand is valid to use (even if as an extension).
10226 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10227                                             Expr *Operand) {
10228   QualType ResType = Operand->getType();
10229   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10230     ResType = ResAtomicType->getValueType();
10231 
10232   if (!ResType->isAnyPointerType()) return true;
10233 
10234   QualType PointeeTy = ResType->getPointeeType();
10235   if (PointeeTy->isVoidType()) {
10236     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10237     return !S.getLangOpts().CPlusPlus;
10238   }
10239   if (PointeeTy->isFunctionType()) {
10240     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10241     return !S.getLangOpts().CPlusPlus;
10242   }
10243 
10244   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10245 
10246   return true;
10247 }
10248 
10249 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10250 /// operands.
10251 ///
10252 /// This routine will diagnose any invalid arithmetic on pointer operands much
10253 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10254 /// for emitting a single diagnostic even for operations where both LHS and RHS
10255 /// are (potentially problematic) pointers.
10256 ///
10257 /// \returns True when the operand is valid to use (even if as an extension).
10258 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10259                                                 Expr *LHSExpr, Expr *RHSExpr) {
10260   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10261   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10262   if (!isLHSPointer && !isRHSPointer) return true;
10263 
10264   QualType LHSPointeeTy, RHSPointeeTy;
10265   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10266   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10267 
10268   // if both are pointers check if operation is valid wrt address spaces
10269   if (isLHSPointer && isRHSPointer) {
10270     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10271       S.Diag(Loc,
10272              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10273           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10274           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10275       return false;
10276     }
10277   }
10278 
10279   // Check for arithmetic on pointers to incomplete types.
10280   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10281   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10282   if (isLHSVoidPtr || isRHSVoidPtr) {
10283     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10284     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10285     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10286 
10287     return !S.getLangOpts().CPlusPlus;
10288   }
10289 
10290   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10291   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10292   if (isLHSFuncPtr || isRHSFuncPtr) {
10293     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10294     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10295                                                                 RHSExpr);
10296     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10297 
10298     return !S.getLangOpts().CPlusPlus;
10299   }
10300 
10301   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10302     return false;
10303   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10304     return false;
10305 
10306   return true;
10307 }
10308 
10309 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10310 /// literal.
10311 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10312                                   Expr *LHSExpr, Expr *RHSExpr) {
10313   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10314   Expr* IndexExpr = RHSExpr;
10315   if (!StrExpr) {
10316     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10317     IndexExpr = LHSExpr;
10318   }
10319 
10320   bool IsStringPlusInt = StrExpr &&
10321       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10322   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10323     return;
10324 
10325   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10326   Self.Diag(OpLoc, diag::warn_string_plus_int)
10327       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10328 
10329   // Only print a fixit for "str" + int, not for int + "str".
10330   if (IndexExpr == RHSExpr) {
10331     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10332     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10333         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10334         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10335         << FixItHint::CreateInsertion(EndLoc, "]");
10336   } else
10337     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10338 }
10339 
10340 /// Emit a warning when adding a char literal to a string.
10341 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10342                                    Expr *LHSExpr, Expr *RHSExpr) {
10343   const Expr *StringRefExpr = LHSExpr;
10344   const CharacterLiteral *CharExpr =
10345       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10346 
10347   if (!CharExpr) {
10348     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10349     StringRefExpr = RHSExpr;
10350   }
10351 
10352   if (!CharExpr || !StringRefExpr)
10353     return;
10354 
10355   const QualType StringType = StringRefExpr->getType();
10356 
10357   // Return if not a PointerType.
10358   if (!StringType->isAnyPointerType())
10359     return;
10360 
10361   // Return if not a CharacterType.
10362   if (!StringType->getPointeeType()->isAnyCharacterType())
10363     return;
10364 
10365   ASTContext &Ctx = Self.getASTContext();
10366   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10367 
10368   const QualType CharType = CharExpr->getType();
10369   if (!CharType->isAnyCharacterType() &&
10370       CharType->isIntegerType() &&
10371       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10372     Self.Diag(OpLoc, diag::warn_string_plus_char)
10373         << DiagRange << Ctx.CharTy;
10374   } else {
10375     Self.Diag(OpLoc, diag::warn_string_plus_char)
10376         << DiagRange << CharExpr->getType();
10377   }
10378 
10379   // Only print a fixit for str + char, not for char + str.
10380   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10381     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10382     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10383         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10384         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10385         << FixItHint::CreateInsertion(EndLoc, "]");
10386   } else {
10387     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10388   }
10389 }
10390 
10391 /// Emit error when two pointers are incompatible.
10392 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10393                                            Expr *LHSExpr, Expr *RHSExpr) {
10394   assert(LHSExpr->getType()->isAnyPointerType());
10395   assert(RHSExpr->getType()->isAnyPointerType());
10396   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10397     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10398     << RHSExpr->getSourceRange();
10399 }
10400 
10401 // C99 6.5.6
10402 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10403                                      SourceLocation Loc, BinaryOperatorKind Opc,
10404                                      QualType* CompLHSTy) {
10405   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10406 
10407   if (LHS.get()->getType()->isVectorType() ||
10408       RHS.get()->getType()->isVectorType()) {
10409     QualType compType = CheckVectorOperands(
10410         LHS, RHS, Loc, CompLHSTy,
10411         /*AllowBothBool*/getLangOpts().AltiVec,
10412         /*AllowBoolConversions*/getLangOpts().ZVector);
10413     if (CompLHSTy) *CompLHSTy = compType;
10414     return compType;
10415   }
10416 
10417   if (LHS.get()->getType()->isConstantMatrixType() ||
10418       RHS.get()->getType()->isConstantMatrixType()) {
10419     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10420   }
10421 
10422   QualType compType = UsualArithmeticConversions(
10423       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10424   if (LHS.isInvalid() || RHS.isInvalid())
10425     return QualType();
10426 
10427   // Diagnose "string literal" '+' int and string '+' "char literal".
10428   if (Opc == BO_Add) {
10429     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10430     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10431   }
10432 
10433   // handle the common case first (both operands are arithmetic).
10434   if (!compType.isNull() && compType->isArithmeticType()) {
10435     if (CompLHSTy) *CompLHSTy = compType;
10436     return compType;
10437   }
10438 
10439   // Type-checking.  Ultimately the pointer's going to be in PExp;
10440   // note that we bias towards the LHS being the pointer.
10441   Expr *PExp = LHS.get(), *IExp = RHS.get();
10442 
10443   bool isObjCPointer;
10444   if (PExp->getType()->isPointerType()) {
10445     isObjCPointer = false;
10446   } else if (PExp->getType()->isObjCObjectPointerType()) {
10447     isObjCPointer = true;
10448   } else {
10449     std::swap(PExp, IExp);
10450     if (PExp->getType()->isPointerType()) {
10451       isObjCPointer = false;
10452     } else if (PExp->getType()->isObjCObjectPointerType()) {
10453       isObjCPointer = true;
10454     } else {
10455       return InvalidOperands(Loc, LHS, RHS);
10456     }
10457   }
10458   assert(PExp->getType()->isAnyPointerType());
10459 
10460   if (!IExp->getType()->isIntegerType())
10461     return InvalidOperands(Loc, LHS, RHS);
10462 
10463   // Adding to a null pointer results in undefined behavior.
10464   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10465           Context, Expr::NPC_ValueDependentIsNotNull)) {
10466     // In C++ adding zero to a null pointer is defined.
10467     Expr::EvalResult KnownVal;
10468     if (!getLangOpts().CPlusPlus ||
10469         (!IExp->isValueDependent() &&
10470          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10471           KnownVal.Val.getInt() != 0))) {
10472       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10473       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10474           Context, BO_Add, PExp, IExp);
10475       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10476     }
10477   }
10478 
10479   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10480     return QualType();
10481 
10482   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10483     return QualType();
10484 
10485   // Check array bounds for pointer arithemtic
10486   CheckArrayAccess(PExp, IExp);
10487 
10488   if (CompLHSTy) {
10489     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10490     if (LHSTy.isNull()) {
10491       LHSTy = LHS.get()->getType();
10492       if (LHSTy->isPromotableIntegerType())
10493         LHSTy = Context.getPromotedIntegerType(LHSTy);
10494     }
10495     *CompLHSTy = LHSTy;
10496   }
10497 
10498   return PExp->getType();
10499 }
10500 
10501 // C99 6.5.6
10502 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10503                                         SourceLocation Loc,
10504                                         QualType* CompLHSTy) {
10505   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10506 
10507   if (LHS.get()->getType()->isVectorType() ||
10508       RHS.get()->getType()->isVectorType()) {
10509     QualType compType = CheckVectorOperands(
10510         LHS, RHS, Loc, CompLHSTy,
10511         /*AllowBothBool*/getLangOpts().AltiVec,
10512         /*AllowBoolConversions*/getLangOpts().ZVector);
10513     if (CompLHSTy) *CompLHSTy = compType;
10514     return compType;
10515   }
10516 
10517   if (LHS.get()->getType()->isConstantMatrixType() ||
10518       RHS.get()->getType()->isConstantMatrixType()) {
10519     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10520   }
10521 
10522   QualType compType = UsualArithmeticConversions(
10523       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10524   if (LHS.isInvalid() || RHS.isInvalid())
10525     return QualType();
10526 
10527   // Enforce type constraints: C99 6.5.6p3.
10528 
10529   // Handle the common case first (both operands are arithmetic).
10530   if (!compType.isNull() && compType->isArithmeticType()) {
10531     if (CompLHSTy) *CompLHSTy = compType;
10532     return compType;
10533   }
10534 
10535   // Either ptr - int   or   ptr - ptr.
10536   if (LHS.get()->getType()->isAnyPointerType()) {
10537     QualType lpointee = LHS.get()->getType()->getPointeeType();
10538 
10539     // Diagnose bad cases where we step over interface counts.
10540     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10541         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10542       return QualType();
10543 
10544     // The result type of a pointer-int computation is the pointer type.
10545     if (RHS.get()->getType()->isIntegerType()) {
10546       // Subtracting from a null pointer should produce a warning.
10547       // The last argument to the diagnose call says this doesn't match the
10548       // GNU int-to-pointer idiom.
10549       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10550                                            Expr::NPC_ValueDependentIsNotNull)) {
10551         // In C++ adding zero to a null pointer is defined.
10552         Expr::EvalResult KnownVal;
10553         if (!getLangOpts().CPlusPlus ||
10554             (!RHS.get()->isValueDependent() &&
10555              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10556               KnownVal.Val.getInt() != 0))) {
10557           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10558         }
10559       }
10560 
10561       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10562         return QualType();
10563 
10564       // Check array bounds for pointer arithemtic
10565       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10566                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10567 
10568       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10569       return LHS.get()->getType();
10570     }
10571 
10572     // Handle pointer-pointer subtractions.
10573     if (const PointerType *RHSPTy
10574           = RHS.get()->getType()->getAs<PointerType>()) {
10575       QualType rpointee = RHSPTy->getPointeeType();
10576 
10577       if (getLangOpts().CPlusPlus) {
10578         // Pointee types must be the same: C++ [expr.add]
10579         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10580           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10581         }
10582       } else {
10583         // Pointee types must be compatible C99 6.5.6p3
10584         if (!Context.typesAreCompatible(
10585                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10586                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10587           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10588           return QualType();
10589         }
10590       }
10591 
10592       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10593                                                LHS.get(), RHS.get()))
10594         return QualType();
10595 
10596       // FIXME: Add warnings for nullptr - ptr.
10597 
10598       // The pointee type may have zero size.  As an extension, a structure or
10599       // union may have zero size or an array may have zero length.  In this
10600       // case subtraction does not make sense.
10601       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10602         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10603         if (ElementSize.isZero()) {
10604           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10605             << rpointee.getUnqualifiedType()
10606             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10607         }
10608       }
10609 
10610       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10611       return Context.getPointerDiffType();
10612     }
10613   }
10614 
10615   return InvalidOperands(Loc, LHS, RHS);
10616 }
10617 
10618 static bool isScopedEnumerationType(QualType T) {
10619   if (const EnumType *ET = T->getAs<EnumType>())
10620     return ET->getDecl()->isScoped();
10621   return false;
10622 }
10623 
10624 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10625                                    SourceLocation Loc, BinaryOperatorKind Opc,
10626                                    QualType LHSType) {
10627   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10628   // so skip remaining warnings as we don't want to modify values within Sema.
10629   if (S.getLangOpts().OpenCL)
10630     return;
10631 
10632   // Check right/shifter operand
10633   Expr::EvalResult RHSResult;
10634   if (RHS.get()->isValueDependent() ||
10635       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10636     return;
10637   llvm::APSInt Right = RHSResult.Val.getInt();
10638 
10639   if (Right.isNegative()) {
10640     S.DiagRuntimeBehavior(Loc, RHS.get(),
10641                           S.PDiag(diag::warn_shift_negative)
10642                             << RHS.get()->getSourceRange());
10643     return;
10644   }
10645 
10646   QualType LHSExprType = LHS.get()->getType();
10647   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
10648   if (LHSExprType->isExtIntType())
10649     LeftSize = S.Context.getIntWidth(LHSExprType);
10650   else if (LHSExprType->isFixedPointType()) {
10651     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
10652     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
10653   }
10654   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10655   if (Right.uge(LeftBits)) {
10656     S.DiagRuntimeBehavior(Loc, RHS.get(),
10657                           S.PDiag(diag::warn_shift_gt_typewidth)
10658                             << RHS.get()->getSourceRange());
10659     return;
10660   }
10661 
10662   // FIXME: We probably need to handle fixed point types specially here.
10663   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
10664     return;
10665 
10666   // When left shifting an ICE which is signed, we can check for overflow which
10667   // according to C++ standards prior to C++2a has undefined behavior
10668   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10669   // more than the maximum value representable in the result type, so never
10670   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10671   // expression is still probably a bug.)
10672   Expr::EvalResult LHSResult;
10673   if (LHS.get()->isValueDependent() ||
10674       LHSType->hasUnsignedIntegerRepresentation() ||
10675       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10676     return;
10677   llvm::APSInt Left = LHSResult.Val.getInt();
10678 
10679   // If LHS does not have a signed type and non-negative value
10680   // then, the behavior is undefined before C++2a. Warn about it.
10681   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10682       !S.getLangOpts().CPlusPlus20) {
10683     S.DiagRuntimeBehavior(Loc, LHS.get(),
10684                           S.PDiag(diag::warn_shift_lhs_negative)
10685                             << LHS.get()->getSourceRange());
10686     return;
10687   }
10688 
10689   llvm::APInt ResultBits =
10690       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10691   if (LeftBits.uge(ResultBits))
10692     return;
10693   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10694   Result = Result.shl(Right);
10695 
10696   // Print the bit representation of the signed integer as an unsigned
10697   // hexadecimal number.
10698   SmallString<40> HexResult;
10699   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10700 
10701   // If we are only missing a sign bit, this is less likely to result in actual
10702   // bugs -- if the result is cast back to an unsigned type, it will have the
10703   // expected value. Thus we place this behind a different warning that can be
10704   // turned off separately if needed.
10705   if (LeftBits == ResultBits - 1) {
10706     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10707         << HexResult << LHSType
10708         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10709     return;
10710   }
10711 
10712   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10713     << HexResult.str() << Result.getMinSignedBits() << LHSType
10714     << Left.getBitWidth() << LHS.get()->getSourceRange()
10715     << RHS.get()->getSourceRange();
10716 }
10717 
10718 /// Return the resulting type when a vector is shifted
10719 ///        by a scalar or vector shift amount.
10720 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10721                                  SourceLocation Loc, bool IsCompAssign) {
10722   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10723   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10724       !LHS.get()->getType()->isVectorType()) {
10725     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10726       << RHS.get()->getType() << LHS.get()->getType()
10727       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10728     return QualType();
10729   }
10730 
10731   if (!IsCompAssign) {
10732     LHS = S.UsualUnaryConversions(LHS.get());
10733     if (LHS.isInvalid()) return QualType();
10734   }
10735 
10736   RHS = S.UsualUnaryConversions(RHS.get());
10737   if (RHS.isInvalid()) return QualType();
10738 
10739   QualType LHSType = LHS.get()->getType();
10740   // Note that LHS might be a scalar because the routine calls not only in
10741   // OpenCL case.
10742   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10743   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10744 
10745   // Note that RHS might not be a vector.
10746   QualType RHSType = RHS.get()->getType();
10747   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10748   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10749 
10750   // The operands need to be integers.
10751   if (!LHSEleType->isIntegerType()) {
10752     S.Diag(Loc, diag::err_typecheck_expect_int)
10753       << LHS.get()->getType() << LHS.get()->getSourceRange();
10754     return QualType();
10755   }
10756 
10757   if (!RHSEleType->isIntegerType()) {
10758     S.Diag(Loc, diag::err_typecheck_expect_int)
10759       << RHS.get()->getType() << RHS.get()->getSourceRange();
10760     return QualType();
10761   }
10762 
10763   if (!LHSVecTy) {
10764     assert(RHSVecTy);
10765     if (IsCompAssign)
10766       return RHSType;
10767     if (LHSEleType != RHSEleType) {
10768       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10769       LHSEleType = RHSEleType;
10770     }
10771     QualType VecTy =
10772         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10773     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10774     LHSType = VecTy;
10775   } else if (RHSVecTy) {
10776     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10777     // are applied component-wise. So if RHS is a vector, then ensure
10778     // that the number of elements is the same as LHS...
10779     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10780       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10781         << LHS.get()->getType() << RHS.get()->getType()
10782         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10783       return QualType();
10784     }
10785     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10786       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10787       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10788       if (LHSBT != RHSBT &&
10789           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10790         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10791             << LHS.get()->getType() << RHS.get()->getType()
10792             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10793       }
10794     }
10795   } else {
10796     // ...else expand RHS to match the number of elements in LHS.
10797     QualType VecTy =
10798       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10799     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10800   }
10801 
10802   return LHSType;
10803 }
10804 
10805 // C99 6.5.7
10806 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10807                                   SourceLocation Loc, BinaryOperatorKind Opc,
10808                                   bool IsCompAssign) {
10809   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10810 
10811   // Vector shifts promote their scalar inputs to vector type.
10812   if (LHS.get()->getType()->isVectorType() ||
10813       RHS.get()->getType()->isVectorType()) {
10814     if (LangOpts.ZVector) {
10815       // The shift operators for the z vector extensions work basically
10816       // like general shifts, except that neither the LHS nor the RHS is
10817       // allowed to be a "vector bool".
10818       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10819         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10820           return InvalidOperands(Loc, LHS, RHS);
10821       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10822         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10823           return InvalidOperands(Loc, LHS, RHS);
10824     }
10825     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10826   }
10827 
10828   // Shifts don't perform usual arithmetic conversions, they just do integer
10829   // promotions on each operand. C99 6.5.7p3
10830 
10831   // For the LHS, do usual unary conversions, but then reset them away
10832   // if this is a compound assignment.
10833   ExprResult OldLHS = LHS;
10834   LHS = UsualUnaryConversions(LHS.get());
10835   if (LHS.isInvalid())
10836     return QualType();
10837   QualType LHSType = LHS.get()->getType();
10838   if (IsCompAssign) LHS = OldLHS;
10839 
10840   // The RHS is simpler.
10841   RHS = UsualUnaryConversions(RHS.get());
10842   if (RHS.isInvalid())
10843     return QualType();
10844   QualType RHSType = RHS.get()->getType();
10845 
10846   // C99 6.5.7p2: Each of the operands shall have integer type.
10847   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
10848   if ((!LHSType->isFixedPointOrIntegerType() &&
10849        !LHSType->hasIntegerRepresentation()) ||
10850       !RHSType->hasIntegerRepresentation())
10851     return InvalidOperands(Loc, LHS, RHS);
10852 
10853   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10854   // hasIntegerRepresentation() above instead of this.
10855   if (isScopedEnumerationType(LHSType) ||
10856       isScopedEnumerationType(RHSType)) {
10857     return InvalidOperands(Loc, LHS, RHS);
10858   }
10859   // Sanity-check shift operands
10860   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10861 
10862   // "The type of the result is that of the promoted left operand."
10863   return LHSType;
10864 }
10865 
10866 /// Diagnose bad pointer comparisons.
10867 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10868                                               ExprResult &LHS, ExprResult &RHS,
10869                                               bool IsError) {
10870   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10871                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10872     << LHS.get()->getType() << RHS.get()->getType()
10873     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10874 }
10875 
10876 /// Returns false if the pointers are converted to a composite type,
10877 /// true otherwise.
10878 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10879                                            ExprResult &LHS, ExprResult &RHS) {
10880   // C++ [expr.rel]p2:
10881   //   [...] Pointer conversions (4.10) and qualification
10882   //   conversions (4.4) are performed on pointer operands (or on
10883   //   a pointer operand and a null pointer constant) to bring
10884   //   them to their composite pointer type. [...]
10885   //
10886   // C++ [expr.eq]p1 uses the same notion for (in)equality
10887   // comparisons of pointers.
10888 
10889   QualType LHSType = LHS.get()->getType();
10890   QualType RHSType = RHS.get()->getType();
10891   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10892          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10893 
10894   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10895   if (T.isNull()) {
10896     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10897         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10898       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10899     else
10900       S.InvalidOperands(Loc, LHS, RHS);
10901     return true;
10902   }
10903 
10904   return false;
10905 }
10906 
10907 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10908                                                     ExprResult &LHS,
10909                                                     ExprResult &RHS,
10910                                                     bool IsError) {
10911   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10912                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10913     << LHS.get()->getType() << RHS.get()->getType()
10914     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10915 }
10916 
10917 static bool isObjCObjectLiteral(ExprResult &E) {
10918   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10919   case Stmt::ObjCArrayLiteralClass:
10920   case Stmt::ObjCDictionaryLiteralClass:
10921   case Stmt::ObjCStringLiteralClass:
10922   case Stmt::ObjCBoxedExprClass:
10923     return true;
10924   default:
10925     // Note that ObjCBoolLiteral is NOT an object literal!
10926     return false;
10927   }
10928 }
10929 
10930 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10931   const ObjCObjectPointerType *Type =
10932     LHS->getType()->getAs<ObjCObjectPointerType>();
10933 
10934   // If this is not actually an Objective-C object, bail out.
10935   if (!Type)
10936     return false;
10937 
10938   // Get the LHS object's interface type.
10939   QualType InterfaceType = Type->getPointeeType();
10940 
10941   // If the RHS isn't an Objective-C object, bail out.
10942   if (!RHS->getType()->isObjCObjectPointerType())
10943     return false;
10944 
10945   // Try to find the -isEqual: method.
10946   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10947   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10948                                                       InterfaceType,
10949                                                       /*IsInstance=*/true);
10950   if (!Method) {
10951     if (Type->isObjCIdType()) {
10952       // For 'id', just check the global pool.
10953       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10954                                                   /*receiverId=*/true);
10955     } else {
10956       // Check protocols.
10957       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10958                                              /*IsInstance=*/true);
10959     }
10960   }
10961 
10962   if (!Method)
10963     return false;
10964 
10965   QualType T = Method->parameters()[0]->getType();
10966   if (!T->isObjCObjectPointerType())
10967     return false;
10968 
10969   QualType R = Method->getReturnType();
10970   if (!R->isScalarType())
10971     return false;
10972 
10973   return true;
10974 }
10975 
10976 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10977   FromE = FromE->IgnoreParenImpCasts();
10978   switch (FromE->getStmtClass()) {
10979     default:
10980       break;
10981     case Stmt::ObjCStringLiteralClass:
10982       // "string literal"
10983       return LK_String;
10984     case Stmt::ObjCArrayLiteralClass:
10985       // "array literal"
10986       return LK_Array;
10987     case Stmt::ObjCDictionaryLiteralClass:
10988       // "dictionary literal"
10989       return LK_Dictionary;
10990     case Stmt::BlockExprClass:
10991       return LK_Block;
10992     case Stmt::ObjCBoxedExprClass: {
10993       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10994       switch (Inner->getStmtClass()) {
10995         case Stmt::IntegerLiteralClass:
10996         case Stmt::FloatingLiteralClass:
10997         case Stmt::CharacterLiteralClass:
10998         case Stmt::ObjCBoolLiteralExprClass:
10999         case Stmt::CXXBoolLiteralExprClass:
11000           // "numeric literal"
11001           return LK_Numeric;
11002         case Stmt::ImplicitCastExprClass: {
11003           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11004           // Boolean literals can be represented by implicit casts.
11005           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11006             return LK_Numeric;
11007           break;
11008         }
11009         default:
11010           break;
11011       }
11012       return LK_Boxed;
11013     }
11014   }
11015   return LK_None;
11016 }
11017 
11018 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11019                                           ExprResult &LHS, ExprResult &RHS,
11020                                           BinaryOperator::Opcode Opc){
11021   Expr *Literal;
11022   Expr *Other;
11023   if (isObjCObjectLiteral(LHS)) {
11024     Literal = LHS.get();
11025     Other = RHS.get();
11026   } else {
11027     Literal = RHS.get();
11028     Other = LHS.get();
11029   }
11030 
11031   // Don't warn on comparisons against nil.
11032   Other = Other->IgnoreParenCasts();
11033   if (Other->isNullPointerConstant(S.getASTContext(),
11034                                    Expr::NPC_ValueDependentIsNotNull))
11035     return;
11036 
11037   // This should be kept in sync with warn_objc_literal_comparison.
11038   // LK_String should always be after the other literals, since it has its own
11039   // warning flag.
11040   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11041   assert(LiteralKind != Sema::LK_Block);
11042   if (LiteralKind == Sema::LK_None) {
11043     llvm_unreachable("Unknown Objective-C object literal kind");
11044   }
11045 
11046   if (LiteralKind == Sema::LK_String)
11047     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11048       << Literal->getSourceRange();
11049   else
11050     S.Diag(Loc, diag::warn_objc_literal_comparison)
11051       << LiteralKind << Literal->getSourceRange();
11052 
11053   if (BinaryOperator::isEqualityOp(Opc) &&
11054       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11055     SourceLocation Start = LHS.get()->getBeginLoc();
11056     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11057     CharSourceRange OpRange =
11058       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11059 
11060     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11061       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11062       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11063       << FixItHint::CreateInsertion(End, "]");
11064   }
11065 }
11066 
11067 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11068 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11069                                            ExprResult &RHS, SourceLocation Loc,
11070                                            BinaryOperatorKind Opc) {
11071   // Check that left hand side is !something.
11072   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11073   if (!UO || UO->getOpcode() != UO_LNot) return;
11074 
11075   // Only check if the right hand side is non-bool arithmetic type.
11076   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11077 
11078   // Make sure that the something in !something is not bool.
11079   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11080   if (SubExpr->isKnownToHaveBooleanValue()) return;
11081 
11082   // Emit warning.
11083   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11084   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11085       << Loc << IsBitwiseOp;
11086 
11087   // First note suggest !(x < y)
11088   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11089   SourceLocation FirstClose = RHS.get()->getEndLoc();
11090   FirstClose = S.getLocForEndOfToken(FirstClose);
11091   if (FirstClose.isInvalid())
11092     FirstOpen = SourceLocation();
11093   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11094       << IsBitwiseOp
11095       << FixItHint::CreateInsertion(FirstOpen, "(")
11096       << FixItHint::CreateInsertion(FirstClose, ")");
11097 
11098   // Second note suggests (!x) < y
11099   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11100   SourceLocation SecondClose = LHS.get()->getEndLoc();
11101   SecondClose = S.getLocForEndOfToken(SecondClose);
11102   if (SecondClose.isInvalid())
11103     SecondOpen = SourceLocation();
11104   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11105       << FixItHint::CreateInsertion(SecondOpen, "(")
11106       << FixItHint::CreateInsertion(SecondClose, ")");
11107 }
11108 
11109 // Returns true if E refers to a non-weak array.
11110 static bool checkForArray(const Expr *E) {
11111   const ValueDecl *D = nullptr;
11112   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11113     D = DR->getDecl();
11114   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11115     if (Mem->isImplicitAccess())
11116       D = Mem->getMemberDecl();
11117   }
11118   if (!D)
11119     return false;
11120   return D->getType()->isArrayType() && !D->isWeak();
11121 }
11122 
11123 /// Diagnose some forms of syntactically-obvious tautological comparison.
11124 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11125                                            Expr *LHS, Expr *RHS,
11126                                            BinaryOperatorKind Opc) {
11127   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11128   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11129 
11130   QualType LHSType = LHS->getType();
11131   QualType RHSType = RHS->getType();
11132   if (LHSType->hasFloatingRepresentation() ||
11133       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11134       S.inTemplateInstantiation())
11135     return;
11136 
11137   // Comparisons between two array types are ill-formed for operator<=>, so
11138   // we shouldn't emit any additional warnings about it.
11139   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11140     return;
11141 
11142   // For non-floating point types, check for self-comparisons of the form
11143   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11144   // often indicate logic errors in the program.
11145   //
11146   // NOTE: Don't warn about comparison expressions resulting from macro
11147   // expansion. Also don't warn about comparisons which are only self
11148   // comparisons within a template instantiation. The warnings should catch
11149   // obvious cases in the definition of the template anyways. The idea is to
11150   // warn when the typed comparison operator will always evaluate to the same
11151   // result.
11152 
11153   // Used for indexing into %select in warn_comparison_always
11154   enum {
11155     AlwaysConstant,
11156     AlwaysTrue,
11157     AlwaysFalse,
11158     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11159   };
11160 
11161   // C++2a [depr.array.comp]:
11162   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11163   //   operands of array type are deprecated.
11164   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11165       RHSStripped->getType()->isArrayType()) {
11166     S.Diag(Loc, diag::warn_depr_array_comparison)
11167         << LHS->getSourceRange() << RHS->getSourceRange()
11168         << LHSStripped->getType() << RHSStripped->getType();
11169     // Carry on to produce the tautological comparison warning, if this
11170     // expression is potentially-evaluated, we can resolve the array to a
11171     // non-weak declaration, and so on.
11172   }
11173 
11174   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11175     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11176       unsigned Result;
11177       switch (Opc) {
11178       case BO_EQ:
11179       case BO_LE:
11180       case BO_GE:
11181         Result = AlwaysTrue;
11182         break;
11183       case BO_NE:
11184       case BO_LT:
11185       case BO_GT:
11186         Result = AlwaysFalse;
11187         break;
11188       case BO_Cmp:
11189         Result = AlwaysEqual;
11190         break;
11191       default:
11192         Result = AlwaysConstant;
11193         break;
11194       }
11195       S.DiagRuntimeBehavior(Loc, nullptr,
11196                             S.PDiag(diag::warn_comparison_always)
11197                                 << 0 /*self-comparison*/
11198                                 << Result);
11199     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11200       // What is it always going to evaluate to?
11201       unsigned Result;
11202       switch (Opc) {
11203       case BO_EQ: // e.g. array1 == array2
11204         Result = AlwaysFalse;
11205         break;
11206       case BO_NE: // e.g. array1 != array2
11207         Result = AlwaysTrue;
11208         break;
11209       default: // e.g. array1 <= array2
11210         // The best we can say is 'a constant'
11211         Result = AlwaysConstant;
11212         break;
11213       }
11214       S.DiagRuntimeBehavior(Loc, nullptr,
11215                             S.PDiag(diag::warn_comparison_always)
11216                                 << 1 /*array comparison*/
11217                                 << Result);
11218     }
11219   }
11220 
11221   if (isa<CastExpr>(LHSStripped))
11222     LHSStripped = LHSStripped->IgnoreParenCasts();
11223   if (isa<CastExpr>(RHSStripped))
11224     RHSStripped = RHSStripped->IgnoreParenCasts();
11225 
11226   // Warn about comparisons against a string constant (unless the other
11227   // operand is null); the user probably wants string comparison function.
11228   Expr *LiteralString = nullptr;
11229   Expr *LiteralStringStripped = nullptr;
11230   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11231       !RHSStripped->isNullPointerConstant(S.Context,
11232                                           Expr::NPC_ValueDependentIsNull)) {
11233     LiteralString = LHS;
11234     LiteralStringStripped = LHSStripped;
11235   } else if ((isa<StringLiteral>(RHSStripped) ||
11236               isa<ObjCEncodeExpr>(RHSStripped)) &&
11237              !LHSStripped->isNullPointerConstant(S.Context,
11238                                           Expr::NPC_ValueDependentIsNull)) {
11239     LiteralString = RHS;
11240     LiteralStringStripped = RHSStripped;
11241   }
11242 
11243   if (LiteralString) {
11244     S.DiagRuntimeBehavior(Loc, nullptr,
11245                           S.PDiag(diag::warn_stringcompare)
11246                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11247                               << LiteralString->getSourceRange());
11248   }
11249 }
11250 
11251 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11252   switch (CK) {
11253   default: {
11254 #ifndef NDEBUG
11255     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11256                  << "\n";
11257 #endif
11258     llvm_unreachable("unhandled cast kind");
11259   }
11260   case CK_UserDefinedConversion:
11261     return ICK_Identity;
11262   case CK_LValueToRValue:
11263     return ICK_Lvalue_To_Rvalue;
11264   case CK_ArrayToPointerDecay:
11265     return ICK_Array_To_Pointer;
11266   case CK_FunctionToPointerDecay:
11267     return ICK_Function_To_Pointer;
11268   case CK_IntegralCast:
11269     return ICK_Integral_Conversion;
11270   case CK_FloatingCast:
11271     return ICK_Floating_Conversion;
11272   case CK_IntegralToFloating:
11273   case CK_FloatingToIntegral:
11274     return ICK_Floating_Integral;
11275   case CK_IntegralComplexCast:
11276   case CK_FloatingComplexCast:
11277   case CK_FloatingComplexToIntegralComplex:
11278   case CK_IntegralComplexToFloatingComplex:
11279     return ICK_Complex_Conversion;
11280   case CK_FloatingComplexToReal:
11281   case CK_FloatingRealToComplex:
11282   case CK_IntegralComplexToReal:
11283   case CK_IntegralRealToComplex:
11284     return ICK_Complex_Real;
11285   }
11286 }
11287 
11288 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11289                                              QualType FromType,
11290                                              SourceLocation Loc) {
11291   // Check for a narrowing implicit conversion.
11292   StandardConversionSequence SCS;
11293   SCS.setAsIdentityConversion();
11294   SCS.setToType(0, FromType);
11295   SCS.setToType(1, ToType);
11296   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11297     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11298 
11299   APValue PreNarrowingValue;
11300   QualType PreNarrowingType;
11301   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11302                                PreNarrowingType,
11303                                /*IgnoreFloatToIntegralConversion*/ true)) {
11304   case NK_Dependent_Narrowing:
11305     // Implicit conversion to a narrower type, but the expression is
11306     // value-dependent so we can't tell whether it's actually narrowing.
11307   case NK_Not_Narrowing:
11308     return false;
11309 
11310   case NK_Constant_Narrowing:
11311     // Implicit conversion to a narrower type, and the value is not a constant
11312     // expression.
11313     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11314         << /*Constant*/ 1
11315         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11316     return true;
11317 
11318   case NK_Variable_Narrowing:
11319     // Implicit conversion to a narrower type, and the value is not a constant
11320     // expression.
11321   case NK_Type_Narrowing:
11322     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11323         << /*Constant*/ 0 << FromType << ToType;
11324     // TODO: It's not a constant expression, but what if the user intended it
11325     // to be? Can we produce notes to help them figure out why it isn't?
11326     return true;
11327   }
11328   llvm_unreachable("unhandled case in switch");
11329 }
11330 
11331 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11332                                                          ExprResult &LHS,
11333                                                          ExprResult &RHS,
11334                                                          SourceLocation Loc) {
11335   QualType LHSType = LHS.get()->getType();
11336   QualType RHSType = RHS.get()->getType();
11337   // Dig out the original argument type and expression before implicit casts
11338   // were applied. These are the types/expressions we need to check the
11339   // [expr.spaceship] requirements against.
11340   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11341   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11342   QualType LHSStrippedType = LHSStripped.get()->getType();
11343   QualType RHSStrippedType = RHSStripped.get()->getType();
11344 
11345   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11346   // other is not, the program is ill-formed.
11347   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11348     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11349     return QualType();
11350   }
11351 
11352   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11353   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11354                     RHSStrippedType->isEnumeralType();
11355   if (NumEnumArgs == 1) {
11356     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11357     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11358     if (OtherTy->hasFloatingRepresentation()) {
11359       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11360       return QualType();
11361     }
11362   }
11363   if (NumEnumArgs == 2) {
11364     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11365     // type E, the operator yields the result of converting the operands
11366     // to the underlying type of E and applying <=> to the converted operands.
11367     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11368       S.InvalidOperands(Loc, LHS, RHS);
11369       return QualType();
11370     }
11371     QualType IntType =
11372         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11373     assert(IntType->isArithmeticType());
11374 
11375     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11376     // promote the boolean type, and all other promotable integer types, to
11377     // avoid this.
11378     if (IntType->isPromotableIntegerType())
11379       IntType = S.Context.getPromotedIntegerType(IntType);
11380 
11381     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11382     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11383     LHSType = RHSType = IntType;
11384   }
11385 
11386   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11387   // usual arithmetic conversions are applied to the operands.
11388   QualType Type =
11389       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11390   if (LHS.isInvalid() || RHS.isInvalid())
11391     return QualType();
11392   if (Type.isNull())
11393     return S.InvalidOperands(Loc, LHS, RHS);
11394 
11395   Optional<ComparisonCategoryType> CCT =
11396       getComparisonCategoryForBuiltinCmp(Type);
11397   if (!CCT)
11398     return S.InvalidOperands(Loc, LHS, RHS);
11399 
11400   bool HasNarrowing = checkThreeWayNarrowingConversion(
11401       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11402   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11403                                                    RHS.get()->getBeginLoc());
11404   if (HasNarrowing)
11405     return QualType();
11406 
11407   assert(!Type.isNull() && "composite type for <=> has not been set");
11408 
11409   return S.CheckComparisonCategoryType(
11410       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11411 }
11412 
11413 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11414                                                  ExprResult &RHS,
11415                                                  SourceLocation Loc,
11416                                                  BinaryOperatorKind Opc) {
11417   if (Opc == BO_Cmp)
11418     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11419 
11420   // C99 6.5.8p3 / C99 6.5.9p4
11421   QualType Type =
11422       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11423   if (LHS.isInvalid() || RHS.isInvalid())
11424     return QualType();
11425   if (Type.isNull())
11426     return S.InvalidOperands(Loc, LHS, RHS);
11427   assert(Type->isArithmeticType() || Type->isEnumeralType());
11428 
11429   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11430     return S.InvalidOperands(Loc, LHS, RHS);
11431 
11432   // Check for comparisons of floating point operands using != and ==.
11433   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11434     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11435 
11436   // The result of comparisons is 'bool' in C++, 'int' in C.
11437   return S.Context.getLogicalOperationType();
11438 }
11439 
11440 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11441   if (!NullE.get()->getType()->isAnyPointerType())
11442     return;
11443   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11444   if (!E.get()->getType()->isAnyPointerType() &&
11445       E.get()->isNullPointerConstant(Context,
11446                                      Expr::NPC_ValueDependentIsNotNull) ==
11447         Expr::NPCK_ZeroExpression) {
11448     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11449       if (CL->getValue() == 0)
11450         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11451             << NullValue
11452             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11453                                             NullValue ? "NULL" : "(void *)0");
11454     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11455         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11456         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11457         if (T == Context.CharTy)
11458           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11459               << NullValue
11460               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11461                                               NullValue ? "NULL" : "(void *)0");
11462       }
11463   }
11464 }
11465 
11466 // C99 6.5.8, C++ [expr.rel]
11467 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11468                                     SourceLocation Loc,
11469                                     BinaryOperatorKind Opc) {
11470   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11471   bool IsThreeWay = Opc == BO_Cmp;
11472   bool IsOrdered = IsRelational || IsThreeWay;
11473   auto IsAnyPointerType = [](ExprResult E) {
11474     QualType Ty = E.get()->getType();
11475     return Ty->isPointerType() || Ty->isMemberPointerType();
11476   };
11477 
11478   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11479   // type, array-to-pointer, ..., conversions are performed on both operands to
11480   // bring them to their composite type.
11481   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11482   // any type-related checks.
11483   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11484     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11485     if (LHS.isInvalid())
11486       return QualType();
11487     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11488     if (RHS.isInvalid())
11489       return QualType();
11490   } else {
11491     LHS = DefaultLvalueConversion(LHS.get());
11492     if (LHS.isInvalid())
11493       return QualType();
11494     RHS = DefaultLvalueConversion(RHS.get());
11495     if (RHS.isInvalid())
11496       return QualType();
11497   }
11498 
11499   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11500   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11501     CheckPtrComparisonWithNullChar(LHS, RHS);
11502     CheckPtrComparisonWithNullChar(RHS, LHS);
11503   }
11504 
11505   // Handle vector comparisons separately.
11506   if (LHS.get()->getType()->isVectorType() ||
11507       RHS.get()->getType()->isVectorType())
11508     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11509 
11510   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11511   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11512 
11513   QualType LHSType = LHS.get()->getType();
11514   QualType RHSType = RHS.get()->getType();
11515   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11516       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11517     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11518 
11519   const Expr::NullPointerConstantKind LHSNullKind =
11520       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11521   const Expr::NullPointerConstantKind RHSNullKind =
11522       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11523   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11524   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11525 
11526   auto computeResultTy = [&]() {
11527     if (Opc != BO_Cmp)
11528       return Context.getLogicalOperationType();
11529     assert(getLangOpts().CPlusPlus);
11530     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11531 
11532     QualType CompositeTy = LHS.get()->getType();
11533     assert(!CompositeTy->isReferenceType());
11534 
11535     Optional<ComparisonCategoryType> CCT =
11536         getComparisonCategoryForBuiltinCmp(CompositeTy);
11537     if (!CCT)
11538       return InvalidOperands(Loc, LHS, RHS);
11539 
11540     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11541       // P0946R0: Comparisons between a null pointer constant and an object
11542       // pointer result in std::strong_equality, which is ill-formed under
11543       // P1959R0.
11544       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11545           << (LHSIsNull ? LHS.get()->getSourceRange()
11546                         : RHS.get()->getSourceRange());
11547       return QualType();
11548     }
11549 
11550     return CheckComparisonCategoryType(
11551         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11552   };
11553 
11554   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11555     bool IsEquality = Opc == BO_EQ;
11556     if (RHSIsNull)
11557       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11558                                    RHS.get()->getSourceRange());
11559     else
11560       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11561                                    LHS.get()->getSourceRange());
11562   }
11563 
11564   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11565       (RHSType->isIntegerType() && !RHSIsNull)) {
11566     // Skip normal pointer conversion checks in this case; we have better
11567     // diagnostics for this below.
11568   } else if (getLangOpts().CPlusPlus) {
11569     // Equality comparison of a function pointer to a void pointer is invalid,
11570     // but we allow it as an extension.
11571     // FIXME: If we really want to allow this, should it be part of composite
11572     // pointer type computation so it works in conditionals too?
11573     if (!IsOrdered &&
11574         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11575          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11576       // This is a gcc extension compatibility comparison.
11577       // In a SFINAE context, we treat this as a hard error to maintain
11578       // conformance with the C++ standard.
11579       diagnoseFunctionPointerToVoidComparison(
11580           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11581 
11582       if (isSFINAEContext())
11583         return QualType();
11584 
11585       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11586       return computeResultTy();
11587     }
11588 
11589     // C++ [expr.eq]p2:
11590     //   If at least one operand is a pointer [...] bring them to their
11591     //   composite pointer type.
11592     // C++ [expr.spaceship]p6
11593     //  If at least one of the operands is of pointer type, [...] bring them
11594     //  to their composite pointer type.
11595     // C++ [expr.rel]p2:
11596     //   If both operands are pointers, [...] bring them to their composite
11597     //   pointer type.
11598     // For <=>, the only valid non-pointer types are arrays and functions, and
11599     // we already decayed those, so this is really the same as the relational
11600     // comparison rule.
11601     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11602             (IsOrdered ? 2 : 1) &&
11603         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11604                                          RHSType->isObjCObjectPointerType()))) {
11605       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11606         return QualType();
11607       return computeResultTy();
11608     }
11609   } else if (LHSType->isPointerType() &&
11610              RHSType->isPointerType()) { // C99 6.5.8p2
11611     // All of the following pointer-related warnings are GCC extensions, except
11612     // when handling null pointer constants.
11613     QualType LCanPointeeTy =
11614       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11615     QualType RCanPointeeTy =
11616       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11617 
11618     // C99 6.5.9p2 and C99 6.5.8p2
11619     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11620                                    RCanPointeeTy.getUnqualifiedType())) {
11621       if (IsRelational) {
11622         // Pointers both need to point to complete or incomplete types
11623         if ((LCanPointeeTy->isIncompleteType() !=
11624              RCanPointeeTy->isIncompleteType()) &&
11625             !getLangOpts().C11) {
11626           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11627               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11628               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11629               << RCanPointeeTy->isIncompleteType();
11630         }
11631         if (LCanPointeeTy->isFunctionType()) {
11632           // Valid unless a relational comparison of function pointers
11633           Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11634               << LHSType << RHSType << LHS.get()->getSourceRange()
11635               << RHS.get()->getSourceRange();
11636         }
11637       }
11638     } else if (!IsRelational &&
11639                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11640       // Valid unless comparison between non-null pointer and function pointer
11641       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11642           && !LHSIsNull && !RHSIsNull)
11643         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11644                                                 /*isError*/false);
11645     } else {
11646       // Invalid
11647       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11648     }
11649     if (LCanPointeeTy != RCanPointeeTy) {
11650       // Treat NULL constant as a special case in OpenCL.
11651       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11652         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11653           Diag(Loc,
11654                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11655               << LHSType << RHSType << 0 /* comparison */
11656               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11657         }
11658       }
11659       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11660       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11661       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11662                                                : CK_BitCast;
11663       if (LHSIsNull && !RHSIsNull)
11664         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11665       else
11666         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11667     }
11668     return computeResultTy();
11669   }
11670 
11671   if (getLangOpts().CPlusPlus) {
11672     // C++ [expr.eq]p4:
11673     //   Two operands of type std::nullptr_t or one operand of type
11674     //   std::nullptr_t and the other a null pointer constant compare equal.
11675     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11676       if (LHSType->isNullPtrType()) {
11677         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11678         return computeResultTy();
11679       }
11680       if (RHSType->isNullPtrType()) {
11681         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11682         return computeResultTy();
11683       }
11684     }
11685 
11686     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11687     // These aren't covered by the composite pointer type rules.
11688     if (!IsOrdered && RHSType->isNullPtrType() &&
11689         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11690       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11691       return computeResultTy();
11692     }
11693     if (!IsOrdered && LHSType->isNullPtrType() &&
11694         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11695       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11696       return computeResultTy();
11697     }
11698 
11699     if (IsRelational &&
11700         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11701          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11702       // HACK: Relational comparison of nullptr_t against a pointer type is
11703       // invalid per DR583, but we allow it within std::less<> and friends,
11704       // since otherwise common uses of it break.
11705       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11706       // friends to have std::nullptr_t overload candidates.
11707       DeclContext *DC = CurContext;
11708       if (isa<FunctionDecl>(DC))
11709         DC = DC->getParent();
11710       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11711         if (CTSD->isInStdNamespace() &&
11712             llvm::StringSwitch<bool>(CTSD->getName())
11713                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11714                 .Default(false)) {
11715           if (RHSType->isNullPtrType())
11716             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11717           else
11718             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11719           return computeResultTy();
11720         }
11721       }
11722     }
11723 
11724     // C++ [expr.eq]p2:
11725     //   If at least one operand is a pointer to member, [...] bring them to
11726     //   their composite pointer type.
11727     if (!IsOrdered &&
11728         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11729       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11730         return QualType();
11731       else
11732         return computeResultTy();
11733     }
11734   }
11735 
11736   // Handle block pointer types.
11737   if (!IsOrdered && LHSType->isBlockPointerType() &&
11738       RHSType->isBlockPointerType()) {
11739     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11740     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11741 
11742     if (!LHSIsNull && !RHSIsNull &&
11743         !Context.typesAreCompatible(lpointee, rpointee)) {
11744       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11745         << LHSType << RHSType << LHS.get()->getSourceRange()
11746         << RHS.get()->getSourceRange();
11747     }
11748     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11749     return computeResultTy();
11750   }
11751 
11752   // Allow block pointers to be compared with null pointer constants.
11753   if (!IsOrdered
11754       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11755           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11756     if (!LHSIsNull && !RHSIsNull) {
11757       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11758              ->getPointeeType()->isVoidType())
11759             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11760                 ->getPointeeType()->isVoidType())))
11761         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11762           << LHSType << RHSType << LHS.get()->getSourceRange()
11763           << RHS.get()->getSourceRange();
11764     }
11765     if (LHSIsNull && !RHSIsNull)
11766       LHS = ImpCastExprToType(LHS.get(), RHSType,
11767                               RHSType->isPointerType() ? CK_BitCast
11768                                 : CK_AnyPointerToBlockPointerCast);
11769     else
11770       RHS = ImpCastExprToType(RHS.get(), LHSType,
11771                               LHSType->isPointerType() ? CK_BitCast
11772                                 : CK_AnyPointerToBlockPointerCast);
11773     return computeResultTy();
11774   }
11775 
11776   if (LHSType->isObjCObjectPointerType() ||
11777       RHSType->isObjCObjectPointerType()) {
11778     const PointerType *LPT = LHSType->getAs<PointerType>();
11779     const PointerType *RPT = RHSType->getAs<PointerType>();
11780     if (LPT || RPT) {
11781       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11782       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11783 
11784       if (!LPtrToVoid && !RPtrToVoid &&
11785           !Context.typesAreCompatible(LHSType, RHSType)) {
11786         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11787                                           /*isError*/false);
11788       }
11789       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11790       // the RHS, but we have test coverage for this behavior.
11791       // FIXME: Consider using convertPointersToCompositeType in C++.
11792       if (LHSIsNull && !RHSIsNull) {
11793         Expr *E = LHS.get();
11794         if (getLangOpts().ObjCAutoRefCount)
11795           CheckObjCConversion(SourceRange(), RHSType, E,
11796                               CCK_ImplicitConversion);
11797         LHS = ImpCastExprToType(E, RHSType,
11798                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11799       }
11800       else {
11801         Expr *E = RHS.get();
11802         if (getLangOpts().ObjCAutoRefCount)
11803           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11804                               /*Diagnose=*/true,
11805                               /*DiagnoseCFAudited=*/false, Opc);
11806         RHS = ImpCastExprToType(E, LHSType,
11807                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11808       }
11809       return computeResultTy();
11810     }
11811     if (LHSType->isObjCObjectPointerType() &&
11812         RHSType->isObjCObjectPointerType()) {
11813       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11814         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11815                                           /*isError*/false);
11816       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11817         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11818 
11819       if (LHSIsNull && !RHSIsNull)
11820         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11821       else
11822         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11823       return computeResultTy();
11824     }
11825 
11826     if (!IsOrdered && LHSType->isBlockPointerType() &&
11827         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11828       LHS = ImpCastExprToType(LHS.get(), RHSType,
11829                               CK_BlockPointerToObjCPointerCast);
11830       return computeResultTy();
11831     } else if (!IsOrdered &&
11832                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11833                RHSType->isBlockPointerType()) {
11834       RHS = ImpCastExprToType(RHS.get(), LHSType,
11835                               CK_BlockPointerToObjCPointerCast);
11836       return computeResultTy();
11837     }
11838   }
11839   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11840       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11841     unsigned DiagID = 0;
11842     bool isError = false;
11843     if (LangOpts.DebuggerSupport) {
11844       // Under a debugger, allow the comparison of pointers to integers,
11845       // since users tend to want to compare addresses.
11846     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11847                (RHSIsNull && RHSType->isIntegerType())) {
11848       if (IsOrdered) {
11849         isError = getLangOpts().CPlusPlus;
11850         DiagID =
11851           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11852                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11853       }
11854     } else if (getLangOpts().CPlusPlus) {
11855       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11856       isError = true;
11857     } else if (IsOrdered)
11858       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11859     else
11860       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11861 
11862     if (DiagID) {
11863       Diag(Loc, DiagID)
11864         << LHSType << RHSType << LHS.get()->getSourceRange()
11865         << RHS.get()->getSourceRange();
11866       if (isError)
11867         return QualType();
11868     }
11869 
11870     if (LHSType->isIntegerType())
11871       LHS = ImpCastExprToType(LHS.get(), RHSType,
11872                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11873     else
11874       RHS = ImpCastExprToType(RHS.get(), LHSType,
11875                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11876     return computeResultTy();
11877   }
11878 
11879   // Handle block pointers.
11880   if (!IsOrdered && RHSIsNull
11881       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11882     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11883     return computeResultTy();
11884   }
11885   if (!IsOrdered && LHSIsNull
11886       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11887     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11888     return computeResultTy();
11889   }
11890 
11891   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11892     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11893       return computeResultTy();
11894     }
11895 
11896     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11897       return computeResultTy();
11898     }
11899 
11900     if (LHSIsNull && RHSType->isQueueT()) {
11901       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11902       return computeResultTy();
11903     }
11904 
11905     if (LHSType->isQueueT() && RHSIsNull) {
11906       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11907       return computeResultTy();
11908     }
11909   }
11910 
11911   return InvalidOperands(Loc, LHS, RHS);
11912 }
11913 
11914 // Return a signed ext_vector_type that is of identical size and number of
11915 // elements. For floating point vectors, return an integer type of identical
11916 // size and number of elements. In the non ext_vector_type case, search from
11917 // the largest type to the smallest type to avoid cases where long long == long,
11918 // where long gets picked over long long.
11919 QualType Sema::GetSignedVectorType(QualType V) {
11920   const VectorType *VTy = V->castAs<VectorType>();
11921   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11922 
11923   if (isa<ExtVectorType>(VTy)) {
11924     if (TypeSize == Context.getTypeSize(Context.CharTy))
11925       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11926     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11927       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11928     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11929       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11930     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11931       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11932     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11933            "Unhandled vector element size in vector compare");
11934     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11935   }
11936 
11937   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11938     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11939                                  VectorType::GenericVector);
11940   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11941     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11942                                  VectorType::GenericVector);
11943   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11944     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11945                                  VectorType::GenericVector);
11946   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11947     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11948                                  VectorType::GenericVector);
11949   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11950          "Unhandled vector element size in vector compare");
11951   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11952                                VectorType::GenericVector);
11953 }
11954 
11955 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11956 /// operates on extended vector types.  Instead of producing an IntTy result,
11957 /// like a scalar comparison, a vector comparison produces a vector of integer
11958 /// types.
11959 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11960                                           SourceLocation Loc,
11961                                           BinaryOperatorKind Opc) {
11962   if (Opc == BO_Cmp) {
11963     Diag(Loc, diag::err_three_way_vector_comparison);
11964     return QualType();
11965   }
11966 
11967   // Check to make sure we're operating on vectors of the same type and width,
11968   // Allowing one side to be a scalar of element type.
11969   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11970                               /*AllowBothBool*/true,
11971                               /*AllowBoolConversions*/getLangOpts().ZVector);
11972   if (vType.isNull())
11973     return vType;
11974 
11975   QualType LHSType = LHS.get()->getType();
11976 
11977   // If AltiVec, the comparison results in a numeric type, i.e.
11978   // bool for C++, int for C
11979   if (getLangOpts().AltiVec &&
11980       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11981     return Context.getLogicalOperationType();
11982 
11983   // For non-floating point types, check for self-comparisons of the form
11984   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11985   // often indicate logic errors in the program.
11986   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11987 
11988   // Check for comparisons of floating point operands using != and ==.
11989   if (BinaryOperator::isEqualityOp(Opc) &&
11990       LHSType->hasFloatingRepresentation()) {
11991     assert(RHS.get()->getType()->hasFloatingRepresentation());
11992     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11993   }
11994 
11995   // Return a signed type for the vector.
11996   return GetSignedVectorType(vType);
11997 }
11998 
11999 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12000                                     const ExprResult &XorRHS,
12001                                     const SourceLocation Loc) {
12002   // Do not diagnose macros.
12003   if (Loc.isMacroID())
12004     return;
12005 
12006   bool Negative = false;
12007   bool ExplicitPlus = false;
12008   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12009   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12010 
12011   if (!LHSInt)
12012     return;
12013   if (!RHSInt) {
12014     // Check negative literals.
12015     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12016       UnaryOperatorKind Opc = UO->getOpcode();
12017       if (Opc != UO_Minus && Opc != UO_Plus)
12018         return;
12019       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12020       if (!RHSInt)
12021         return;
12022       Negative = (Opc == UO_Minus);
12023       ExplicitPlus = !Negative;
12024     } else {
12025       return;
12026     }
12027   }
12028 
12029   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12030   llvm::APInt RightSideValue = RHSInt->getValue();
12031   if (LeftSideValue != 2 && LeftSideValue != 10)
12032     return;
12033 
12034   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12035     return;
12036 
12037   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12038       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12039   llvm::StringRef ExprStr =
12040       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12041 
12042   CharSourceRange XorRange =
12043       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12044   llvm::StringRef XorStr =
12045       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12046   // Do not diagnose if xor keyword/macro is used.
12047   if (XorStr == "xor")
12048     return;
12049 
12050   std::string LHSStr = std::string(Lexer::getSourceText(
12051       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12052       S.getSourceManager(), S.getLangOpts()));
12053   std::string RHSStr = std::string(Lexer::getSourceText(
12054       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12055       S.getSourceManager(), S.getLangOpts()));
12056 
12057   if (Negative) {
12058     RightSideValue = -RightSideValue;
12059     RHSStr = "-" + RHSStr;
12060   } else if (ExplicitPlus) {
12061     RHSStr = "+" + RHSStr;
12062   }
12063 
12064   StringRef LHSStrRef = LHSStr;
12065   StringRef RHSStrRef = RHSStr;
12066   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12067   // literals.
12068   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12069       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12070       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12071       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12072       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12073       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12074       LHSStrRef.find('\'') != StringRef::npos ||
12075       RHSStrRef.find('\'') != StringRef::npos)
12076     return;
12077 
12078   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12079   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12080   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12081   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12082     std::string SuggestedExpr = "1 << " + RHSStr;
12083     bool Overflow = false;
12084     llvm::APInt One = (LeftSideValue - 1);
12085     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12086     if (Overflow) {
12087       if (RightSideIntValue < 64)
12088         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12089             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12090             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12091       else if (RightSideIntValue == 64)
12092         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12093       else
12094         return;
12095     } else {
12096       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12097           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12098           << PowValue.toString(10, true)
12099           << FixItHint::CreateReplacement(
12100                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12101     }
12102 
12103     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12104   } else if (LeftSideValue == 10) {
12105     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12106     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12107         << ExprStr << XorValue.toString(10, true) << SuggestedValue
12108         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12109     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12110   }
12111 }
12112 
12113 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12114                                           SourceLocation Loc) {
12115   // Ensure that either both operands are of the same vector type, or
12116   // one operand is of a vector type and the other is of its element type.
12117   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12118                                        /*AllowBothBool*/true,
12119                                        /*AllowBoolConversions*/false);
12120   if (vType.isNull())
12121     return InvalidOperands(Loc, LHS, RHS);
12122   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12123       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12124     return InvalidOperands(Loc, LHS, RHS);
12125   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12126   //        usage of the logical operators && and || with vectors in C. This
12127   //        check could be notionally dropped.
12128   if (!getLangOpts().CPlusPlus &&
12129       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12130     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12131 
12132   return GetSignedVectorType(LHS.get()->getType());
12133 }
12134 
12135 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12136                                               SourceLocation Loc,
12137                                               bool IsCompAssign) {
12138   if (!IsCompAssign) {
12139     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12140     if (LHS.isInvalid())
12141       return QualType();
12142   }
12143   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12144   if (RHS.isInvalid())
12145     return QualType();
12146 
12147   // For conversion purposes, we ignore any qualifiers.
12148   // For example, "const float" and "float" are equivalent.
12149   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12150   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12151 
12152   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12153   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12154   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12155 
12156   if (Context.hasSameType(LHSType, RHSType))
12157     return LHSType;
12158 
12159   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12160   // case we have to return InvalidOperands.
12161   ExprResult OriginalLHS = LHS;
12162   ExprResult OriginalRHS = RHS;
12163   if (LHSMatType && !RHSMatType) {
12164     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12165     if (!RHS.isInvalid())
12166       return LHSType;
12167 
12168     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12169   }
12170 
12171   if (!LHSMatType && RHSMatType) {
12172     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12173     if (!LHS.isInvalid())
12174       return RHSType;
12175     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12176   }
12177 
12178   return InvalidOperands(Loc, LHS, RHS);
12179 }
12180 
12181 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12182                                            SourceLocation Loc,
12183                                            bool IsCompAssign) {
12184   if (!IsCompAssign) {
12185     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12186     if (LHS.isInvalid())
12187       return QualType();
12188   }
12189   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12190   if (RHS.isInvalid())
12191     return QualType();
12192 
12193   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12194   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12195   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12196 
12197   if (LHSMatType && RHSMatType) {
12198     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12199       return InvalidOperands(Loc, LHS, RHS);
12200 
12201     if (!Context.hasSameType(LHSMatType->getElementType(),
12202                              RHSMatType->getElementType()))
12203       return InvalidOperands(Loc, LHS, RHS);
12204 
12205     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12206                                          LHSMatType->getNumRows(),
12207                                          RHSMatType->getNumColumns());
12208   }
12209   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12210 }
12211 
12212 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12213                                            SourceLocation Loc,
12214                                            BinaryOperatorKind Opc) {
12215   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12216 
12217   bool IsCompAssign =
12218       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12219 
12220   if (LHS.get()->getType()->isVectorType() ||
12221       RHS.get()->getType()->isVectorType()) {
12222     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12223         RHS.get()->getType()->hasIntegerRepresentation())
12224       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12225                         /*AllowBothBool*/true,
12226                         /*AllowBoolConversions*/getLangOpts().ZVector);
12227     return InvalidOperands(Loc, LHS, RHS);
12228   }
12229 
12230   if (Opc == BO_And)
12231     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12232 
12233   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12234       RHS.get()->getType()->hasFloatingRepresentation())
12235     return InvalidOperands(Loc, LHS, RHS);
12236 
12237   ExprResult LHSResult = LHS, RHSResult = RHS;
12238   QualType compType = UsualArithmeticConversions(
12239       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12240   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12241     return QualType();
12242   LHS = LHSResult.get();
12243   RHS = RHSResult.get();
12244 
12245   if (Opc == BO_Xor)
12246     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12247 
12248   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12249     return compType;
12250   return InvalidOperands(Loc, LHS, RHS);
12251 }
12252 
12253 // C99 6.5.[13,14]
12254 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12255                                            SourceLocation Loc,
12256                                            BinaryOperatorKind Opc) {
12257   // Check vector operands differently.
12258   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12259     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12260 
12261   bool EnumConstantInBoolContext = false;
12262   for (const ExprResult &HS : {LHS, RHS}) {
12263     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12264       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12265       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12266         EnumConstantInBoolContext = true;
12267     }
12268   }
12269 
12270   if (EnumConstantInBoolContext)
12271     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12272 
12273   // Diagnose cases where the user write a logical and/or but probably meant a
12274   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12275   // is a constant.
12276   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12277       !LHS.get()->getType()->isBooleanType() &&
12278       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12279       // Don't warn in macros or template instantiations.
12280       !Loc.isMacroID() && !inTemplateInstantiation()) {
12281     // If the RHS can be constant folded, and if it constant folds to something
12282     // that isn't 0 or 1 (which indicate a potential logical operation that
12283     // happened to fold to true/false) then warn.
12284     // Parens on the RHS are ignored.
12285     Expr::EvalResult EVResult;
12286     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12287       llvm::APSInt Result = EVResult.Val.getInt();
12288       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12289            !RHS.get()->getExprLoc().isMacroID()) ||
12290           (Result != 0 && Result != 1)) {
12291         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12292           << RHS.get()->getSourceRange()
12293           << (Opc == BO_LAnd ? "&&" : "||");
12294         // Suggest replacing the logical operator with the bitwise version
12295         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12296             << (Opc == BO_LAnd ? "&" : "|")
12297             << FixItHint::CreateReplacement(SourceRange(
12298                                                  Loc, getLocForEndOfToken(Loc)),
12299                                             Opc == BO_LAnd ? "&" : "|");
12300         if (Opc == BO_LAnd)
12301           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12302           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12303               << FixItHint::CreateRemoval(
12304                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12305                                  RHS.get()->getEndLoc()));
12306       }
12307     }
12308   }
12309 
12310   if (!Context.getLangOpts().CPlusPlus) {
12311     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12312     // not operate on the built-in scalar and vector float types.
12313     if (Context.getLangOpts().OpenCL &&
12314         Context.getLangOpts().OpenCLVersion < 120) {
12315       if (LHS.get()->getType()->isFloatingType() ||
12316           RHS.get()->getType()->isFloatingType())
12317         return InvalidOperands(Loc, LHS, RHS);
12318     }
12319 
12320     LHS = UsualUnaryConversions(LHS.get());
12321     if (LHS.isInvalid())
12322       return QualType();
12323 
12324     RHS = UsualUnaryConversions(RHS.get());
12325     if (RHS.isInvalid())
12326       return QualType();
12327 
12328     if (!LHS.get()->getType()->isScalarType() ||
12329         !RHS.get()->getType()->isScalarType())
12330       return InvalidOperands(Loc, LHS, RHS);
12331 
12332     return Context.IntTy;
12333   }
12334 
12335   // The following is safe because we only use this method for
12336   // non-overloadable operands.
12337 
12338   // C++ [expr.log.and]p1
12339   // C++ [expr.log.or]p1
12340   // The operands are both contextually converted to type bool.
12341   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12342   if (LHSRes.isInvalid())
12343     return InvalidOperands(Loc, LHS, RHS);
12344   LHS = LHSRes;
12345 
12346   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12347   if (RHSRes.isInvalid())
12348     return InvalidOperands(Loc, LHS, RHS);
12349   RHS = RHSRes;
12350 
12351   // C++ [expr.log.and]p2
12352   // C++ [expr.log.or]p2
12353   // The result is a bool.
12354   return Context.BoolTy;
12355 }
12356 
12357 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12358   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12359   if (!ME) return false;
12360   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12361   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12362       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12363   if (!Base) return false;
12364   return Base->getMethodDecl() != nullptr;
12365 }
12366 
12367 /// Is the given expression (which must be 'const') a reference to a
12368 /// variable which was originally non-const, but which has become
12369 /// 'const' due to being captured within a block?
12370 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12371 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12372   assert(E->isLValue() && E->getType().isConstQualified());
12373   E = E->IgnoreParens();
12374 
12375   // Must be a reference to a declaration from an enclosing scope.
12376   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12377   if (!DRE) return NCCK_None;
12378   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12379 
12380   // The declaration must be a variable which is not declared 'const'.
12381   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12382   if (!var) return NCCK_None;
12383   if (var->getType().isConstQualified()) return NCCK_None;
12384   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12385 
12386   // Decide whether the first capture was for a block or a lambda.
12387   DeclContext *DC = S.CurContext, *Prev = nullptr;
12388   // Decide whether the first capture was for a block or a lambda.
12389   while (DC) {
12390     // For init-capture, it is possible that the variable belongs to the
12391     // template pattern of the current context.
12392     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12393       if (var->isInitCapture() &&
12394           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12395         break;
12396     if (DC == var->getDeclContext())
12397       break;
12398     Prev = DC;
12399     DC = DC->getParent();
12400   }
12401   // Unless we have an init-capture, we've gone one step too far.
12402   if (!var->isInitCapture())
12403     DC = Prev;
12404   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12405 }
12406 
12407 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12408   Ty = Ty.getNonReferenceType();
12409   if (IsDereference && Ty->isPointerType())
12410     Ty = Ty->getPointeeType();
12411   return !Ty.isConstQualified();
12412 }
12413 
12414 // Update err_typecheck_assign_const and note_typecheck_assign_const
12415 // when this enum is changed.
12416 enum {
12417   ConstFunction,
12418   ConstVariable,
12419   ConstMember,
12420   ConstMethod,
12421   NestedConstMember,
12422   ConstUnknown,  // Keep as last element
12423 };
12424 
12425 /// Emit the "read-only variable not assignable" error and print notes to give
12426 /// more information about why the variable is not assignable, such as pointing
12427 /// to the declaration of a const variable, showing that a method is const, or
12428 /// that the function is returning a const reference.
12429 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12430                                     SourceLocation Loc) {
12431   SourceRange ExprRange = E->getSourceRange();
12432 
12433   // Only emit one error on the first const found.  All other consts will emit
12434   // a note to the error.
12435   bool DiagnosticEmitted = false;
12436 
12437   // Track if the current expression is the result of a dereference, and if the
12438   // next checked expression is the result of a dereference.
12439   bool IsDereference = false;
12440   bool NextIsDereference = false;
12441 
12442   // Loop to process MemberExpr chains.
12443   while (true) {
12444     IsDereference = NextIsDereference;
12445 
12446     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12447     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12448       NextIsDereference = ME->isArrow();
12449       const ValueDecl *VD = ME->getMemberDecl();
12450       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12451         // Mutable fields can be modified even if the class is const.
12452         if (Field->isMutable()) {
12453           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12454           break;
12455         }
12456 
12457         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12458           if (!DiagnosticEmitted) {
12459             S.Diag(Loc, diag::err_typecheck_assign_const)
12460                 << ExprRange << ConstMember << false /*static*/ << Field
12461                 << Field->getType();
12462             DiagnosticEmitted = true;
12463           }
12464           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12465               << ConstMember << false /*static*/ << Field << Field->getType()
12466               << Field->getSourceRange();
12467         }
12468         E = ME->getBase();
12469         continue;
12470       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12471         if (VDecl->getType().isConstQualified()) {
12472           if (!DiagnosticEmitted) {
12473             S.Diag(Loc, diag::err_typecheck_assign_const)
12474                 << ExprRange << ConstMember << true /*static*/ << VDecl
12475                 << VDecl->getType();
12476             DiagnosticEmitted = true;
12477           }
12478           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12479               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12480               << VDecl->getSourceRange();
12481         }
12482         // Static fields do not inherit constness from parents.
12483         break;
12484       }
12485       break; // End MemberExpr
12486     } else if (const ArraySubscriptExpr *ASE =
12487                    dyn_cast<ArraySubscriptExpr>(E)) {
12488       E = ASE->getBase()->IgnoreParenImpCasts();
12489       continue;
12490     } else if (const ExtVectorElementExpr *EVE =
12491                    dyn_cast<ExtVectorElementExpr>(E)) {
12492       E = EVE->getBase()->IgnoreParenImpCasts();
12493       continue;
12494     }
12495     break;
12496   }
12497 
12498   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12499     // Function calls
12500     const FunctionDecl *FD = CE->getDirectCallee();
12501     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12502       if (!DiagnosticEmitted) {
12503         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12504                                                       << ConstFunction << FD;
12505         DiagnosticEmitted = true;
12506       }
12507       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12508              diag::note_typecheck_assign_const)
12509           << ConstFunction << FD << FD->getReturnType()
12510           << FD->getReturnTypeSourceRange();
12511     }
12512   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12513     // Point to variable declaration.
12514     if (const ValueDecl *VD = DRE->getDecl()) {
12515       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12516         if (!DiagnosticEmitted) {
12517           S.Diag(Loc, diag::err_typecheck_assign_const)
12518               << ExprRange << ConstVariable << VD << VD->getType();
12519           DiagnosticEmitted = true;
12520         }
12521         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12522             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12523       }
12524     }
12525   } else if (isa<CXXThisExpr>(E)) {
12526     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12527       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12528         if (MD->isConst()) {
12529           if (!DiagnosticEmitted) {
12530             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12531                                                           << ConstMethod << MD;
12532             DiagnosticEmitted = true;
12533           }
12534           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12535               << ConstMethod << MD << MD->getSourceRange();
12536         }
12537       }
12538     }
12539   }
12540 
12541   if (DiagnosticEmitted)
12542     return;
12543 
12544   // Can't determine a more specific message, so display the generic error.
12545   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12546 }
12547 
12548 enum OriginalExprKind {
12549   OEK_Variable,
12550   OEK_Member,
12551   OEK_LValue
12552 };
12553 
12554 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12555                                          const RecordType *Ty,
12556                                          SourceLocation Loc, SourceRange Range,
12557                                          OriginalExprKind OEK,
12558                                          bool &DiagnosticEmitted) {
12559   std::vector<const RecordType *> RecordTypeList;
12560   RecordTypeList.push_back(Ty);
12561   unsigned NextToCheckIndex = 0;
12562   // We walk the record hierarchy breadth-first to ensure that we print
12563   // diagnostics in field nesting order.
12564   while (RecordTypeList.size() > NextToCheckIndex) {
12565     bool IsNested = NextToCheckIndex > 0;
12566     for (const FieldDecl *Field :
12567          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12568       // First, check every field for constness.
12569       QualType FieldTy = Field->getType();
12570       if (FieldTy.isConstQualified()) {
12571         if (!DiagnosticEmitted) {
12572           S.Diag(Loc, diag::err_typecheck_assign_const)
12573               << Range << NestedConstMember << OEK << VD
12574               << IsNested << Field;
12575           DiagnosticEmitted = true;
12576         }
12577         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12578             << NestedConstMember << IsNested << Field
12579             << FieldTy << Field->getSourceRange();
12580       }
12581 
12582       // Then we append it to the list to check next in order.
12583       FieldTy = FieldTy.getCanonicalType();
12584       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12585         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12586           RecordTypeList.push_back(FieldRecTy);
12587       }
12588     }
12589     ++NextToCheckIndex;
12590   }
12591 }
12592 
12593 /// Emit an error for the case where a record we are trying to assign to has a
12594 /// const-qualified field somewhere in its hierarchy.
12595 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12596                                          SourceLocation Loc) {
12597   QualType Ty = E->getType();
12598   assert(Ty->isRecordType() && "lvalue was not record?");
12599   SourceRange Range = E->getSourceRange();
12600   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12601   bool DiagEmitted = false;
12602 
12603   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12604     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12605             Range, OEK_Member, DiagEmitted);
12606   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12607     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12608             Range, OEK_Variable, DiagEmitted);
12609   else
12610     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12611             Range, OEK_LValue, DiagEmitted);
12612   if (!DiagEmitted)
12613     DiagnoseConstAssignment(S, E, Loc);
12614 }
12615 
12616 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12617 /// emit an error and return true.  If so, return false.
12618 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12619   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12620 
12621   S.CheckShadowingDeclModification(E, Loc);
12622 
12623   SourceLocation OrigLoc = Loc;
12624   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12625                                                               &Loc);
12626   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12627     IsLV = Expr::MLV_InvalidMessageExpression;
12628   if (IsLV == Expr::MLV_Valid)
12629     return false;
12630 
12631   unsigned DiagID = 0;
12632   bool NeedType = false;
12633   switch (IsLV) { // C99 6.5.16p2
12634   case Expr::MLV_ConstQualified:
12635     // Use a specialized diagnostic when we're assigning to an object
12636     // from an enclosing function or block.
12637     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12638       if (NCCK == NCCK_Block)
12639         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12640       else
12641         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12642       break;
12643     }
12644 
12645     // In ARC, use some specialized diagnostics for occasions where we
12646     // infer 'const'.  These are always pseudo-strong variables.
12647     if (S.getLangOpts().ObjCAutoRefCount) {
12648       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12649       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12650         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12651 
12652         // Use the normal diagnostic if it's pseudo-__strong but the
12653         // user actually wrote 'const'.
12654         if (var->isARCPseudoStrong() &&
12655             (!var->getTypeSourceInfo() ||
12656              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12657           // There are three pseudo-strong cases:
12658           //  - self
12659           ObjCMethodDecl *method = S.getCurMethodDecl();
12660           if (method && var == method->getSelfDecl()) {
12661             DiagID = method->isClassMethod()
12662               ? diag::err_typecheck_arc_assign_self_class_method
12663               : diag::err_typecheck_arc_assign_self;
12664 
12665           //  - Objective-C externally_retained attribute.
12666           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12667                      isa<ParmVarDecl>(var)) {
12668             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12669 
12670           //  - fast enumeration variables
12671           } else {
12672             DiagID = diag::err_typecheck_arr_assign_enumeration;
12673           }
12674 
12675           SourceRange Assign;
12676           if (Loc != OrigLoc)
12677             Assign = SourceRange(OrigLoc, OrigLoc);
12678           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12679           // We need to preserve the AST regardless, so migration tool
12680           // can do its job.
12681           return false;
12682         }
12683       }
12684     }
12685 
12686     // If none of the special cases above are triggered, then this is a
12687     // simple const assignment.
12688     if (DiagID == 0) {
12689       DiagnoseConstAssignment(S, E, Loc);
12690       return true;
12691     }
12692 
12693     break;
12694   case Expr::MLV_ConstAddrSpace:
12695     DiagnoseConstAssignment(S, E, Loc);
12696     return true;
12697   case Expr::MLV_ConstQualifiedField:
12698     DiagnoseRecursiveConstFields(S, E, Loc);
12699     return true;
12700   case Expr::MLV_ArrayType:
12701   case Expr::MLV_ArrayTemporary:
12702     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12703     NeedType = true;
12704     break;
12705   case Expr::MLV_NotObjectType:
12706     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12707     NeedType = true;
12708     break;
12709   case Expr::MLV_LValueCast:
12710     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12711     break;
12712   case Expr::MLV_Valid:
12713     llvm_unreachable("did not take early return for MLV_Valid");
12714   case Expr::MLV_InvalidExpression:
12715   case Expr::MLV_MemberFunction:
12716   case Expr::MLV_ClassTemporary:
12717     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12718     break;
12719   case Expr::MLV_IncompleteType:
12720   case Expr::MLV_IncompleteVoidType:
12721     return S.RequireCompleteType(Loc, E->getType(),
12722              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12723   case Expr::MLV_DuplicateVectorComponents:
12724     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12725     break;
12726   case Expr::MLV_NoSetterProperty:
12727     llvm_unreachable("readonly properties should be processed differently");
12728   case Expr::MLV_InvalidMessageExpression:
12729     DiagID = diag::err_readonly_message_assignment;
12730     break;
12731   case Expr::MLV_SubObjCPropertySetting:
12732     DiagID = diag::err_no_subobject_property_setting;
12733     break;
12734   }
12735 
12736   SourceRange Assign;
12737   if (Loc != OrigLoc)
12738     Assign = SourceRange(OrigLoc, OrigLoc);
12739   if (NeedType)
12740     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12741   else
12742     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12743   return true;
12744 }
12745 
12746 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12747                                          SourceLocation Loc,
12748                                          Sema &Sema) {
12749   if (Sema.inTemplateInstantiation())
12750     return;
12751   if (Sema.isUnevaluatedContext())
12752     return;
12753   if (Loc.isInvalid() || Loc.isMacroID())
12754     return;
12755   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12756     return;
12757 
12758   // C / C++ fields
12759   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12760   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12761   if (ML && MR) {
12762     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12763       return;
12764     const ValueDecl *LHSDecl =
12765         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12766     const ValueDecl *RHSDecl =
12767         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12768     if (LHSDecl != RHSDecl)
12769       return;
12770     if (LHSDecl->getType().isVolatileQualified())
12771       return;
12772     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12773       if (RefTy->getPointeeType().isVolatileQualified())
12774         return;
12775 
12776     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12777   }
12778 
12779   // Objective-C instance variables
12780   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12781   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12782   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12783     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12784     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12785     if (RL && RR && RL->getDecl() == RR->getDecl())
12786       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12787   }
12788 }
12789 
12790 // C99 6.5.16.1
12791 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12792                                        SourceLocation Loc,
12793                                        QualType CompoundType) {
12794   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12795 
12796   // Verify that LHS is a modifiable lvalue, and emit error if not.
12797   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12798     return QualType();
12799 
12800   QualType LHSType = LHSExpr->getType();
12801   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12802                                              CompoundType;
12803   // OpenCL v1.2 s6.1.1.1 p2:
12804   // The half data type can only be used to declare a pointer to a buffer that
12805   // contains half values
12806   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12807     LHSType->isHalfType()) {
12808     Diag(Loc, diag::err_opencl_half_load_store) << 1
12809         << LHSType.getUnqualifiedType();
12810     return QualType();
12811   }
12812 
12813   AssignConvertType ConvTy;
12814   if (CompoundType.isNull()) {
12815     Expr *RHSCheck = RHS.get();
12816 
12817     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12818 
12819     QualType LHSTy(LHSType);
12820     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12821     if (RHS.isInvalid())
12822       return QualType();
12823     // Special case of NSObject attributes on c-style pointer types.
12824     if (ConvTy == IncompatiblePointer &&
12825         ((Context.isObjCNSObjectType(LHSType) &&
12826           RHSType->isObjCObjectPointerType()) ||
12827          (Context.isObjCNSObjectType(RHSType) &&
12828           LHSType->isObjCObjectPointerType())))
12829       ConvTy = Compatible;
12830 
12831     if (ConvTy == Compatible &&
12832         LHSType->isObjCObjectType())
12833         Diag(Loc, diag::err_objc_object_assignment)
12834           << LHSType;
12835 
12836     // If the RHS is a unary plus or minus, check to see if they = and + are
12837     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12838     // instead of "x += 4".
12839     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12840       RHSCheck = ICE->getSubExpr();
12841     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12842       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12843           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12844           // Only if the two operators are exactly adjacent.
12845           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12846           // And there is a space or other character before the subexpr of the
12847           // unary +/-.  We don't want to warn on "x=-1".
12848           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12849           UO->getSubExpr()->getBeginLoc().isFileID()) {
12850         Diag(Loc, diag::warn_not_compound_assign)
12851           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12852           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12853       }
12854     }
12855 
12856     if (ConvTy == Compatible) {
12857       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12858         // Warn about retain cycles where a block captures the LHS, but
12859         // not if the LHS is a simple variable into which the block is
12860         // being stored...unless that variable can be captured by reference!
12861         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12862         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12863         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12864           checkRetainCycles(LHSExpr, RHS.get());
12865       }
12866 
12867       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12868           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12869         // It is safe to assign a weak reference into a strong variable.
12870         // Although this code can still have problems:
12871         //   id x = self.weakProp;
12872         //   id y = self.weakProp;
12873         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12874         // paths through the function. This should be revisited if
12875         // -Wrepeated-use-of-weak is made flow-sensitive.
12876         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12877         // variable, which will be valid for the current autorelease scope.
12878         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12879                              RHS.get()->getBeginLoc()))
12880           getCurFunction()->markSafeWeakUse(RHS.get());
12881 
12882       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12883         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12884       }
12885     }
12886   } else {
12887     // Compound assignment "x += y"
12888     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12889   }
12890 
12891   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12892                                RHS.get(), AA_Assigning))
12893     return QualType();
12894 
12895   CheckForNullPointerDereference(*this, LHSExpr);
12896 
12897   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12898     if (CompoundType.isNull()) {
12899       // C++2a [expr.ass]p5:
12900       //   A simple-assignment whose left operand is of a volatile-qualified
12901       //   type is deprecated unless the assignment is either a discarded-value
12902       //   expression or an unevaluated operand
12903       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12904     } else {
12905       // C++2a [expr.ass]p6:
12906       //   [Compound-assignment] expressions are deprecated if E1 has
12907       //   volatile-qualified type
12908       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12909     }
12910   }
12911 
12912   // C99 6.5.16p3: The type of an assignment expression is the type of the
12913   // left operand unless the left operand has qualified type, in which case
12914   // it is the unqualified version of the type of the left operand.
12915   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12916   // is converted to the type of the assignment expression (above).
12917   // C++ 5.17p1: the type of the assignment expression is that of its left
12918   // operand.
12919   return (getLangOpts().CPlusPlus
12920           ? LHSType : LHSType.getUnqualifiedType());
12921 }
12922 
12923 // Only ignore explicit casts to void.
12924 static bool IgnoreCommaOperand(const Expr *E) {
12925   E = E->IgnoreParens();
12926 
12927   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12928     if (CE->getCastKind() == CK_ToVoid) {
12929       return true;
12930     }
12931 
12932     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12933     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12934         CE->getSubExpr()->getType()->isDependentType()) {
12935       return true;
12936     }
12937   }
12938 
12939   return false;
12940 }
12941 
12942 // Look for instances where it is likely the comma operator is confused with
12943 // another operator.  There is an explicit list of acceptable expressions for
12944 // the left hand side of the comma operator, otherwise emit a warning.
12945 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12946   // No warnings in macros
12947   if (Loc.isMacroID())
12948     return;
12949 
12950   // Don't warn in template instantiations.
12951   if (inTemplateInstantiation())
12952     return;
12953 
12954   // Scope isn't fine-grained enough to explicitly list the specific cases, so
12955   // instead, skip more than needed, then call back into here with the
12956   // CommaVisitor in SemaStmt.cpp.
12957   // The listed locations are the initialization and increment portions
12958   // of a for loop.  The additional checks are on the condition of
12959   // if statements, do/while loops, and for loops.
12960   // Differences in scope flags for C89 mode requires the extra logic.
12961   const unsigned ForIncrementFlags =
12962       getLangOpts().C99 || getLangOpts().CPlusPlus
12963           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12964           : Scope::ContinueScope | Scope::BreakScope;
12965   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12966   const unsigned ScopeFlags = getCurScope()->getFlags();
12967   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12968       (ScopeFlags & ForInitFlags) == ForInitFlags)
12969     return;
12970 
12971   // If there are multiple comma operators used together, get the RHS of the
12972   // of the comma operator as the LHS.
12973   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12974     if (BO->getOpcode() != BO_Comma)
12975       break;
12976     LHS = BO->getRHS();
12977   }
12978 
12979   // Only allow some expressions on LHS to not warn.
12980   if (IgnoreCommaOperand(LHS))
12981     return;
12982 
12983   Diag(Loc, diag::warn_comma_operator);
12984   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12985       << LHS->getSourceRange()
12986       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12987                                     LangOpts.CPlusPlus ? "static_cast<void>("
12988                                                        : "(void)(")
12989       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12990                                     ")");
12991 }
12992 
12993 // C99 6.5.17
12994 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12995                                    SourceLocation Loc) {
12996   LHS = S.CheckPlaceholderExpr(LHS.get());
12997   RHS = S.CheckPlaceholderExpr(RHS.get());
12998   if (LHS.isInvalid() || RHS.isInvalid())
12999     return QualType();
13000 
13001   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13002   // operands, but not unary promotions.
13003   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13004 
13005   // So we treat the LHS as a ignored value, and in C++ we allow the
13006   // containing site to determine what should be done with the RHS.
13007   LHS = S.IgnoredValueConversions(LHS.get());
13008   if (LHS.isInvalid())
13009     return QualType();
13010 
13011   S.DiagnoseUnusedExprResult(LHS.get());
13012 
13013   if (!S.getLangOpts().CPlusPlus) {
13014     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13015     if (RHS.isInvalid())
13016       return QualType();
13017     if (!RHS.get()->getType()->isVoidType())
13018       S.RequireCompleteType(Loc, RHS.get()->getType(),
13019                             diag::err_incomplete_type);
13020   }
13021 
13022   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13023     S.DiagnoseCommaOperator(LHS.get(), Loc);
13024 
13025   return RHS.get()->getType();
13026 }
13027 
13028 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13029 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13030 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13031                                                ExprValueKind &VK,
13032                                                ExprObjectKind &OK,
13033                                                SourceLocation OpLoc,
13034                                                bool IsInc, bool IsPrefix) {
13035   if (Op->isTypeDependent())
13036     return S.Context.DependentTy;
13037 
13038   QualType ResType = Op->getType();
13039   // Atomic types can be used for increment / decrement where the non-atomic
13040   // versions can, so ignore the _Atomic() specifier for the purpose of
13041   // checking.
13042   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13043     ResType = ResAtomicType->getValueType();
13044 
13045   assert(!ResType.isNull() && "no type for increment/decrement expression");
13046 
13047   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13048     // Decrement of bool is not allowed.
13049     if (!IsInc) {
13050       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13051       return QualType();
13052     }
13053     // Increment of bool sets it to true, but is deprecated.
13054     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13055                                               : diag::warn_increment_bool)
13056       << Op->getSourceRange();
13057   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13058     // Error on enum increments and decrements in C++ mode
13059     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13060     return QualType();
13061   } else if (ResType->isRealType()) {
13062     // OK!
13063   } else if (ResType->isPointerType()) {
13064     // C99 6.5.2.4p2, 6.5.6p2
13065     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13066       return QualType();
13067   } else if (ResType->isObjCObjectPointerType()) {
13068     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13069     // Otherwise, we just need a complete type.
13070     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13071         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13072       return QualType();
13073   } else if (ResType->isAnyComplexType()) {
13074     // C99 does not support ++/-- on complex types, we allow as an extension.
13075     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13076       << ResType << Op->getSourceRange();
13077   } else if (ResType->isPlaceholderType()) {
13078     ExprResult PR = S.CheckPlaceholderExpr(Op);
13079     if (PR.isInvalid()) return QualType();
13080     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13081                                           IsInc, IsPrefix);
13082   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13083     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13084   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13085              (ResType->castAs<VectorType>()->getVectorKind() !=
13086               VectorType::AltiVecBool)) {
13087     // The z vector extensions allow ++ and -- for non-bool vectors.
13088   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13089             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13090     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13091   } else {
13092     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13093       << ResType << int(IsInc) << Op->getSourceRange();
13094     return QualType();
13095   }
13096   // At this point, we know we have a real, complex or pointer type.
13097   // Now make sure the operand is a modifiable lvalue.
13098   if (CheckForModifiableLvalue(Op, OpLoc, S))
13099     return QualType();
13100   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13101     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13102     //   An operand with volatile-qualified type is deprecated
13103     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13104         << IsInc << ResType;
13105   }
13106   // In C++, a prefix increment is the same type as the operand. Otherwise
13107   // (in C or with postfix), the increment is the unqualified type of the
13108   // operand.
13109   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13110     VK = VK_LValue;
13111     OK = Op->getObjectKind();
13112     return ResType;
13113   } else {
13114     VK = VK_RValue;
13115     return ResType.getUnqualifiedType();
13116   }
13117 }
13118 
13119 
13120 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13121 /// This routine allows us to typecheck complex/recursive expressions
13122 /// where the declaration is needed for type checking. We only need to
13123 /// handle cases when the expression references a function designator
13124 /// or is an lvalue. Here are some examples:
13125 ///  - &(x) => x
13126 ///  - &*****f => f for f a function designator.
13127 ///  - &s.xx => s
13128 ///  - &s.zz[1].yy -> s, if zz is an array
13129 ///  - *(x + 1) -> x, if x is an array
13130 ///  - &"123"[2] -> 0
13131 ///  - & __real__ x -> x
13132 ///
13133 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13134 /// members.
13135 static ValueDecl *getPrimaryDecl(Expr *E) {
13136   switch (E->getStmtClass()) {
13137   case Stmt::DeclRefExprClass:
13138     return cast<DeclRefExpr>(E)->getDecl();
13139   case Stmt::MemberExprClass:
13140     // If this is an arrow operator, the address is an offset from
13141     // the base's value, so the object the base refers to is
13142     // irrelevant.
13143     if (cast<MemberExpr>(E)->isArrow())
13144       return nullptr;
13145     // Otherwise, the expression refers to a part of the base
13146     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13147   case Stmt::ArraySubscriptExprClass: {
13148     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13149     // promotion of register arrays earlier.
13150     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13151     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13152       if (ICE->getSubExpr()->getType()->isArrayType())
13153         return getPrimaryDecl(ICE->getSubExpr());
13154     }
13155     return nullptr;
13156   }
13157   case Stmt::UnaryOperatorClass: {
13158     UnaryOperator *UO = cast<UnaryOperator>(E);
13159 
13160     switch(UO->getOpcode()) {
13161     case UO_Real:
13162     case UO_Imag:
13163     case UO_Extension:
13164       return getPrimaryDecl(UO->getSubExpr());
13165     default:
13166       return nullptr;
13167     }
13168   }
13169   case Stmt::ParenExprClass:
13170     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13171   case Stmt::ImplicitCastExprClass:
13172     // If the result of an implicit cast is an l-value, we care about
13173     // the sub-expression; otherwise, the result here doesn't matter.
13174     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13175   case Stmt::CXXUuidofExprClass:
13176     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13177   default:
13178     return nullptr;
13179   }
13180 }
13181 
13182 namespace {
13183 enum {
13184   AO_Bit_Field = 0,
13185   AO_Vector_Element = 1,
13186   AO_Property_Expansion = 2,
13187   AO_Register_Variable = 3,
13188   AO_Matrix_Element = 4,
13189   AO_No_Error = 5
13190 };
13191 }
13192 /// Diagnose invalid operand for address of operations.
13193 ///
13194 /// \param Type The type of operand which cannot have its address taken.
13195 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13196                                          Expr *E, unsigned Type) {
13197   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13198 }
13199 
13200 /// CheckAddressOfOperand - The operand of & must be either a function
13201 /// designator or an lvalue designating an object. If it is an lvalue, the
13202 /// object cannot be declared with storage class register or be a bit field.
13203 /// Note: The usual conversions are *not* applied to the operand of the &
13204 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13205 /// In C++, the operand might be an overloaded function name, in which case
13206 /// we allow the '&' but retain the overloaded-function type.
13207 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13208   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13209     if (PTy->getKind() == BuiltinType::Overload) {
13210       Expr *E = OrigOp.get()->IgnoreParens();
13211       if (!isa<OverloadExpr>(E)) {
13212         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13213         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13214           << OrigOp.get()->getSourceRange();
13215         return QualType();
13216       }
13217 
13218       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13219       if (isa<UnresolvedMemberExpr>(Ovl))
13220         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13221           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13222             << OrigOp.get()->getSourceRange();
13223           return QualType();
13224         }
13225 
13226       return Context.OverloadTy;
13227     }
13228 
13229     if (PTy->getKind() == BuiltinType::UnknownAny)
13230       return Context.UnknownAnyTy;
13231 
13232     if (PTy->getKind() == BuiltinType::BoundMember) {
13233       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13234         << OrigOp.get()->getSourceRange();
13235       return QualType();
13236     }
13237 
13238     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13239     if (OrigOp.isInvalid()) return QualType();
13240   }
13241 
13242   if (OrigOp.get()->isTypeDependent())
13243     return Context.DependentTy;
13244 
13245   assert(!OrigOp.get()->getType()->isPlaceholderType());
13246 
13247   // Make sure to ignore parentheses in subsequent checks
13248   Expr *op = OrigOp.get()->IgnoreParens();
13249 
13250   // In OpenCL captures for blocks called as lambda functions
13251   // are located in the private address space. Blocks used in
13252   // enqueue_kernel can be located in a different address space
13253   // depending on a vendor implementation. Thus preventing
13254   // taking an address of the capture to avoid invalid AS casts.
13255   if (LangOpts.OpenCL) {
13256     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13257     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13258       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13259       return QualType();
13260     }
13261   }
13262 
13263   if (getLangOpts().C99) {
13264     // Implement C99-only parts of addressof rules.
13265     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13266       if (uOp->getOpcode() == UO_Deref)
13267         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13268         // (assuming the deref expression is valid).
13269         return uOp->getSubExpr()->getType();
13270     }
13271     // Technically, there should be a check for array subscript
13272     // expressions here, but the result of one is always an lvalue anyway.
13273   }
13274   ValueDecl *dcl = getPrimaryDecl(op);
13275 
13276   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13277     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13278                                            op->getBeginLoc()))
13279       return QualType();
13280 
13281   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13282   unsigned AddressOfError = AO_No_Error;
13283 
13284   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13285     bool sfinae = (bool)isSFINAEContext();
13286     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13287                                   : diag::ext_typecheck_addrof_temporary)
13288       << op->getType() << op->getSourceRange();
13289     if (sfinae)
13290       return QualType();
13291     // Materialize the temporary as an lvalue so that we can take its address.
13292     OrigOp = op =
13293         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13294   } else if (isa<ObjCSelectorExpr>(op)) {
13295     return Context.getPointerType(op->getType());
13296   } else if (lval == Expr::LV_MemberFunction) {
13297     // If it's an instance method, make a member pointer.
13298     // The expression must have exactly the form &A::foo.
13299 
13300     // If the underlying expression isn't a decl ref, give up.
13301     if (!isa<DeclRefExpr>(op)) {
13302       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13303         << OrigOp.get()->getSourceRange();
13304       return QualType();
13305     }
13306     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13307     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13308 
13309     // The id-expression was parenthesized.
13310     if (OrigOp.get() != DRE) {
13311       Diag(OpLoc, diag::err_parens_pointer_member_function)
13312         << OrigOp.get()->getSourceRange();
13313 
13314     // The method was named without a qualifier.
13315     } else if (!DRE->getQualifier()) {
13316       if (MD->getParent()->getName().empty())
13317         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13318           << op->getSourceRange();
13319       else {
13320         SmallString<32> Str;
13321         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13322         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13323           << op->getSourceRange()
13324           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13325       }
13326     }
13327 
13328     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13329     if (isa<CXXDestructorDecl>(MD))
13330       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13331 
13332     QualType MPTy = Context.getMemberPointerType(
13333         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13334     // Under the MS ABI, lock down the inheritance model now.
13335     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13336       (void)isCompleteType(OpLoc, MPTy);
13337     return MPTy;
13338   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13339     // C99 6.5.3.2p1
13340     // The operand must be either an l-value or a function designator
13341     if (!op->getType()->isFunctionType()) {
13342       // Use a special diagnostic for loads from property references.
13343       if (isa<PseudoObjectExpr>(op)) {
13344         AddressOfError = AO_Property_Expansion;
13345       } else {
13346         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13347           << op->getType() << op->getSourceRange();
13348         return QualType();
13349       }
13350     }
13351   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13352     // The operand cannot be a bit-field
13353     AddressOfError = AO_Bit_Field;
13354   } else if (op->getObjectKind() == OK_VectorComponent) {
13355     // The operand cannot be an element of a vector
13356     AddressOfError = AO_Vector_Element;
13357   } else if (op->getObjectKind() == OK_MatrixComponent) {
13358     // The operand cannot be an element of a matrix.
13359     AddressOfError = AO_Matrix_Element;
13360   } else if (dcl) { // C99 6.5.3.2p1
13361     // We have an lvalue with a decl. Make sure the decl is not declared
13362     // with the register storage-class specifier.
13363     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13364       // in C++ it is not error to take address of a register
13365       // variable (c++03 7.1.1P3)
13366       if (vd->getStorageClass() == SC_Register &&
13367           !getLangOpts().CPlusPlus) {
13368         AddressOfError = AO_Register_Variable;
13369       }
13370     } else if (isa<MSPropertyDecl>(dcl)) {
13371       AddressOfError = AO_Property_Expansion;
13372     } else if (isa<FunctionTemplateDecl>(dcl)) {
13373       return Context.OverloadTy;
13374     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13375       // Okay: we can take the address of a field.
13376       // Could be a pointer to member, though, if there is an explicit
13377       // scope qualifier for the class.
13378       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13379         DeclContext *Ctx = dcl->getDeclContext();
13380         if (Ctx && Ctx->isRecord()) {
13381           if (dcl->getType()->isReferenceType()) {
13382             Diag(OpLoc,
13383                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13384               << dcl->getDeclName() << dcl->getType();
13385             return QualType();
13386           }
13387 
13388           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13389             Ctx = Ctx->getParent();
13390 
13391           QualType MPTy = Context.getMemberPointerType(
13392               op->getType(),
13393               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13394           // Under the MS ABI, lock down the inheritance model now.
13395           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13396             (void)isCompleteType(OpLoc, MPTy);
13397           return MPTy;
13398         }
13399       }
13400     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13401                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13402       llvm_unreachable("Unknown/unexpected decl type");
13403   }
13404 
13405   if (AddressOfError != AO_No_Error) {
13406     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13407     return QualType();
13408   }
13409 
13410   if (lval == Expr::LV_IncompleteVoidType) {
13411     // Taking the address of a void variable is technically illegal, but we
13412     // allow it in cases which are otherwise valid.
13413     // Example: "extern void x; void* y = &x;".
13414     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13415   }
13416 
13417   // If the operand has type "type", the result has type "pointer to type".
13418   if (op->getType()->isObjCObjectType())
13419     return Context.getObjCObjectPointerType(op->getType());
13420 
13421   CheckAddressOfPackedMember(op);
13422 
13423   return Context.getPointerType(op->getType());
13424 }
13425 
13426 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13427   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13428   if (!DRE)
13429     return;
13430   const Decl *D = DRE->getDecl();
13431   if (!D)
13432     return;
13433   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13434   if (!Param)
13435     return;
13436   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13437     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13438       return;
13439   if (FunctionScopeInfo *FD = S.getCurFunction())
13440     if (!FD->ModifiedNonNullParams.count(Param))
13441       FD->ModifiedNonNullParams.insert(Param);
13442 }
13443 
13444 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13445 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13446                                         SourceLocation OpLoc) {
13447   if (Op->isTypeDependent())
13448     return S.Context.DependentTy;
13449 
13450   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13451   if (ConvResult.isInvalid())
13452     return QualType();
13453   Op = ConvResult.get();
13454   QualType OpTy = Op->getType();
13455   QualType Result;
13456 
13457   if (isa<CXXReinterpretCastExpr>(Op)) {
13458     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13459     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13460                                      Op->getSourceRange());
13461   }
13462 
13463   if (const PointerType *PT = OpTy->getAs<PointerType>())
13464   {
13465     Result = PT->getPointeeType();
13466   }
13467   else if (const ObjCObjectPointerType *OPT =
13468              OpTy->getAs<ObjCObjectPointerType>())
13469     Result = OPT->getPointeeType();
13470   else {
13471     ExprResult PR = S.CheckPlaceholderExpr(Op);
13472     if (PR.isInvalid()) return QualType();
13473     if (PR.get() != Op)
13474       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13475   }
13476 
13477   if (Result.isNull()) {
13478     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13479       << OpTy << Op->getSourceRange();
13480     return QualType();
13481   }
13482 
13483   // Note that per both C89 and C99, indirection is always legal, even if Result
13484   // is an incomplete type or void.  It would be possible to warn about
13485   // dereferencing a void pointer, but it's completely well-defined, and such a
13486   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13487   // for pointers to 'void' but is fine for any other pointer type:
13488   //
13489   // C++ [expr.unary.op]p1:
13490   //   [...] the expression to which [the unary * operator] is applied shall
13491   //   be a pointer to an object type, or a pointer to a function type
13492   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13493     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13494       << OpTy << Op->getSourceRange();
13495 
13496   // Dereferences are usually l-values...
13497   VK = VK_LValue;
13498 
13499   // ...except that certain expressions are never l-values in C.
13500   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13501     VK = VK_RValue;
13502 
13503   return Result;
13504 }
13505 
13506 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13507   BinaryOperatorKind Opc;
13508   switch (Kind) {
13509   default: llvm_unreachable("Unknown binop!");
13510   case tok::periodstar:           Opc = BO_PtrMemD; break;
13511   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13512   case tok::star:                 Opc = BO_Mul; break;
13513   case tok::slash:                Opc = BO_Div; break;
13514   case tok::percent:              Opc = BO_Rem; break;
13515   case tok::plus:                 Opc = BO_Add; break;
13516   case tok::minus:                Opc = BO_Sub; break;
13517   case tok::lessless:             Opc = BO_Shl; break;
13518   case tok::greatergreater:       Opc = BO_Shr; break;
13519   case tok::lessequal:            Opc = BO_LE; break;
13520   case tok::less:                 Opc = BO_LT; break;
13521   case tok::greaterequal:         Opc = BO_GE; break;
13522   case tok::greater:              Opc = BO_GT; break;
13523   case tok::exclaimequal:         Opc = BO_NE; break;
13524   case tok::equalequal:           Opc = BO_EQ; break;
13525   case tok::spaceship:            Opc = BO_Cmp; break;
13526   case tok::amp:                  Opc = BO_And; break;
13527   case tok::caret:                Opc = BO_Xor; break;
13528   case tok::pipe:                 Opc = BO_Or; break;
13529   case tok::ampamp:               Opc = BO_LAnd; break;
13530   case tok::pipepipe:             Opc = BO_LOr; break;
13531   case tok::equal:                Opc = BO_Assign; break;
13532   case tok::starequal:            Opc = BO_MulAssign; break;
13533   case tok::slashequal:           Opc = BO_DivAssign; break;
13534   case tok::percentequal:         Opc = BO_RemAssign; break;
13535   case tok::plusequal:            Opc = BO_AddAssign; break;
13536   case tok::minusequal:           Opc = BO_SubAssign; break;
13537   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13538   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13539   case tok::ampequal:             Opc = BO_AndAssign; break;
13540   case tok::caretequal:           Opc = BO_XorAssign; break;
13541   case tok::pipeequal:            Opc = BO_OrAssign; break;
13542   case tok::comma:                Opc = BO_Comma; break;
13543   }
13544   return Opc;
13545 }
13546 
13547 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13548   tok::TokenKind Kind) {
13549   UnaryOperatorKind Opc;
13550   switch (Kind) {
13551   default: llvm_unreachable("Unknown unary op!");
13552   case tok::plusplus:     Opc = UO_PreInc; break;
13553   case tok::minusminus:   Opc = UO_PreDec; break;
13554   case tok::amp:          Opc = UO_AddrOf; break;
13555   case tok::star:         Opc = UO_Deref; break;
13556   case tok::plus:         Opc = UO_Plus; break;
13557   case tok::minus:        Opc = UO_Minus; break;
13558   case tok::tilde:        Opc = UO_Not; break;
13559   case tok::exclaim:      Opc = UO_LNot; break;
13560   case tok::kw___real:    Opc = UO_Real; break;
13561   case tok::kw___imag:    Opc = UO_Imag; break;
13562   case tok::kw___extension__: Opc = UO_Extension; break;
13563   }
13564   return Opc;
13565 }
13566 
13567 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13568 /// This warning suppressed in the event of macro expansions.
13569 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13570                                    SourceLocation OpLoc, bool IsBuiltin) {
13571   if (S.inTemplateInstantiation())
13572     return;
13573   if (S.isUnevaluatedContext())
13574     return;
13575   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13576     return;
13577   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13578   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13579   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13580   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13581   if (!LHSDeclRef || !RHSDeclRef ||
13582       LHSDeclRef->getLocation().isMacroID() ||
13583       RHSDeclRef->getLocation().isMacroID())
13584     return;
13585   const ValueDecl *LHSDecl =
13586     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13587   const ValueDecl *RHSDecl =
13588     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13589   if (LHSDecl != RHSDecl)
13590     return;
13591   if (LHSDecl->getType().isVolatileQualified())
13592     return;
13593   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13594     if (RefTy->getPointeeType().isVolatileQualified())
13595       return;
13596 
13597   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13598                           : diag::warn_self_assignment_overloaded)
13599       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13600       << RHSExpr->getSourceRange();
13601 }
13602 
13603 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13604 /// is usually indicative of introspection within the Objective-C pointer.
13605 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13606                                           SourceLocation OpLoc) {
13607   if (!S.getLangOpts().ObjC)
13608     return;
13609 
13610   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13611   const Expr *LHS = L.get();
13612   const Expr *RHS = R.get();
13613 
13614   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13615     ObjCPointerExpr = LHS;
13616     OtherExpr = RHS;
13617   }
13618   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13619     ObjCPointerExpr = RHS;
13620     OtherExpr = LHS;
13621   }
13622 
13623   // This warning is deliberately made very specific to reduce false
13624   // positives with logic that uses '&' for hashing.  This logic mainly
13625   // looks for code trying to introspect into tagged pointers, which
13626   // code should generally never do.
13627   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13628     unsigned Diag = diag::warn_objc_pointer_masking;
13629     // Determine if we are introspecting the result of performSelectorXXX.
13630     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13631     // Special case messages to -performSelector and friends, which
13632     // can return non-pointer values boxed in a pointer value.
13633     // Some clients may wish to silence warnings in this subcase.
13634     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13635       Selector S = ME->getSelector();
13636       StringRef SelArg0 = S.getNameForSlot(0);
13637       if (SelArg0.startswith("performSelector"))
13638         Diag = diag::warn_objc_pointer_masking_performSelector;
13639     }
13640 
13641     S.Diag(OpLoc, Diag)
13642       << ObjCPointerExpr->getSourceRange();
13643   }
13644 }
13645 
13646 static NamedDecl *getDeclFromExpr(Expr *E) {
13647   if (!E)
13648     return nullptr;
13649   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13650     return DRE->getDecl();
13651   if (auto *ME = dyn_cast<MemberExpr>(E))
13652     return ME->getMemberDecl();
13653   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13654     return IRE->getDecl();
13655   return nullptr;
13656 }
13657 
13658 // This helper function promotes a binary operator's operands (which are of a
13659 // half vector type) to a vector of floats and then truncates the result to
13660 // a vector of either half or short.
13661 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13662                                       BinaryOperatorKind Opc, QualType ResultTy,
13663                                       ExprValueKind VK, ExprObjectKind OK,
13664                                       bool IsCompAssign, SourceLocation OpLoc,
13665                                       FPOptionsOverride FPFeatures) {
13666   auto &Context = S.getASTContext();
13667   assert((isVector(ResultTy, Context.HalfTy) ||
13668           isVector(ResultTy, Context.ShortTy)) &&
13669          "Result must be a vector of half or short");
13670   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13671          isVector(RHS.get()->getType(), Context.HalfTy) &&
13672          "both operands expected to be a half vector");
13673 
13674   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13675   QualType BinOpResTy = RHS.get()->getType();
13676 
13677   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13678   // change BinOpResTy to a vector of ints.
13679   if (isVector(ResultTy, Context.ShortTy))
13680     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13681 
13682   if (IsCompAssign)
13683     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13684                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13685                                           BinOpResTy, BinOpResTy);
13686 
13687   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13688   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13689                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13690   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13691 }
13692 
13693 static std::pair<ExprResult, ExprResult>
13694 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13695                            Expr *RHSExpr) {
13696   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13697   if (!S.Context.isDependenceAllowed()) {
13698     // C cannot handle TypoExpr nodes on either side of a binop because it
13699     // doesn't handle dependent types properly, so make sure any TypoExprs have
13700     // been dealt with before checking the operands.
13701     LHS = S.CorrectDelayedTyposInExpr(LHS);
13702     RHS = S.CorrectDelayedTyposInExpr(
13703         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13704         [Opc, LHS](Expr *E) {
13705           if (Opc != BO_Assign)
13706             return ExprResult(E);
13707           // Avoid correcting the RHS to the same Expr as the LHS.
13708           Decl *D = getDeclFromExpr(E);
13709           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13710         });
13711   }
13712   return std::make_pair(LHS, RHS);
13713 }
13714 
13715 /// Returns true if conversion between vectors of halfs and vectors of floats
13716 /// is needed.
13717 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13718                                      Expr *E0, Expr *E1 = nullptr) {
13719   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13720       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13721     return false;
13722 
13723   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13724     QualType Ty = E->IgnoreImplicit()->getType();
13725 
13726     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13727     // to vectors of floats. Although the element type of the vectors is __fp16,
13728     // the vectors shouldn't be treated as storage-only types. See the
13729     // discussion here: https://reviews.llvm.org/rG825235c140e7
13730     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13731       if (VT->getVectorKind() == VectorType::NeonVector)
13732         return false;
13733       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13734     }
13735     return false;
13736   };
13737 
13738   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13739 }
13740 
13741 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13742 /// operator @p Opc at location @c TokLoc. This routine only supports
13743 /// built-in operations; ActOnBinOp handles overloaded operators.
13744 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13745                                     BinaryOperatorKind Opc,
13746                                     Expr *LHSExpr, Expr *RHSExpr) {
13747   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13748     // The syntax only allows initializer lists on the RHS of assignment,
13749     // so we don't need to worry about accepting invalid code for
13750     // non-assignment operators.
13751     // C++11 5.17p9:
13752     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13753     //   of x = {} is x = T().
13754     InitializationKind Kind = InitializationKind::CreateDirectList(
13755         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13756     InitializedEntity Entity =
13757         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13758     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13759     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13760     if (Init.isInvalid())
13761       return Init;
13762     RHSExpr = Init.get();
13763   }
13764 
13765   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13766   QualType ResultTy;     // Result type of the binary operator.
13767   // The following two variables are used for compound assignment operators
13768   QualType CompLHSTy;    // Type of LHS after promotions for computation
13769   QualType CompResultTy; // Type of computation result
13770   ExprValueKind VK = VK_RValue;
13771   ExprObjectKind OK = OK_Ordinary;
13772   bool ConvertHalfVec = false;
13773 
13774   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13775   if (!LHS.isUsable() || !RHS.isUsable())
13776     return ExprError();
13777 
13778   if (getLangOpts().OpenCL) {
13779     QualType LHSTy = LHSExpr->getType();
13780     QualType RHSTy = RHSExpr->getType();
13781     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13782     // the ATOMIC_VAR_INIT macro.
13783     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13784       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13785       if (BO_Assign == Opc)
13786         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13787       else
13788         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13789       return ExprError();
13790     }
13791 
13792     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13793     // only with a builtin functions and therefore should be disallowed here.
13794     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13795         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13796         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13797         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13798       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13799       return ExprError();
13800     }
13801   }
13802 
13803   switch (Opc) {
13804   case BO_Assign:
13805     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13806     if (getLangOpts().CPlusPlus &&
13807         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13808       VK = LHS.get()->getValueKind();
13809       OK = LHS.get()->getObjectKind();
13810     }
13811     if (!ResultTy.isNull()) {
13812       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13813       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13814 
13815       // Avoid copying a block to the heap if the block is assigned to a local
13816       // auto variable that is declared in the same scope as the block. This
13817       // optimization is unsafe if the local variable is declared in an outer
13818       // scope. For example:
13819       //
13820       // BlockTy b;
13821       // {
13822       //   b = ^{...};
13823       // }
13824       // // It is unsafe to invoke the block here if it wasn't copied to the
13825       // // heap.
13826       // b();
13827 
13828       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13829         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13830           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13831             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13832               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13833 
13834       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13835         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13836                               NTCUC_Assignment, NTCUK_Copy);
13837     }
13838     RecordModifiableNonNullParam(*this, LHS.get());
13839     break;
13840   case BO_PtrMemD:
13841   case BO_PtrMemI:
13842     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13843                                             Opc == BO_PtrMemI);
13844     break;
13845   case BO_Mul:
13846   case BO_Div:
13847     ConvertHalfVec = true;
13848     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13849                                            Opc == BO_Div);
13850     break;
13851   case BO_Rem:
13852     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13853     break;
13854   case BO_Add:
13855     ConvertHalfVec = true;
13856     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13857     break;
13858   case BO_Sub:
13859     ConvertHalfVec = true;
13860     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13861     break;
13862   case BO_Shl:
13863   case BO_Shr:
13864     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13865     break;
13866   case BO_LE:
13867   case BO_LT:
13868   case BO_GE:
13869   case BO_GT:
13870     ConvertHalfVec = true;
13871     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13872     break;
13873   case BO_EQ:
13874   case BO_NE:
13875     ConvertHalfVec = true;
13876     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13877     break;
13878   case BO_Cmp:
13879     ConvertHalfVec = true;
13880     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13881     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13882     break;
13883   case BO_And:
13884     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13885     LLVM_FALLTHROUGH;
13886   case BO_Xor:
13887   case BO_Or:
13888     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13889     break;
13890   case BO_LAnd:
13891   case BO_LOr:
13892     ConvertHalfVec = true;
13893     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13894     break;
13895   case BO_MulAssign:
13896   case BO_DivAssign:
13897     ConvertHalfVec = true;
13898     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13899                                                Opc == BO_DivAssign);
13900     CompLHSTy = CompResultTy;
13901     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13902       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13903     break;
13904   case BO_RemAssign:
13905     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13906     CompLHSTy = CompResultTy;
13907     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13908       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13909     break;
13910   case BO_AddAssign:
13911     ConvertHalfVec = true;
13912     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13913     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13914       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13915     break;
13916   case BO_SubAssign:
13917     ConvertHalfVec = true;
13918     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13919     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13920       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13921     break;
13922   case BO_ShlAssign:
13923   case BO_ShrAssign:
13924     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13925     CompLHSTy = CompResultTy;
13926     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13927       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13928     break;
13929   case BO_AndAssign:
13930   case BO_OrAssign: // fallthrough
13931     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13932     LLVM_FALLTHROUGH;
13933   case BO_XorAssign:
13934     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13935     CompLHSTy = CompResultTy;
13936     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13937       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13938     break;
13939   case BO_Comma:
13940     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13941     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13942       VK = RHS.get()->getValueKind();
13943       OK = RHS.get()->getObjectKind();
13944     }
13945     break;
13946   }
13947   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13948     return ExprError();
13949 
13950   // Some of the binary operations require promoting operands of half vector to
13951   // float vectors and truncating the result back to half vector. For now, we do
13952   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13953   // arm64).
13954   assert(
13955       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
13956                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
13957       "both sides are half vectors or neither sides are");
13958   ConvertHalfVec =
13959       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13960 
13961   // Check for array bounds violations for both sides of the BinaryOperator
13962   CheckArrayAccess(LHS.get());
13963   CheckArrayAccess(RHS.get());
13964 
13965   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13966     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13967                                                  &Context.Idents.get("object_setClass"),
13968                                                  SourceLocation(), LookupOrdinaryName);
13969     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13970       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13971       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13972           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13973                                         "object_setClass(")
13974           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13975                                           ",")
13976           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13977     }
13978     else
13979       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13980   }
13981   else if (const ObjCIvarRefExpr *OIRE =
13982            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13983     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13984 
13985   // Opc is not a compound assignment if CompResultTy is null.
13986   if (CompResultTy.isNull()) {
13987     if (ConvertHalfVec)
13988       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13989                                  OpLoc, CurFPFeatureOverrides());
13990     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
13991                                   VK, OK, OpLoc, CurFPFeatureOverrides());
13992   }
13993 
13994   // Handle compound assignments.
13995   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13996       OK_ObjCProperty) {
13997     VK = VK_LValue;
13998     OK = LHS.get()->getObjectKind();
13999   }
14000 
14001   // The LHS is not converted to the result type for fixed-point compound
14002   // assignment as the common type is computed on demand. Reset the CompLHSTy
14003   // to the LHS type we would have gotten after unary conversions.
14004   if (CompResultTy->isFixedPointType())
14005     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14006 
14007   if (ConvertHalfVec)
14008     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14009                                OpLoc, CurFPFeatureOverrides());
14010 
14011   return CompoundAssignOperator::Create(
14012       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14013       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14014 }
14015 
14016 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14017 /// operators are mixed in a way that suggests that the programmer forgot that
14018 /// comparison operators have higher precedence. The most typical example of
14019 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14020 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14021                                       SourceLocation OpLoc, Expr *LHSExpr,
14022                                       Expr *RHSExpr) {
14023   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14024   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14025 
14026   // Check that one of the sides is a comparison operator and the other isn't.
14027   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14028   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14029   if (isLeftComp == isRightComp)
14030     return;
14031 
14032   // Bitwise operations are sometimes used as eager logical ops.
14033   // Don't diagnose this.
14034   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14035   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14036   if (isLeftBitwise || isRightBitwise)
14037     return;
14038 
14039   SourceRange DiagRange = isLeftComp
14040                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14041                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14042   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14043   SourceRange ParensRange =
14044       isLeftComp
14045           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14046           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14047 
14048   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14049     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14050   SuggestParentheses(Self, OpLoc,
14051     Self.PDiag(diag::note_precedence_silence) << OpStr,
14052     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14053   SuggestParentheses(Self, OpLoc,
14054     Self.PDiag(diag::note_precedence_bitwise_first)
14055       << BinaryOperator::getOpcodeStr(Opc),
14056     ParensRange);
14057 }
14058 
14059 /// It accepts a '&&' expr that is inside a '||' one.
14060 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14061 /// in parentheses.
14062 static void
14063 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14064                                        BinaryOperator *Bop) {
14065   assert(Bop->getOpcode() == BO_LAnd);
14066   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14067       << Bop->getSourceRange() << OpLoc;
14068   SuggestParentheses(Self, Bop->getOperatorLoc(),
14069     Self.PDiag(diag::note_precedence_silence)
14070       << Bop->getOpcodeStr(),
14071     Bop->getSourceRange());
14072 }
14073 
14074 /// Returns true if the given expression can be evaluated as a constant
14075 /// 'true'.
14076 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14077   bool Res;
14078   return !E->isValueDependent() &&
14079          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14080 }
14081 
14082 /// Returns true if the given expression can be evaluated as a constant
14083 /// 'false'.
14084 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14085   bool Res;
14086   return !E->isValueDependent() &&
14087          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14088 }
14089 
14090 /// Look for '&&' in the left hand of a '||' expr.
14091 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14092                                              Expr *LHSExpr, Expr *RHSExpr) {
14093   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14094     if (Bop->getOpcode() == BO_LAnd) {
14095       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14096       if (EvaluatesAsFalse(S, RHSExpr))
14097         return;
14098       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14099       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14100         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14101     } else if (Bop->getOpcode() == BO_LOr) {
14102       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14103         // If it's "a || b && 1 || c" we didn't warn earlier for
14104         // "a || b && 1", but warn now.
14105         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14106           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14107       }
14108     }
14109   }
14110 }
14111 
14112 /// Look for '&&' in the right hand of a '||' expr.
14113 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14114                                              Expr *LHSExpr, Expr *RHSExpr) {
14115   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14116     if (Bop->getOpcode() == BO_LAnd) {
14117       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14118       if (EvaluatesAsFalse(S, LHSExpr))
14119         return;
14120       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14121       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14122         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14123     }
14124   }
14125 }
14126 
14127 /// Look for bitwise op in the left or right hand of a bitwise op with
14128 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14129 /// the '&' expression in parentheses.
14130 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14131                                          SourceLocation OpLoc, Expr *SubExpr) {
14132   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14133     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14134       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14135         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14136         << Bop->getSourceRange() << OpLoc;
14137       SuggestParentheses(S, Bop->getOperatorLoc(),
14138         S.PDiag(diag::note_precedence_silence)
14139           << Bop->getOpcodeStr(),
14140         Bop->getSourceRange());
14141     }
14142   }
14143 }
14144 
14145 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14146                                     Expr *SubExpr, StringRef Shift) {
14147   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14148     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14149       StringRef Op = Bop->getOpcodeStr();
14150       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14151           << Bop->getSourceRange() << OpLoc << Shift << Op;
14152       SuggestParentheses(S, Bop->getOperatorLoc(),
14153           S.PDiag(diag::note_precedence_silence) << Op,
14154           Bop->getSourceRange());
14155     }
14156   }
14157 }
14158 
14159 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14160                                  Expr *LHSExpr, Expr *RHSExpr) {
14161   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14162   if (!OCE)
14163     return;
14164 
14165   FunctionDecl *FD = OCE->getDirectCallee();
14166   if (!FD || !FD->isOverloadedOperator())
14167     return;
14168 
14169   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14170   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14171     return;
14172 
14173   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14174       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14175       << (Kind == OO_LessLess);
14176   SuggestParentheses(S, OCE->getOperatorLoc(),
14177                      S.PDiag(diag::note_precedence_silence)
14178                          << (Kind == OO_LessLess ? "<<" : ">>"),
14179                      OCE->getSourceRange());
14180   SuggestParentheses(
14181       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14182       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14183 }
14184 
14185 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14186 /// precedence.
14187 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14188                                     SourceLocation OpLoc, Expr *LHSExpr,
14189                                     Expr *RHSExpr){
14190   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14191   if (BinaryOperator::isBitwiseOp(Opc))
14192     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14193 
14194   // Diagnose "arg1 & arg2 | arg3"
14195   if ((Opc == BO_Or || Opc == BO_Xor) &&
14196       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14197     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14198     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14199   }
14200 
14201   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14202   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14203   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14204     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14205     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14206   }
14207 
14208   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14209       || Opc == BO_Shr) {
14210     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14211     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14212     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14213   }
14214 
14215   // Warn on overloaded shift operators and comparisons, such as:
14216   // cout << 5 == 4;
14217   if (BinaryOperator::isComparisonOp(Opc))
14218     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14219 }
14220 
14221 // Binary Operators.  'Tok' is the token for the operator.
14222 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14223                             tok::TokenKind Kind,
14224                             Expr *LHSExpr, Expr *RHSExpr) {
14225   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14226   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14227   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14228 
14229   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14230   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14231 
14232   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14233 }
14234 
14235 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14236                        UnresolvedSetImpl &Functions) {
14237   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14238   if (OverOp != OO_None && OverOp != OO_Equal)
14239     LookupOverloadedOperatorName(OverOp, S, Functions);
14240 
14241   // In C++20 onwards, we may have a second operator to look up.
14242   if (getLangOpts().CPlusPlus20) {
14243     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14244       LookupOverloadedOperatorName(ExtraOp, S, Functions);
14245   }
14246 }
14247 
14248 /// Build an overloaded binary operator expression in the given scope.
14249 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14250                                        BinaryOperatorKind Opc,
14251                                        Expr *LHS, Expr *RHS) {
14252   switch (Opc) {
14253   case BO_Assign:
14254   case BO_DivAssign:
14255   case BO_RemAssign:
14256   case BO_SubAssign:
14257   case BO_AndAssign:
14258   case BO_OrAssign:
14259   case BO_XorAssign:
14260     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14261     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14262     break;
14263   default:
14264     break;
14265   }
14266 
14267   // Find all of the overloaded operators visible from this point.
14268   UnresolvedSet<16> Functions;
14269   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14270 
14271   // Build the (potentially-overloaded, potentially-dependent)
14272   // binary operation.
14273   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14274 }
14275 
14276 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14277                             BinaryOperatorKind Opc,
14278                             Expr *LHSExpr, Expr *RHSExpr) {
14279   ExprResult LHS, RHS;
14280   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14281   if (!LHS.isUsable() || !RHS.isUsable())
14282     return ExprError();
14283   LHSExpr = LHS.get();
14284   RHSExpr = RHS.get();
14285 
14286   // We want to end up calling one of checkPseudoObjectAssignment
14287   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14288   // both expressions are overloadable or either is type-dependent),
14289   // or CreateBuiltinBinOp (in any other case).  We also want to get
14290   // any placeholder types out of the way.
14291 
14292   // Handle pseudo-objects in the LHS.
14293   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14294     // Assignments with a pseudo-object l-value need special analysis.
14295     if (pty->getKind() == BuiltinType::PseudoObject &&
14296         BinaryOperator::isAssignmentOp(Opc))
14297       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14298 
14299     // Don't resolve overloads if the other type is overloadable.
14300     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14301       // We can't actually test that if we still have a placeholder,
14302       // though.  Fortunately, none of the exceptions we see in that
14303       // code below are valid when the LHS is an overload set.  Note
14304       // that an overload set can be dependently-typed, but it never
14305       // instantiates to having an overloadable type.
14306       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14307       if (resolvedRHS.isInvalid()) return ExprError();
14308       RHSExpr = resolvedRHS.get();
14309 
14310       if (RHSExpr->isTypeDependent() ||
14311           RHSExpr->getType()->isOverloadableType())
14312         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14313     }
14314 
14315     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14316     // template, diagnose the missing 'template' keyword instead of diagnosing
14317     // an invalid use of a bound member function.
14318     //
14319     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14320     // to C++1z [over.over]/1.4, but we already checked for that case above.
14321     if (Opc == BO_LT && inTemplateInstantiation() &&
14322         (pty->getKind() == BuiltinType::BoundMember ||
14323          pty->getKind() == BuiltinType::Overload)) {
14324       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14325       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14326           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14327             return isa<FunctionTemplateDecl>(ND);
14328           })) {
14329         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14330                                 : OE->getNameLoc(),
14331              diag::err_template_kw_missing)
14332           << OE->getName().getAsString() << "";
14333         return ExprError();
14334       }
14335     }
14336 
14337     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14338     if (LHS.isInvalid()) return ExprError();
14339     LHSExpr = LHS.get();
14340   }
14341 
14342   // Handle pseudo-objects in the RHS.
14343   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14344     // An overload in the RHS can potentially be resolved by the type
14345     // being assigned to.
14346     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14347       if (getLangOpts().CPlusPlus &&
14348           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14349            LHSExpr->getType()->isOverloadableType()))
14350         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14351 
14352       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14353     }
14354 
14355     // Don't resolve overloads if the other type is overloadable.
14356     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14357         LHSExpr->getType()->isOverloadableType())
14358       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14359 
14360     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14361     if (!resolvedRHS.isUsable()) return ExprError();
14362     RHSExpr = resolvedRHS.get();
14363   }
14364 
14365   if (getLangOpts().CPlusPlus) {
14366     // If either expression is type-dependent, always build an
14367     // overloaded op.
14368     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14369       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14370 
14371     // Otherwise, build an overloaded op if either expression has an
14372     // overloadable type.
14373     if (LHSExpr->getType()->isOverloadableType() ||
14374         RHSExpr->getType()->isOverloadableType())
14375       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14376   }
14377 
14378   if (getLangOpts().RecoveryAST &&
14379       (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
14380     assert(!getLangOpts().CPlusPlus);
14381     assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
14382            "Should only occur in error-recovery path.");
14383     if (BinaryOperator::isCompoundAssignmentOp(Opc))
14384       // C [6.15.16] p3:
14385       // An assignment expression has the value of the left operand after the
14386       // assignment, but is not an lvalue.
14387       return CompoundAssignOperator::Create(
14388           Context, LHSExpr, RHSExpr, Opc,
14389           LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary,
14390           OpLoc, CurFPFeatureOverrides());
14391     QualType ResultType;
14392     switch (Opc) {
14393     case BO_Assign:
14394       ResultType = LHSExpr->getType().getUnqualifiedType();
14395       break;
14396     case BO_LT:
14397     case BO_GT:
14398     case BO_LE:
14399     case BO_GE:
14400     case BO_EQ:
14401     case BO_NE:
14402     case BO_LAnd:
14403     case BO_LOr:
14404       // These operators have a fixed result type regardless of operands.
14405       ResultType = Context.IntTy;
14406       break;
14407     case BO_Comma:
14408       ResultType = RHSExpr->getType();
14409       break;
14410     default:
14411       ResultType = Context.DependentTy;
14412       break;
14413     }
14414     return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
14415                                   VK_RValue, OK_Ordinary, OpLoc,
14416                                   CurFPFeatureOverrides());
14417   }
14418 
14419   // Build a built-in binary operation.
14420   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14421 }
14422 
14423 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14424   if (T.isNull() || T->isDependentType())
14425     return false;
14426 
14427   if (!T->isPromotableIntegerType())
14428     return true;
14429 
14430   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14431 }
14432 
14433 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14434                                       UnaryOperatorKind Opc,
14435                                       Expr *InputExpr) {
14436   ExprResult Input = InputExpr;
14437   ExprValueKind VK = VK_RValue;
14438   ExprObjectKind OK = OK_Ordinary;
14439   QualType resultType;
14440   bool CanOverflow = false;
14441 
14442   bool ConvertHalfVec = false;
14443   if (getLangOpts().OpenCL) {
14444     QualType Ty = InputExpr->getType();
14445     // The only legal unary operation for atomics is '&'.
14446     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14447     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14448     // only with a builtin functions and therefore should be disallowed here.
14449         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14450         || Ty->isBlockPointerType())) {
14451       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14452                        << InputExpr->getType()
14453                        << Input.get()->getSourceRange());
14454     }
14455   }
14456 
14457   switch (Opc) {
14458   case UO_PreInc:
14459   case UO_PreDec:
14460   case UO_PostInc:
14461   case UO_PostDec:
14462     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14463                                                 OpLoc,
14464                                                 Opc == UO_PreInc ||
14465                                                 Opc == UO_PostInc,
14466                                                 Opc == UO_PreInc ||
14467                                                 Opc == UO_PreDec);
14468     CanOverflow = isOverflowingIntegerType(Context, resultType);
14469     break;
14470   case UO_AddrOf:
14471     resultType = CheckAddressOfOperand(Input, OpLoc);
14472     CheckAddressOfNoDeref(InputExpr);
14473     RecordModifiableNonNullParam(*this, InputExpr);
14474     break;
14475   case UO_Deref: {
14476     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14477     if (Input.isInvalid()) return ExprError();
14478     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14479     break;
14480   }
14481   case UO_Plus:
14482   case UO_Minus:
14483     CanOverflow = Opc == UO_Minus &&
14484                   isOverflowingIntegerType(Context, Input.get()->getType());
14485     Input = UsualUnaryConversions(Input.get());
14486     if (Input.isInvalid()) return ExprError();
14487     // Unary plus and minus require promoting an operand of half vector to a
14488     // float vector and truncating the result back to a half vector. For now, we
14489     // do this only when HalfArgsAndReturns is set (that is, when the target is
14490     // arm or arm64).
14491     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14492 
14493     // If the operand is a half vector, promote it to a float vector.
14494     if (ConvertHalfVec)
14495       Input = convertVector(Input.get(), Context.FloatTy, *this);
14496     resultType = Input.get()->getType();
14497     if (resultType->isDependentType())
14498       break;
14499     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14500       break;
14501     else if (resultType->isVectorType() &&
14502              // The z vector extensions don't allow + or - with bool vectors.
14503              (!Context.getLangOpts().ZVector ||
14504               resultType->castAs<VectorType>()->getVectorKind() !=
14505               VectorType::AltiVecBool))
14506       break;
14507     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14508              Opc == UO_Plus &&
14509              resultType->isPointerType())
14510       break;
14511 
14512     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14513       << resultType << Input.get()->getSourceRange());
14514 
14515   case UO_Not: // bitwise complement
14516     Input = UsualUnaryConversions(Input.get());
14517     if (Input.isInvalid())
14518       return ExprError();
14519     resultType = Input.get()->getType();
14520     if (resultType->isDependentType())
14521       break;
14522     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14523     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14524       // C99 does not support '~' for complex conjugation.
14525       Diag(OpLoc, diag::ext_integer_complement_complex)
14526           << resultType << Input.get()->getSourceRange();
14527     else if (resultType->hasIntegerRepresentation())
14528       break;
14529     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14530       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14531       // on vector float types.
14532       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14533       if (!T->isIntegerType())
14534         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14535                           << resultType << Input.get()->getSourceRange());
14536     } else {
14537       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14538                        << resultType << Input.get()->getSourceRange());
14539     }
14540     break;
14541 
14542   case UO_LNot: // logical negation
14543     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14544     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14545     if (Input.isInvalid()) return ExprError();
14546     resultType = Input.get()->getType();
14547 
14548     // Though we still have to promote half FP to float...
14549     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14550       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14551       resultType = Context.FloatTy;
14552     }
14553 
14554     if (resultType->isDependentType())
14555       break;
14556     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14557       // C99 6.5.3.3p1: ok, fallthrough;
14558       if (Context.getLangOpts().CPlusPlus) {
14559         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14560         // operand contextually converted to bool.
14561         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14562                                   ScalarTypeToBooleanCastKind(resultType));
14563       } else if (Context.getLangOpts().OpenCL &&
14564                  Context.getLangOpts().OpenCLVersion < 120) {
14565         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14566         // operate on scalar float types.
14567         if (!resultType->isIntegerType() && !resultType->isPointerType())
14568           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14569                            << resultType << Input.get()->getSourceRange());
14570       }
14571     } else if (resultType->isExtVectorType()) {
14572       if (Context.getLangOpts().OpenCL &&
14573           Context.getLangOpts().OpenCLVersion < 120 &&
14574           !Context.getLangOpts().OpenCLCPlusPlus) {
14575         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14576         // operate on vector float types.
14577         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14578         if (!T->isIntegerType())
14579           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14580                            << resultType << Input.get()->getSourceRange());
14581       }
14582       // Vector logical not returns the signed variant of the operand type.
14583       resultType = GetSignedVectorType(resultType);
14584       break;
14585     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14586       const VectorType *VTy = resultType->castAs<VectorType>();
14587       if (VTy->getVectorKind() != VectorType::GenericVector)
14588         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14589                          << resultType << Input.get()->getSourceRange());
14590 
14591       // Vector logical not returns the signed variant of the operand type.
14592       resultType = GetSignedVectorType(resultType);
14593       break;
14594     } else {
14595       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14596         << resultType << Input.get()->getSourceRange());
14597     }
14598 
14599     // LNot always has type int. C99 6.5.3.3p5.
14600     // In C++, it's bool. C++ 5.3.1p8
14601     resultType = Context.getLogicalOperationType();
14602     break;
14603   case UO_Real:
14604   case UO_Imag:
14605     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14606     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14607     // complex l-values to ordinary l-values and all other values to r-values.
14608     if (Input.isInvalid()) return ExprError();
14609     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14610       if (Input.get()->getValueKind() != VK_RValue &&
14611           Input.get()->getObjectKind() == OK_Ordinary)
14612         VK = Input.get()->getValueKind();
14613     } else if (!getLangOpts().CPlusPlus) {
14614       // In C, a volatile scalar is read by __imag. In C++, it is not.
14615       Input = DefaultLvalueConversion(Input.get());
14616     }
14617     break;
14618   case UO_Extension:
14619     resultType = Input.get()->getType();
14620     VK = Input.get()->getValueKind();
14621     OK = Input.get()->getObjectKind();
14622     break;
14623   case UO_Coawait:
14624     // It's unnecessary to represent the pass-through operator co_await in the
14625     // AST; just return the input expression instead.
14626     assert(!Input.get()->getType()->isDependentType() &&
14627                    "the co_await expression must be non-dependant before "
14628                    "building operator co_await");
14629     return Input;
14630   }
14631   if (resultType.isNull() || Input.isInvalid())
14632     return ExprError();
14633 
14634   // Check for array bounds violations in the operand of the UnaryOperator,
14635   // except for the '*' and '&' operators that have to be handled specially
14636   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14637   // that are explicitly defined as valid by the standard).
14638   if (Opc != UO_AddrOf && Opc != UO_Deref)
14639     CheckArrayAccess(Input.get());
14640 
14641   auto *UO =
14642       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14643                             OpLoc, CanOverflow, CurFPFeatureOverrides());
14644 
14645   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14646       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14647     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14648 
14649   // Convert the result back to a half vector.
14650   if (ConvertHalfVec)
14651     return convertVector(UO, Context.HalfTy, *this);
14652   return UO;
14653 }
14654 
14655 /// Determine whether the given expression is a qualified member
14656 /// access expression, of a form that could be turned into a pointer to member
14657 /// with the address-of operator.
14658 bool Sema::isQualifiedMemberAccess(Expr *E) {
14659   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14660     if (!DRE->getQualifier())
14661       return false;
14662 
14663     ValueDecl *VD = DRE->getDecl();
14664     if (!VD->isCXXClassMember())
14665       return false;
14666 
14667     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14668       return true;
14669     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14670       return Method->isInstance();
14671 
14672     return false;
14673   }
14674 
14675   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14676     if (!ULE->getQualifier())
14677       return false;
14678 
14679     for (NamedDecl *D : ULE->decls()) {
14680       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14681         if (Method->isInstance())
14682           return true;
14683       } else {
14684         // Overload set does not contain methods.
14685         break;
14686       }
14687     }
14688 
14689     return false;
14690   }
14691 
14692   return false;
14693 }
14694 
14695 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14696                               UnaryOperatorKind Opc, Expr *Input) {
14697   // First things first: handle placeholders so that the
14698   // overloaded-operator check considers the right type.
14699   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14700     // Increment and decrement of pseudo-object references.
14701     if (pty->getKind() == BuiltinType::PseudoObject &&
14702         UnaryOperator::isIncrementDecrementOp(Opc))
14703       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14704 
14705     // extension is always a builtin operator.
14706     if (Opc == UO_Extension)
14707       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14708 
14709     // & gets special logic for several kinds of placeholder.
14710     // The builtin code knows what to do.
14711     if (Opc == UO_AddrOf &&
14712         (pty->getKind() == BuiltinType::Overload ||
14713          pty->getKind() == BuiltinType::UnknownAny ||
14714          pty->getKind() == BuiltinType::BoundMember))
14715       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14716 
14717     // Anything else needs to be handled now.
14718     ExprResult Result = CheckPlaceholderExpr(Input);
14719     if (Result.isInvalid()) return ExprError();
14720     Input = Result.get();
14721   }
14722 
14723   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14724       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14725       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14726     // Find all of the overloaded operators visible from this point.
14727     UnresolvedSet<16> Functions;
14728     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14729     if (S && OverOp != OO_None)
14730       LookupOverloadedOperatorName(OverOp, S, Functions);
14731 
14732     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14733   }
14734 
14735   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14736 }
14737 
14738 // Unary Operators.  'Tok' is the token for the operator.
14739 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14740                               tok::TokenKind Op, Expr *Input) {
14741   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14742 }
14743 
14744 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14745 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14746                                 LabelDecl *TheDecl) {
14747   TheDecl->markUsed(Context);
14748   // Create the AST node.  The address of a label always has type 'void*'.
14749   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14750                                      Context.getPointerType(Context.VoidTy));
14751 }
14752 
14753 void Sema::ActOnStartStmtExpr() {
14754   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14755 }
14756 
14757 void Sema::ActOnStmtExprError() {
14758   // Note that function is also called by TreeTransform when leaving a
14759   // StmtExpr scope without rebuilding anything.
14760 
14761   DiscardCleanupsInEvaluationContext();
14762   PopExpressionEvaluationContext();
14763 }
14764 
14765 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14766                                SourceLocation RPLoc) {
14767   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14768 }
14769 
14770 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14771                                SourceLocation RPLoc, unsigned TemplateDepth) {
14772   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14773   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14774 
14775   if (hasAnyUnrecoverableErrorsInThisFunction())
14776     DiscardCleanupsInEvaluationContext();
14777   assert(!Cleanup.exprNeedsCleanups() &&
14778          "cleanups within StmtExpr not correctly bound!");
14779   PopExpressionEvaluationContext();
14780 
14781   // FIXME: there are a variety of strange constraints to enforce here, for
14782   // example, it is not possible to goto into a stmt expression apparently.
14783   // More semantic analysis is needed.
14784 
14785   // If there are sub-stmts in the compound stmt, take the type of the last one
14786   // as the type of the stmtexpr.
14787   QualType Ty = Context.VoidTy;
14788   bool StmtExprMayBindToTemp = false;
14789   if (!Compound->body_empty()) {
14790     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14791     if (const auto *LastStmt =
14792             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14793       if (const Expr *Value = LastStmt->getExprStmt()) {
14794         StmtExprMayBindToTemp = true;
14795         Ty = Value->getType();
14796       }
14797     }
14798   }
14799 
14800   // FIXME: Check that expression type is complete/non-abstract; statement
14801   // expressions are not lvalues.
14802   Expr *ResStmtExpr =
14803       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14804   if (StmtExprMayBindToTemp)
14805     return MaybeBindToTemporary(ResStmtExpr);
14806   return ResStmtExpr;
14807 }
14808 
14809 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14810   if (ER.isInvalid())
14811     return ExprError();
14812 
14813   // Do function/array conversion on the last expression, but not
14814   // lvalue-to-rvalue.  However, initialize an unqualified type.
14815   ER = DefaultFunctionArrayConversion(ER.get());
14816   if (ER.isInvalid())
14817     return ExprError();
14818   Expr *E = ER.get();
14819 
14820   if (E->isTypeDependent())
14821     return E;
14822 
14823   // In ARC, if the final expression ends in a consume, splice
14824   // the consume out and bind it later.  In the alternate case
14825   // (when dealing with a retainable type), the result
14826   // initialization will create a produce.  In both cases the
14827   // result will be +1, and we'll need to balance that out with
14828   // a bind.
14829   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14830   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14831     return Cast->getSubExpr();
14832 
14833   // FIXME: Provide a better location for the initialization.
14834   return PerformCopyInitialization(
14835       InitializedEntity::InitializeStmtExprResult(
14836           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14837       SourceLocation(), E);
14838 }
14839 
14840 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14841                                       TypeSourceInfo *TInfo,
14842                                       ArrayRef<OffsetOfComponent> Components,
14843                                       SourceLocation RParenLoc) {
14844   QualType ArgTy = TInfo->getType();
14845   bool Dependent = ArgTy->isDependentType();
14846   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14847 
14848   // We must have at least one component that refers to the type, and the first
14849   // one is known to be a field designator.  Verify that the ArgTy represents
14850   // a struct/union/class.
14851   if (!Dependent && !ArgTy->isRecordType())
14852     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14853                        << ArgTy << TypeRange);
14854 
14855   // Type must be complete per C99 7.17p3 because a declaring a variable
14856   // with an incomplete type would be ill-formed.
14857   if (!Dependent
14858       && RequireCompleteType(BuiltinLoc, ArgTy,
14859                              diag::err_offsetof_incomplete_type, TypeRange))
14860     return ExprError();
14861 
14862   bool DidWarnAboutNonPOD = false;
14863   QualType CurrentType = ArgTy;
14864   SmallVector<OffsetOfNode, 4> Comps;
14865   SmallVector<Expr*, 4> Exprs;
14866   for (const OffsetOfComponent &OC : Components) {
14867     if (OC.isBrackets) {
14868       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14869       if (!CurrentType->isDependentType()) {
14870         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14871         if(!AT)
14872           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14873                            << CurrentType);
14874         CurrentType = AT->getElementType();
14875       } else
14876         CurrentType = Context.DependentTy;
14877 
14878       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14879       if (IdxRval.isInvalid())
14880         return ExprError();
14881       Expr *Idx = IdxRval.get();
14882 
14883       // The expression must be an integral expression.
14884       // FIXME: An integral constant expression?
14885       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14886           !Idx->getType()->isIntegerType())
14887         return ExprError(
14888             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14889             << Idx->getSourceRange());
14890 
14891       // Record this array index.
14892       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14893       Exprs.push_back(Idx);
14894       continue;
14895     }
14896 
14897     // Offset of a field.
14898     if (CurrentType->isDependentType()) {
14899       // We have the offset of a field, but we can't look into the dependent
14900       // type. Just record the identifier of the field.
14901       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14902       CurrentType = Context.DependentTy;
14903       continue;
14904     }
14905 
14906     // We need to have a complete type to look into.
14907     if (RequireCompleteType(OC.LocStart, CurrentType,
14908                             diag::err_offsetof_incomplete_type))
14909       return ExprError();
14910 
14911     // Look for the designated field.
14912     const RecordType *RC = CurrentType->getAs<RecordType>();
14913     if (!RC)
14914       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14915                        << CurrentType);
14916     RecordDecl *RD = RC->getDecl();
14917 
14918     // C++ [lib.support.types]p5:
14919     //   The macro offsetof accepts a restricted set of type arguments in this
14920     //   International Standard. type shall be a POD structure or a POD union
14921     //   (clause 9).
14922     // C++11 [support.types]p4:
14923     //   If type is not a standard-layout class (Clause 9), the results are
14924     //   undefined.
14925     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14926       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14927       unsigned DiagID =
14928         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14929                             : diag::ext_offsetof_non_pod_type;
14930 
14931       if (!IsSafe && !DidWarnAboutNonPOD &&
14932           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14933                               PDiag(DiagID)
14934                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14935                               << CurrentType))
14936         DidWarnAboutNonPOD = true;
14937     }
14938 
14939     // Look for the field.
14940     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14941     LookupQualifiedName(R, RD);
14942     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14943     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14944     if (!MemberDecl) {
14945       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14946         MemberDecl = IndirectMemberDecl->getAnonField();
14947     }
14948 
14949     if (!MemberDecl)
14950       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14951                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14952                                                               OC.LocEnd));
14953 
14954     // C99 7.17p3:
14955     //   (If the specified member is a bit-field, the behavior is undefined.)
14956     //
14957     // We diagnose this as an error.
14958     if (MemberDecl->isBitField()) {
14959       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14960         << MemberDecl->getDeclName()
14961         << SourceRange(BuiltinLoc, RParenLoc);
14962       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14963       return ExprError();
14964     }
14965 
14966     RecordDecl *Parent = MemberDecl->getParent();
14967     if (IndirectMemberDecl)
14968       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14969 
14970     // If the member was found in a base class, introduce OffsetOfNodes for
14971     // the base class indirections.
14972     CXXBasePaths Paths;
14973     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14974                       Paths)) {
14975       if (Paths.getDetectedVirtual()) {
14976         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14977           << MemberDecl->getDeclName()
14978           << SourceRange(BuiltinLoc, RParenLoc);
14979         return ExprError();
14980       }
14981 
14982       CXXBasePath &Path = Paths.front();
14983       for (const CXXBasePathElement &B : Path)
14984         Comps.push_back(OffsetOfNode(B.Base));
14985     }
14986 
14987     if (IndirectMemberDecl) {
14988       for (auto *FI : IndirectMemberDecl->chain()) {
14989         assert(isa<FieldDecl>(FI));
14990         Comps.push_back(OffsetOfNode(OC.LocStart,
14991                                      cast<FieldDecl>(FI), OC.LocEnd));
14992       }
14993     } else
14994       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14995 
14996     CurrentType = MemberDecl->getType().getNonReferenceType();
14997   }
14998 
14999   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15000                               Comps, Exprs, RParenLoc);
15001 }
15002 
15003 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15004                                       SourceLocation BuiltinLoc,
15005                                       SourceLocation TypeLoc,
15006                                       ParsedType ParsedArgTy,
15007                                       ArrayRef<OffsetOfComponent> Components,
15008                                       SourceLocation RParenLoc) {
15009 
15010   TypeSourceInfo *ArgTInfo;
15011   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15012   if (ArgTy.isNull())
15013     return ExprError();
15014 
15015   if (!ArgTInfo)
15016     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15017 
15018   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15019 }
15020 
15021 
15022 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15023                                  Expr *CondExpr,
15024                                  Expr *LHSExpr, Expr *RHSExpr,
15025                                  SourceLocation RPLoc) {
15026   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15027 
15028   ExprValueKind VK = VK_RValue;
15029   ExprObjectKind OK = OK_Ordinary;
15030   QualType resType;
15031   bool CondIsTrue = false;
15032   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15033     resType = Context.DependentTy;
15034   } else {
15035     // The conditional expression is required to be a constant expression.
15036     llvm::APSInt condEval(32);
15037     ExprResult CondICE = VerifyIntegerConstantExpression(
15038         CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15039     if (CondICE.isInvalid())
15040       return ExprError();
15041     CondExpr = CondICE.get();
15042     CondIsTrue = condEval.getZExtValue();
15043 
15044     // If the condition is > zero, then the AST type is the same as the LHSExpr.
15045     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15046 
15047     resType = ActiveExpr->getType();
15048     VK = ActiveExpr->getValueKind();
15049     OK = ActiveExpr->getObjectKind();
15050   }
15051 
15052   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15053                                   resType, VK, OK, RPLoc, CondIsTrue);
15054 }
15055 
15056 //===----------------------------------------------------------------------===//
15057 // Clang Extensions.
15058 //===----------------------------------------------------------------------===//
15059 
15060 /// ActOnBlockStart - This callback is invoked when a block literal is started.
15061 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15062   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15063 
15064   if (LangOpts.CPlusPlus) {
15065     MangleNumberingContext *MCtx;
15066     Decl *ManglingContextDecl;
15067     std::tie(MCtx, ManglingContextDecl) =
15068         getCurrentMangleNumberContext(Block->getDeclContext());
15069     if (MCtx) {
15070       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15071       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15072     }
15073   }
15074 
15075   PushBlockScope(CurScope, Block);
15076   CurContext->addDecl(Block);
15077   if (CurScope)
15078     PushDeclContext(CurScope, Block);
15079   else
15080     CurContext = Block;
15081 
15082   getCurBlock()->HasImplicitReturnType = true;
15083 
15084   // Enter a new evaluation context to insulate the block from any
15085   // cleanups from the enclosing full-expression.
15086   PushExpressionEvaluationContext(
15087       ExpressionEvaluationContext::PotentiallyEvaluated);
15088 }
15089 
15090 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15091                                Scope *CurScope) {
15092   assert(ParamInfo.getIdentifier() == nullptr &&
15093          "block-id should have no identifier!");
15094   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15095   BlockScopeInfo *CurBlock = getCurBlock();
15096 
15097   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15098   QualType T = Sig->getType();
15099 
15100   // FIXME: We should allow unexpanded parameter packs here, but that would,
15101   // in turn, make the block expression contain unexpanded parameter packs.
15102   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15103     // Drop the parameters.
15104     FunctionProtoType::ExtProtoInfo EPI;
15105     EPI.HasTrailingReturn = false;
15106     EPI.TypeQuals.addConst();
15107     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15108     Sig = Context.getTrivialTypeSourceInfo(T);
15109   }
15110 
15111   // GetTypeForDeclarator always produces a function type for a block
15112   // literal signature.  Furthermore, it is always a FunctionProtoType
15113   // unless the function was written with a typedef.
15114   assert(T->isFunctionType() &&
15115          "GetTypeForDeclarator made a non-function block signature");
15116 
15117   // Look for an explicit signature in that function type.
15118   FunctionProtoTypeLoc ExplicitSignature;
15119 
15120   if ((ExplicitSignature = Sig->getTypeLoc()
15121                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15122 
15123     // Check whether that explicit signature was synthesized by
15124     // GetTypeForDeclarator.  If so, don't save that as part of the
15125     // written signature.
15126     if (ExplicitSignature.getLocalRangeBegin() ==
15127         ExplicitSignature.getLocalRangeEnd()) {
15128       // This would be much cheaper if we stored TypeLocs instead of
15129       // TypeSourceInfos.
15130       TypeLoc Result = ExplicitSignature.getReturnLoc();
15131       unsigned Size = Result.getFullDataSize();
15132       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15133       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15134 
15135       ExplicitSignature = FunctionProtoTypeLoc();
15136     }
15137   }
15138 
15139   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15140   CurBlock->FunctionType = T;
15141 
15142   const FunctionType *Fn = T->getAs<FunctionType>();
15143   QualType RetTy = Fn->getReturnType();
15144   bool isVariadic =
15145     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15146 
15147   CurBlock->TheDecl->setIsVariadic(isVariadic);
15148 
15149   // Context.DependentTy is used as a placeholder for a missing block
15150   // return type.  TODO:  what should we do with declarators like:
15151   //   ^ * { ... }
15152   // If the answer is "apply template argument deduction"....
15153   if (RetTy != Context.DependentTy) {
15154     CurBlock->ReturnType = RetTy;
15155     CurBlock->TheDecl->setBlockMissingReturnType(false);
15156     CurBlock->HasImplicitReturnType = false;
15157   }
15158 
15159   // Push block parameters from the declarator if we had them.
15160   SmallVector<ParmVarDecl*, 8> Params;
15161   if (ExplicitSignature) {
15162     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15163       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15164       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15165           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15166         // Diagnose this as an extension in C17 and earlier.
15167         if (!getLangOpts().C2x)
15168           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15169       }
15170       Params.push_back(Param);
15171     }
15172 
15173   // Fake up parameter variables if we have a typedef, like
15174   //   ^ fntype { ... }
15175   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15176     for (const auto &I : Fn->param_types()) {
15177       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15178           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15179       Params.push_back(Param);
15180     }
15181   }
15182 
15183   // Set the parameters on the block decl.
15184   if (!Params.empty()) {
15185     CurBlock->TheDecl->setParams(Params);
15186     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15187                              /*CheckParameterNames=*/false);
15188   }
15189 
15190   // Finally we can process decl attributes.
15191   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15192 
15193   // Put the parameter variables in scope.
15194   for (auto AI : CurBlock->TheDecl->parameters()) {
15195     AI->setOwningFunction(CurBlock->TheDecl);
15196 
15197     // If this has an identifier, add it to the scope stack.
15198     if (AI->getIdentifier()) {
15199       CheckShadow(CurBlock->TheScope, AI);
15200 
15201       PushOnScopeChains(AI, CurBlock->TheScope);
15202     }
15203   }
15204 }
15205 
15206 /// ActOnBlockError - If there is an error parsing a block, this callback
15207 /// is invoked to pop the information about the block from the action impl.
15208 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15209   // Leave the expression-evaluation context.
15210   DiscardCleanupsInEvaluationContext();
15211   PopExpressionEvaluationContext();
15212 
15213   // Pop off CurBlock, handle nested blocks.
15214   PopDeclContext();
15215   PopFunctionScopeInfo();
15216 }
15217 
15218 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15219 /// literal was successfully completed.  ^(int x){...}
15220 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15221                                     Stmt *Body, Scope *CurScope) {
15222   // If blocks are disabled, emit an error.
15223   if (!LangOpts.Blocks)
15224     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15225 
15226   // Leave the expression-evaluation context.
15227   if (hasAnyUnrecoverableErrorsInThisFunction())
15228     DiscardCleanupsInEvaluationContext();
15229   assert(!Cleanup.exprNeedsCleanups() &&
15230          "cleanups within block not correctly bound!");
15231   PopExpressionEvaluationContext();
15232 
15233   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15234   BlockDecl *BD = BSI->TheDecl;
15235 
15236   if (BSI->HasImplicitReturnType)
15237     deduceClosureReturnType(*BSI);
15238 
15239   QualType RetTy = Context.VoidTy;
15240   if (!BSI->ReturnType.isNull())
15241     RetTy = BSI->ReturnType;
15242 
15243   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15244   QualType BlockTy;
15245 
15246   // If the user wrote a function type in some form, try to use that.
15247   if (!BSI->FunctionType.isNull()) {
15248     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15249 
15250     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15251     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15252 
15253     // Turn protoless block types into nullary block types.
15254     if (isa<FunctionNoProtoType>(FTy)) {
15255       FunctionProtoType::ExtProtoInfo EPI;
15256       EPI.ExtInfo = Ext;
15257       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15258 
15259     // Otherwise, if we don't need to change anything about the function type,
15260     // preserve its sugar structure.
15261     } else if (FTy->getReturnType() == RetTy &&
15262                (!NoReturn || FTy->getNoReturnAttr())) {
15263       BlockTy = BSI->FunctionType;
15264 
15265     // Otherwise, make the minimal modifications to the function type.
15266     } else {
15267       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15268       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15269       EPI.TypeQuals = Qualifiers();
15270       EPI.ExtInfo = Ext;
15271       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15272     }
15273 
15274   // If we don't have a function type, just build one from nothing.
15275   } else {
15276     FunctionProtoType::ExtProtoInfo EPI;
15277     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15278     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15279   }
15280 
15281   DiagnoseUnusedParameters(BD->parameters());
15282   BlockTy = Context.getBlockPointerType(BlockTy);
15283 
15284   // If needed, diagnose invalid gotos and switches in the block.
15285   if (getCurFunction()->NeedsScopeChecking() &&
15286       !PP.isCodeCompletionEnabled())
15287     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15288 
15289   BD->setBody(cast<CompoundStmt>(Body));
15290 
15291   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15292     DiagnoseUnguardedAvailabilityViolations(BD);
15293 
15294   // Try to apply the named return value optimization. We have to check again
15295   // if we can do this, though, because blocks keep return statements around
15296   // to deduce an implicit return type.
15297   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15298       !BD->isDependentContext())
15299     computeNRVO(Body, BSI);
15300 
15301   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15302       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15303     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15304                           NTCUK_Destruct|NTCUK_Copy);
15305 
15306   PopDeclContext();
15307 
15308   // Pop the block scope now but keep it alive to the end of this function.
15309   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15310   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15311 
15312   // Set the captured variables on the block.
15313   SmallVector<BlockDecl::Capture, 4> Captures;
15314   for (Capture &Cap : BSI->Captures) {
15315     if (Cap.isInvalid() || Cap.isThisCapture())
15316       continue;
15317 
15318     VarDecl *Var = Cap.getVariable();
15319     Expr *CopyExpr = nullptr;
15320     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15321       if (const RecordType *Record =
15322               Cap.getCaptureType()->getAs<RecordType>()) {
15323         // The capture logic needs the destructor, so make sure we mark it.
15324         // Usually this is unnecessary because most local variables have
15325         // their destructors marked at declaration time, but parameters are
15326         // an exception because it's technically only the call site that
15327         // actually requires the destructor.
15328         if (isa<ParmVarDecl>(Var))
15329           FinalizeVarWithDestructor(Var, Record);
15330 
15331         // Enter a separate potentially-evaluated context while building block
15332         // initializers to isolate their cleanups from those of the block
15333         // itself.
15334         // FIXME: Is this appropriate even when the block itself occurs in an
15335         // unevaluated operand?
15336         EnterExpressionEvaluationContext EvalContext(
15337             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15338 
15339         SourceLocation Loc = Cap.getLocation();
15340 
15341         ExprResult Result = BuildDeclarationNameExpr(
15342             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15343 
15344         // According to the blocks spec, the capture of a variable from
15345         // the stack requires a const copy constructor.  This is not true
15346         // of the copy/move done to move a __block variable to the heap.
15347         if (!Result.isInvalid() &&
15348             !Result.get()->getType().isConstQualified()) {
15349           Result = ImpCastExprToType(Result.get(),
15350                                      Result.get()->getType().withConst(),
15351                                      CK_NoOp, VK_LValue);
15352         }
15353 
15354         if (!Result.isInvalid()) {
15355           Result = PerformCopyInitialization(
15356               InitializedEntity::InitializeBlock(Var->getLocation(),
15357                                                  Cap.getCaptureType(), false),
15358               Loc, Result.get());
15359         }
15360 
15361         // Build a full-expression copy expression if initialization
15362         // succeeded and used a non-trivial constructor.  Recover from
15363         // errors by pretending that the copy isn't necessary.
15364         if (!Result.isInvalid() &&
15365             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15366                 ->isTrivial()) {
15367           Result = MaybeCreateExprWithCleanups(Result);
15368           CopyExpr = Result.get();
15369         }
15370       }
15371     }
15372 
15373     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15374                               CopyExpr);
15375     Captures.push_back(NewCap);
15376   }
15377   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15378 
15379   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15380 
15381   // If the block isn't obviously global, i.e. it captures anything at
15382   // all, then we need to do a few things in the surrounding context:
15383   if (Result->getBlockDecl()->hasCaptures()) {
15384     // First, this expression has a new cleanup object.
15385     ExprCleanupObjects.push_back(Result->getBlockDecl());
15386     Cleanup.setExprNeedsCleanups(true);
15387 
15388     // It also gets a branch-protected scope if any of the captured
15389     // variables needs destruction.
15390     for (const auto &CI : Result->getBlockDecl()->captures()) {
15391       const VarDecl *var = CI.getVariable();
15392       if (var->getType().isDestructedType() != QualType::DK_none) {
15393         setFunctionHasBranchProtectedScope();
15394         break;
15395       }
15396     }
15397   }
15398 
15399   if (getCurFunction())
15400     getCurFunction()->addBlock(BD);
15401 
15402   return Result;
15403 }
15404 
15405 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15406                             SourceLocation RPLoc) {
15407   TypeSourceInfo *TInfo;
15408   GetTypeFromParser(Ty, &TInfo);
15409   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15410 }
15411 
15412 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15413                                 Expr *E, TypeSourceInfo *TInfo,
15414                                 SourceLocation RPLoc) {
15415   Expr *OrigExpr = E;
15416   bool IsMS = false;
15417 
15418   // CUDA device code does not support varargs.
15419   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15420     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15421       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15422       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15423         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15424     }
15425   }
15426 
15427   // NVPTX does not support va_arg expression.
15428   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15429       Context.getTargetInfo().getTriple().isNVPTX())
15430     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15431 
15432   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15433   // as Microsoft ABI on an actual Microsoft platform, where
15434   // __builtin_ms_va_list and __builtin_va_list are the same.)
15435   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15436       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15437     QualType MSVaListType = Context.getBuiltinMSVaListType();
15438     if (Context.hasSameType(MSVaListType, E->getType())) {
15439       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15440         return ExprError();
15441       IsMS = true;
15442     }
15443   }
15444 
15445   // Get the va_list type
15446   QualType VaListType = Context.getBuiltinVaListType();
15447   if (!IsMS) {
15448     if (VaListType->isArrayType()) {
15449       // Deal with implicit array decay; for example, on x86-64,
15450       // va_list is an array, but it's supposed to decay to
15451       // a pointer for va_arg.
15452       VaListType = Context.getArrayDecayedType(VaListType);
15453       // Make sure the input expression also decays appropriately.
15454       ExprResult Result = UsualUnaryConversions(E);
15455       if (Result.isInvalid())
15456         return ExprError();
15457       E = Result.get();
15458     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15459       // If va_list is a record type and we are compiling in C++ mode,
15460       // check the argument using reference binding.
15461       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15462           Context, Context.getLValueReferenceType(VaListType), false);
15463       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15464       if (Init.isInvalid())
15465         return ExprError();
15466       E = Init.getAs<Expr>();
15467     } else {
15468       // Otherwise, the va_list argument must be an l-value because
15469       // it is modified by va_arg.
15470       if (!E->isTypeDependent() &&
15471           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15472         return ExprError();
15473     }
15474   }
15475 
15476   if (!IsMS && !E->isTypeDependent() &&
15477       !Context.hasSameType(VaListType, E->getType()))
15478     return ExprError(
15479         Diag(E->getBeginLoc(),
15480              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15481         << OrigExpr->getType() << E->getSourceRange());
15482 
15483   if (!TInfo->getType()->isDependentType()) {
15484     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15485                             diag::err_second_parameter_to_va_arg_incomplete,
15486                             TInfo->getTypeLoc()))
15487       return ExprError();
15488 
15489     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15490                                TInfo->getType(),
15491                                diag::err_second_parameter_to_va_arg_abstract,
15492                                TInfo->getTypeLoc()))
15493       return ExprError();
15494 
15495     if (!TInfo->getType().isPODType(Context)) {
15496       Diag(TInfo->getTypeLoc().getBeginLoc(),
15497            TInfo->getType()->isObjCLifetimeType()
15498              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15499              : diag::warn_second_parameter_to_va_arg_not_pod)
15500         << TInfo->getType()
15501         << TInfo->getTypeLoc().getSourceRange();
15502     }
15503 
15504     // Check for va_arg where arguments of the given type will be promoted
15505     // (i.e. this va_arg is guaranteed to have undefined behavior).
15506     QualType PromoteType;
15507     if (TInfo->getType()->isPromotableIntegerType()) {
15508       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15509       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15510         PromoteType = QualType();
15511     }
15512     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15513       PromoteType = Context.DoubleTy;
15514     if (!PromoteType.isNull())
15515       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15516                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15517                           << TInfo->getType()
15518                           << PromoteType
15519                           << TInfo->getTypeLoc().getSourceRange());
15520   }
15521 
15522   QualType T = TInfo->getType().getNonLValueExprType(Context);
15523   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15524 }
15525 
15526 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15527   // The type of __null will be int or long, depending on the size of
15528   // pointers on the target.
15529   QualType Ty;
15530   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15531   if (pw == Context.getTargetInfo().getIntWidth())
15532     Ty = Context.IntTy;
15533   else if (pw == Context.getTargetInfo().getLongWidth())
15534     Ty = Context.LongTy;
15535   else if (pw == Context.getTargetInfo().getLongLongWidth())
15536     Ty = Context.LongLongTy;
15537   else {
15538     llvm_unreachable("I don't know size of pointer!");
15539   }
15540 
15541   return new (Context) GNUNullExpr(Ty, TokenLoc);
15542 }
15543 
15544 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15545                                     SourceLocation BuiltinLoc,
15546                                     SourceLocation RPLoc) {
15547   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15548 }
15549 
15550 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15551                                     SourceLocation BuiltinLoc,
15552                                     SourceLocation RPLoc,
15553                                     DeclContext *ParentContext) {
15554   return new (Context)
15555       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15556 }
15557 
15558 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15559                                         bool Diagnose) {
15560   if (!getLangOpts().ObjC)
15561     return false;
15562 
15563   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15564   if (!PT)
15565     return false;
15566   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15567 
15568   // Ignore any parens, implicit casts (should only be
15569   // array-to-pointer decays), and not-so-opaque values.  The last is
15570   // important for making this trigger for property assignments.
15571   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15572   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15573     if (OV->getSourceExpr())
15574       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15575 
15576   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15577     if (!PT->isObjCIdType() &&
15578         !(ID && ID->getIdentifier()->isStr("NSString")))
15579       return false;
15580     if (!SL->isAscii())
15581       return false;
15582 
15583     if (Diagnose) {
15584       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15585           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15586       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15587     }
15588     return true;
15589   }
15590 
15591   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15592       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15593       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15594       !SrcExpr->isNullPointerConstant(
15595           getASTContext(), Expr::NPC_NeverValueDependent)) {
15596     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15597       return false;
15598     if (Diagnose) {
15599       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15600           << /*number*/1
15601           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15602       Expr *NumLit =
15603           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15604       if (NumLit)
15605         Exp = NumLit;
15606     }
15607     return true;
15608   }
15609 
15610   return false;
15611 }
15612 
15613 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15614                                               const Expr *SrcExpr) {
15615   if (!DstType->isFunctionPointerType() ||
15616       !SrcExpr->getType()->isFunctionType())
15617     return false;
15618 
15619   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15620   if (!DRE)
15621     return false;
15622 
15623   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15624   if (!FD)
15625     return false;
15626 
15627   return !S.checkAddressOfFunctionIsAvailable(FD,
15628                                               /*Complain=*/true,
15629                                               SrcExpr->getBeginLoc());
15630 }
15631 
15632 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15633                                     SourceLocation Loc,
15634                                     QualType DstType, QualType SrcType,
15635                                     Expr *SrcExpr, AssignmentAction Action,
15636                                     bool *Complained) {
15637   if (Complained)
15638     *Complained = false;
15639 
15640   // Decode the result (notice that AST's are still created for extensions).
15641   bool CheckInferredResultType = false;
15642   bool isInvalid = false;
15643   unsigned DiagKind = 0;
15644   ConversionFixItGenerator ConvHints;
15645   bool MayHaveConvFixit = false;
15646   bool MayHaveFunctionDiff = false;
15647   const ObjCInterfaceDecl *IFace = nullptr;
15648   const ObjCProtocolDecl *PDecl = nullptr;
15649 
15650   switch (ConvTy) {
15651   case Compatible:
15652       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15653       return false;
15654 
15655   case PointerToInt:
15656     if (getLangOpts().CPlusPlus) {
15657       DiagKind = diag::err_typecheck_convert_pointer_int;
15658       isInvalid = true;
15659     } else {
15660       DiagKind = diag::ext_typecheck_convert_pointer_int;
15661     }
15662     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15663     MayHaveConvFixit = true;
15664     break;
15665   case IntToPointer:
15666     if (getLangOpts().CPlusPlus) {
15667       DiagKind = diag::err_typecheck_convert_int_pointer;
15668       isInvalid = true;
15669     } else {
15670       DiagKind = diag::ext_typecheck_convert_int_pointer;
15671     }
15672     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15673     MayHaveConvFixit = true;
15674     break;
15675   case IncompatibleFunctionPointer:
15676     if (getLangOpts().CPlusPlus) {
15677       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15678       isInvalid = true;
15679     } else {
15680       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15681     }
15682     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15683     MayHaveConvFixit = true;
15684     break;
15685   case IncompatiblePointer:
15686     if (Action == AA_Passing_CFAudited) {
15687       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15688     } else if (getLangOpts().CPlusPlus) {
15689       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15690       isInvalid = true;
15691     } else {
15692       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15693     }
15694     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15695       SrcType->isObjCObjectPointerType();
15696     if (!CheckInferredResultType) {
15697       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15698     } else if (CheckInferredResultType) {
15699       SrcType = SrcType.getUnqualifiedType();
15700       DstType = DstType.getUnqualifiedType();
15701     }
15702     MayHaveConvFixit = true;
15703     break;
15704   case IncompatiblePointerSign:
15705     if (getLangOpts().CPlusPlus) {
15706       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15707       isInvalid = true;
15708     } else {
15709       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15710     }
15711     break;
15712   case FunctionVoidPointer:
15713     if (getLangOpts().CPlusPlus) {
15714       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15715       isInvalid = true;
15716     } else {
15717       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15718     }
15719     break;
15720   case IncompatiblePointerDiscardsQualifiers: {
15721     // Perform array-to-pointer decay if necessary.
15722     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15723 
15724     isInvalid = true;
15725 
15726     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15727     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15728     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15729       DiagKind = diag::err_typecheck_incompatible_address_space;
15730       break;
15731 
15732     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15733       DiagKind = diag::err_typecheck_incompatible_ownership;
15734       break;
15735     }
15736 
15737     llvm_unreachable("unknown error case for discarding qualifiers!");
15738     // fallthrough
15739   }
15740   case CompatiblePointerDiscardsQualifiers:
15741     // If the qualifiers lost were because we were applying the
15742     // (deprecated) C++ conversion from a string literal to a char*
15743     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15744     // Ideally, this check would be performed in
15745     // checkPointerTypesForAssignment. However, that would require a
15746     // bit of refactoring (so that the second argument is an
15747     // expression, rather than a type), which should be done as part
15748     // of a larger effort to fix checkPointerTypesForAssignment for
15749     // C++ semantics.
15750     if (getLangOpts().CPlusPlus &&
15751         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15752       return false;
15753     if (getLangOpts().CPlusPlus) {
15754       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15755       isInvalid = true;
15756     } else {
15757       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15758     }
15759 
15760     break;
15761   case IncompatibleNestedPointerQualifiers:
15762     if (getLangOpts().CPlusPlus) {
15763       isInvalid = true;
15764       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15765     } else {
15766       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15767     }
15768     break;
15769   case IncompatibleNestedPointerAddressSpaceMismatch:
15770     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15771     isInvalid = true;
15772     break;
15773   case IntToBlockPointer:
15774     DiagKind = diag::err_int_to_block_pointer;
15775     isInvalid = true;
15776     break;
15777   case IncompatibleBlockPointer:
15778     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15779     isInvalid = true;
15780     break;
15781   case IncompatibleObjCQualifiedId: {
15782     if (SrcType->isObjCQualifiedIdType()) {
15783       const ObjCObjectPointerType *srcOPT =
15784                 SrcType->castAs<ObjCObjectPointerType>();
15785       for (auto *srcProto : srcOPT->quals()) {
15786         PDecl = srcProto;
15787         break;
15788       }
15789       if (const ObjCInterfaceType *IFaceT =
15790             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15791         IFace = IFaceT->getDecl();
15792     }
15793     else if (DstType->isObjCQualifiedIdType()) {
15794       const ObjCObjectPointerType *dstOPT =
15795         DstType->castAs<ObjCObjectPointerType>();
15796       for (auto *dstProto : dstOPT->quals()) {
15797         PDecl = dstProto;
15798         break;
15799       }
15800       if (const ObjCInterfaceType *IFaceT =
15801             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15802         IFace = IFaceT->getDecl();
15803     }
15804     if (getLangOpts().CPlusPlus) {
15805       DiagKind = diag::err_incompatible_qualified_id;
15806       isInvalid = true;
15807     } else {
15808       DiagKind = diag::warn_incompatible_qualified_id;
15809     }
15810     break;
15811   }
15812   case IncompatibleVectors:
15813     if (getLangOpts().CPlusPlus) {
15814       DiagKind = diag::err_incompatible_vectors;
15815       isInvalid = true;
15816     } else {
15817       DiagKind = diag::warn_incompatible_vectors;
15818     }
15819     break;
15820   case IncompatibleObjCWeakRef:
15821     DiagKind = diag::err_arc_weak_unavailable_assign;
15822     isInvalid = true;
15823     break;
15824   case Incompatible:
15825     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15826       if (Complained)
15827         *Complained = true;
15828       return true;
15829     }
15830 
15831     DiagKind = diag::err_typecheck_convert_incompatible;
15832     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15833     MayHaveConvFixit = true;
15834     isInvalid = true;
15835     MayHaveFunctionDiff = true;
15836     break;
15837   }
15838 
15839   QualType FirstType, SecondType;
15840   switch (Action) {
15841   case AA_Assigning:
15842   case AA_Initializing:
15843     // The destination type comes first.
15844     FirstType = DstType;
15845     SecondType = SrcType;
15846     break;
15847 
15848   case AA_Returning:
15849   case AA_Passing:
15850   case AA_Passing_CFAudited:
15851   case AA_Converting:
15852   case AA_Sending:
15853   case AA_Casting:
15854     // The source type comes first.
15855     FirstType = SrcType;
15856     SecondType = DstType;
15857     break;
15858   }
15859 
15860   PartialDiagnostic FDiag = PDiag(DiagKind);
15861   if (Action == AA_Passing_CFAudited)
15862     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15863   else
15864     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15865 
15866   // If we can fix the conversion, suggest the FixIts.
15867   if (!ConvHints.isNull()) {
15868     for (FixItHint &H : ConvHints.Hints)
15869       FDiag << H;
15870   }
15871 
15872   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15873 
15874   if (MayHaveFunctionDiff)
15875     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15876 
15877   Diag(Loc, FDiag);
15878   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15879        DiagKind == diag::err_incompatible_qualified_id) &&
15880       PDecl && IFace && !IFace->hasDefinition())
15881     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15882         << IFace << PDecl;
15883 
15884   if (SecondType == Context.OverloadTy)
15885     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15886                               FirstType, /*TakingAddress=*/true);
15887 
15888   if (CheckInferredResultType)
15889     EmitRelatedResultTypeNote(SrcExpr);
15890 
15891   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15892     EmitRelatedResultTypeNoteForReturn(DstType);
15893 
15894   if (Complained)
15895     *Complained = true;
15896   return isInvalid;
15897 }
15898 
15899 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15900                                                  llvm::APSInt *Result,
15901                                                  AllowFoldKind CanFold) {
15902   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15903   public:
15904     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
15905                                              QualType T) override {
15906       return S.Diag(Loc, diag::err_ice_not_integral)
15907              << T << S.LangOpts.CPlusPlus;
15908     }
15909     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
15910       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
15911     }
15912   } Diagnoser;
15913 
15914   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
15915 }
15916 
15917 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15918                                                  llvm::APSInt *Result,
15919                                                  unsigned DiagID,
15920                                                  AllowFoldKind CanFold) {
15921   class IDDiagnoser : public VerifyICEDiagnoser {
15922     unsigned DiagID;
15923 
15924   public:
15925     IDDiagnoser(unsigned DiagID)
15926       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15927 
15928     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
15929       return S.Diag(Loc, DiagID);
15930     }
15931   } Diagnoser(DiagID);
15932 
15933   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
15934 }
15935 
15936 Sema::SemaDiagnosticBuilder
15937 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
15938                                              QualType T) {
15939   return diagnoseNotICE(S, Loc);
15940 }
15941 
15942 Sema::SemaDiagnosticBuilder
15943 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
15944   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
15945 }
15946 
15947 ExprResult
15948 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15949                                       VerifyICEDiagnoser &Diagnoser,
15950                                       AllowFoldKind CanFold) {
15951   SourceLocation DiagLoc = E->getBeginLoc();
15952 
15953   if (getLangOpts().CPlusPlus11) {
15954     // C++11 [expr.const]p5:
15955     //   If an expression of literal class type is used in a context where an
15956     //   integral constant expression is required, then that class type shall
15957     //   have a single non-explicit conversion function to an integral or
15958     //   unscoped enumeration type
15959     ExprResult Converted;
15960     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15961       VerifyICEDiagnoser &BaseDiagnoser;
15962     public:
15963       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
15964           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
15965                                 BaseDiagnoser.Suppress, true),
15966             BaseDiagnoser(BaseDiagnoser) {}
15967 
15968       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15969                                            QualType T) override {
15970         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
15971       }
15972 
15973       SemaDiagnosticBuilder diagnoseIncomplete(
15974           Sema &S, SourceLocation Loc, QualType T) override {
15975         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15976       }
15977 
15978       SemaDiagnosticBuilder diagnoseExplicitConv(
15979           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15980         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15981       }
15982 
15983       SemaDiagnosticBuilder noteExplicitConv(
15984           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15985         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15986                  << ConvTy->isEnumeralType() << ConvTy;
15987       }
15988 
15989       SemaDiagnosticBuilder diagnoseAmbiguous(
15990           Sema &S, SourceLocation Loc, QualType T) override {
15991         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15992       }
15993 
15994       SemaDiagnosticBuilder noteAmbiguous(
15995           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15996         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15997                  << ConvTy->isEnumeralType() << ConvTy;
15998       }
15999 
16000       SemaDiagnosticBuilder diagnoseConversion(
16001           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16002         llvm_unreachable("conversion functions are permitted");
16003       }
16004     } ConvertDiagnoser(Diagnoser);
16005 
16006     Converted = PerformContextualImplicitConversion(DiagLoc, E,
16007                                                     ConvertDiagnoser);
16008     if (Converted.isInvalid())
16009       return Converted;
16010     E = Converted.get();
16011     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16012       return ExprError();
16013   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16014     // An ICE must be of integral or unscoped enumeration type.
16015     if (!Diagnoser.Suppress)
16016       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16017           << E->getSourceRange();
16018     return ExprError();
16019   }
16020 
16021   ExprResult RValueExpr = DefaultLvalueConversion(E);
16022   if (RValueExpr.isInvalid())
16023     return ExprError();
16024 
16025   E = RValueExpr.get();
16026 
16027   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16028   // in the non-ICE case.
16029   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16030     if (Result)
16031       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16032     if (!isa<ConstantExpr>(E))
16033       E = ConstantExpr::Create(Context, E);
16034     return E;
16035   }
16036 
16037   Expr::EvalResult EvalResult;
16038   SmallVector<PartialDiagnosticAt, 8> Notes;
16039   EvalResult.Diag = &Notes;
16040 
16041   // Try to evaluate the expression, and produce diagnostics explaining why it's
16042   // not a constant expression as a side-effect.
16043   bool Folded =
16044       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16045       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16046 
16047   if (!isa<ConstantExpr>(E))
16048     E = ConstantExpr::Create(Context, E, EvalResult.Val);
16049 
16050   // In C++11, we can rely on diagnostics being produced for any expression
16051   // which is not a constant expression. If no diagnostics were produced, then
16052   // this is a constant expression.
16053   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16054     if (Result)
16055       *Result = EvalResult.Val.getInt();
16056     return E;
16057   }
16058 
16059   // If our only note is the usual "invalid subexpression" note, just point
16060   // the caret at its location rather than producing an essentially
16061   // redundant note.
16062   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16063         diag::note_invalid_subexpr_in_const_expr) {
16064     DiagLoc = Notes[0].first;
16065     Notes.clear();
16066   }
16067 
16068   if (!Folded || !CanFold) {
16069     if (!Diagnoser.Suppress) {
16070       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16071       for (const PartialDiagnosticAt &Note : Notes)
16072         Diag(Note.first, Note.second);
16073     }
16074 
16075     return ExprError();
16076   }
16077 
16078   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16079   for (const PartialDiagnosticAt &Note : Notes)
16080     Diag(Note.first, Note.second);
16081 
16082   if (Result)
16083     *Result = EvalResult.Val.getInt();
16084   return E;
16085 }
16086 
16087 namespace {
16088   // Handle the case where we conclude a expression which we speculatively
16089   // considered to be unevaluated is actually evaluated.
16090   class TransformToPE : public TreeTransform<TransformToPE> {
16091     typedef TreeTransform<TransformToPE> BaseTransform;
16092 
16093   public:
16094     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16095 
16096     // Make sure we redo semantic analysis
16097     bool AlwaysRebuild() { return true; }
16098     bool ReplacingOriginal() { return true; }
16099 
16100     // We need to special-case DeclRefExprs referring to FieldDecls which
16101     // are not part of a member pointer formation; normal TreeTransforming
16102     // doesn't catch this case because of the way we represent them in the AST.
16103     // FIXME: This is a bit ugly; is it really the best way to handle this
16104     // case?
16105     //
16106     // Error on DeclRefExprs referring to FieldDecls.
16107     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16108       if (isa<FieldDecl>(E->getDecl()) &&
16109           !SemaRef.isUnevaluatedContext())
16110         return SemaRef.Diag(E->getLocation(),
16111                             diag::err_invalid_non_static_member_use)
16112             << E->getDecl() << E->getSourceRange();
16113 
16114       return BaseTransform::TransformDeclRefExpr(E);
16115     }
16116 
16117     // Exception: filter out member pointer formation
16118     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16119       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16120         return E;
16121 
16122       return BaseTransform::TransformUnaryOperator(E);
16123     }
16124 
16125     // The body of a lambda-expression is in a separate expression evaluation
16126     // context so never needs to be transformed.
16127     // FIXME: Ideally we wouldn't transform the closure type either, and would
16128     // just recreate the capture expressions and lambda expression.
16129     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16130       return SkipLambdaBody(E, Body);
16131     }
16132   };
16133 }
16134 
16135 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16136   assert(isUnevaluatedContext() &&
16137          "Should only transform unevaluated expressions");
16138   ExprEvalContexts.back().Context =
16139       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16140   if (isUnevaluatedContext())
16141     return E;
16142   return TransformToPE(*this).TransformExpr(E);
16143 }
16144 
16145 void
16146 Sema::PushExpressionEvaluationContext(
16147     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16148     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16149   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16150                                 LambdaContextDecl, ExprContext);
16151   Cleanup.reset();
16152   if (!MaybeODRUseExprs.empty())
16153     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16154 }
16155 
16156 void
16157 Sema::PushExpressionEvaluationContext(
16158     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16159     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16160   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16161   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16162 }
16163 
16164 namespace {
16165 
16166 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16167   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16168   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16169     if (E->getOpcode() == UO_Deref)
16170       return CheckPossibleDeref(S, E->getSubExpr());
16171   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16172     return CheckPossibleDeref(S, E->getBase());
16173   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16174     return CheckPossibleDeref(S, E->getBase());
16175   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16176     QualType Inner;
16177     QualType Ty = E->getType();
16178     if (const auto *Ptr = Ty->getAs<PointerType>())
16179       Inner = Ptr->getPointeeType();
16180     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16181       Inner = Arr->getElementType();
16182     else
16183       return nullptr;
16184 
16185     if (Inner->hasAttr(attr::NoDeref))
16186       return E;
16187   }
16188   return nullptr;
16189 }
16190 
16191 } // namespace
16192 
16193 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16194   for (const Expr *E : Rec.PossibleDerefs) {
16195     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16196     if (DeclRef) {
16197       const ValueDecl *Decl = DeclRef->getDecl();
16198       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16199           << Decl->getName() << E->getSourceRange();
16200       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16201     } else {
16202       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16203           << E->getSourceRange();
16204     }
16205   }
16206   Rec.PossibleDerefs.clear();
16207 }
16208 
16209 /// Check whether E, which is either a discarded-value expression or an
16210 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16211 /// and if so, remove it from the list of volatile-qualified assignments that
16212 /// we are going to warn are deprecated.
16213 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16214   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16215     return;
16216 
16217   // Note: ignoring parens here is not justified by the standard rules, but
16218   // ignoring parentheses seems like a more reasonable approach, and this only
16219   // drives a deprecation warning so doesn't affect conformance.
16220   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16221     if (BO->getOpcode() == BO_Assign) {
16222       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16223       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16224                  LHSs.end());
16225     }
16226   }
16227 }
16228 
16229 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16230   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16231       RebuildingImmediateInvocation)
16232     return E;
16233 
16234   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16235   /// It's OK if this fails; we'll also remove this in
16236   /// HandleImmediateInvocations, but catching it here allows us to avoid
16237   /// walking the AST looking for it in simple cases.
16238   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16239     if (auto *DeclRef =
16240             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16241       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16242 
16243   E = MaybeCreateExprWithCleanups(E);
16244 
16245   ConstantExpr *Res = ConstantExpr::Create(
16246       getASTContext(), E.get(),
16247       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16248                                    getASTContext()),
16249       /*IsImmediateInvocation*/ true);
16250   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16251   return Res;
16252 }
16253 
16254 static void EvaluateAndDiagnoseImmediateInvocation(
16255     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16256   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16257   Expr::EvalResult Eval;
16258   Eval.Diag = &Notes;
16259   ConstantExpr *CE = Candidate.getPointer();
16260   bool Result = CE->EvaluateAsConstantExpr(
16261       Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
16262   if (!Result || !Notes.empty()) {
16263     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16264     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16265       InnerExpr = FunctionalCast->getSubExpr();
16266     FunctionDecl *FD = nullptr;
16267     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16268       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16269     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16270       FD = Call->getConstructor();
16271     else
16272       llvm_unreachable("unhandled decl kind");
16273     assert(FD->isConsteval());
16274     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16275     for (auto &Note : Notes)
16276       SemaRef.Diag(Note.first, Note.second);
16277     return;
16278   }
16279   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16280 }
16281 
16282 static void RemoveNestedImmediateInvocation(
16283     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16284     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16285   struct ComplexRemove : TreeTransform<ComplexRemove> {
16286     using Base = TreeTransform<ComplexRemove>;
16287     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16288     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16289     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16290         CurrentII;
16291     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16292                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16293                   SmallVector<Sema::ImmediateInvocationCandidate,
16294                               4>::reverse_iterator Current)
16295         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16296     void RemoveImmediateInvocation(ConstantExpr* E) {
16297       auto It = std::find_if(CurrentII, IISet.rend(),
16298                              [E](Sema::ImmediateInvocationCandidate Elem) {
16299                                return Elem.getPointer() == E;
16300                              });
16301       assert(It != IISet.rend() &&
16302              "ConstantExpr marked IsImmediateInvocation should "
16303              "be present");
16304       It->setInt(1); // Mark as deleted
16305     }
16306     ExprResult TransformConstantExpr(ConstantExpr *E) {
16307       if (!E->isImmediateInvocation())
16308         return Base::TransformConstantExpr(E);
16309       RemoveImmediateInvocation(E);
16310       return Base::TransformExpr(E->getSubExpr());
16311     }
16312     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16313     /// we need to remove its DeclRefExpr from the DRSet.
16314     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16315       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16316       return Base::TransformCXXOperatorCallExpr(E);
16317     }
16318     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16319     /// here.
16320     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16321       if (!Init)
16322         return Init;
16323       /// ConstantExpr are the first layer of implicit node to be removed so if
16324       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16325       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16326         if (CE->isImmediateInvocation())
16327           RemoveImmediateInvocation(CE);
16328       return Base::TransformInitializer(Init, NotCopyInit);
16329     }
16330     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16331       DRSet.erase(E);
16332       return E;
16333     }
16334     bool AlwaysRebuild() { return false; }
16335     bool ReplacingOriginal() { return true; }
16336     bool AllowSkippingCXXConstructExpr() {
16337       bool Res = AllowSkippingFirstCXXConstructExpr;
16338       AllowSkippingFirstCXXConstructExpr = true;
16339       return Res;
16340     }
16341     bool AllowSkippingFirstCXXConstructExpr = true;
16342   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16343                 Rec.ImmediateInvocationCandidates, It);
16344 
16345   /// CXXConstructExpr with a single argument are getting skipped by
16346   /// TreeTransform in some situtation because they could be implicit. This
16347   /// can only occur for the top-level CXXConstructExpr because it is used
16348   /// nowhere in the expression being transformed therefore will not be rebuilt.
16349   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16350   /// skipping the first CXXConstructExpr.
16351   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16352     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16353 
16354   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16355   assert(Res.isUsable());
16356   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16357   It->getPointer()->setSubExpr(Res.get());
16358 }
16359 
16360 static void
16361 HandleImmediateInvocations(Sema &SemaRef,
16362                            Sema::ExpressionEvaluationContextRecord &Rec) {
16363   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16364        Rec.ReferenceToConsteval.size() == 0) ||
16365       SemaRef.RebuildingImmediateInvocation)
16366     return;
16367 
16368   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16369   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16370   /// need to remove ReferenceToConsteval in the immediate invocation.
16371   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16372 
16373     /// Prevent sema calls during the tree transform from adding pointers that
16374     /// are already in the sets.
16375     llvm::SaveAndRestore<bool> DisableIITracking(
16376         SemaRef.RebuildingImmediateInvocation, true);
16377 
16378     /// Prevent diagnostic during tree transfrom as they are duplicates
16379     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16380 
16381     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16382          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16383       if (!It->getInt())
16384         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16385   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16386              Rec.ReferenceToConsteval.size()) {
16387     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16388       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16389       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16390       bool VisitDeclRefExpr(DeclRefExpr *E) {
16391         DRSet.erase(E);
16392         return DRSet.size();
16393       }
16394     } Visitor(Rec.ReferenceToConsteval);
16395     Visitor.TraverseStmt(
16396         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16397   }
16398   for (auto CE : Rec.ImmediateInvocationCandidates)
16399     if (!CE.getInt())
16400       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16401   for (auto DR : Rec.ReferenceToConsteval) {
16402     auto *FD = cast<FunctionDecl>(DR->getDecl());
16403     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16404         << FD;
16405     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16406   }
16407 }
16408 
16409 void Sema::PopExpressionEvaluationContext() {
16410   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16411   unsigned NumTypos = Rec.NumTypos;
16412 
16413   if (!Rec.Lambdas.empty()) {
16414     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16415     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16416         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16417       unsigned D;
16418       if (Rec.isUnevaluated()) {
16419         // C++11 [expr.prim.lambda]p2:
16420         //   A lambda-expression shall not appear in an unevaluated operand
16421         //   (Clause 5).
16422         D = diag::err_lambda_unevaluated_operand;
16423       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16424         // C++1y [expr.const]p2:
16425         //   A conditional-expression e is a core constant expression unless the
16426         //   evaluation of e, following the rules of the abstract machine, would
16427         //   evaluate [...] a lambda-expression.
16428         D = diag::err_lambda_in_constant_expression;
16429       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16430         // C++17 [expr.prim.lamda]p2:
16431         // A lambda-expression shall not appear [...] in a template-argument.
16432         D = diag::err_lambda_in_invalid_context;
16433       } else
16434         llvm_unreachable("Couldn't infer lambda error message.");
16435 
16436       for (const auto *L : Rec.Lambdas)
16437         Diag(L->getBeginLoc(), D);
16438     }
16439   }
16440 
16441   WarnOnPendingNoDerefs(Rec);
16442   HandleImmediateInvocations(*this, Rec);
16443 
16444   // Warn on any volatile-qualified simple-assignments that are not discarded-
16445   // value expressions nor unevaluated operands (those cases get removed from
16446   // this list by CheckUnusedVolatileAssignment).
16447   for (auto *BO : Rec.VolatileAssignmentLHSs)
16448     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16449         << BO->getType();
16450 
16451   // When are coming out of an unevaluated context, clear out any
16452   // temporaries that we may have created as part of the evaluation of
16453   // the expression in that context: they aren't relevant because they
16454   // will never be constructed.
16455   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16456     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16457                              ExprCleanupObjects.end());
16458     Cleanup = Rec.ParentCleanup;
16459     CleanupVarDeclMarking();
16460     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16461   // Otherwise, merge the contexts together.
16462   } else {
16463     Cleanup.mergeFrom(Rec.ParentCleanup);
16464     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16465                             Rec.SavedMaybeODRUseExprs.end());
16466   }
16467 
16468   // Pop the current expression evaluation context off the stack.
16469   ExprEvalContexts.pop_back();
16470 
16471   // The global expression evaluation context record is never popped.
16472   ExprEvalContexts.back().NumTypos += NumTypos;
16473 }
16474 
16475 void Sema::DiscardCleanupsInEvaluationContext() {
16476   ExprCleanupObjects.erase(
16477          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16478          ExprCleanupObjects.end());
16479   Cleanup.reset();
16480   MaybeODRUseExprs.clear();
16481 }
16482 
16483 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16484   ExprResult Result = CheckPlaceholderExpr(E);
16485   if (Result.isInvalid())
16486     return ExprError();
16487   E = Result.get();
16488   if (!E->getType()->isVariablyModifiedType())
16489     return E;
16490   return TransformToPotentiallyEvaluated(E);
16491 }
16492 
16493 /// Are we in a context that is potentially constant evaluated per C++20
16494 /// [expr.const]p12?
16495 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16496   /// C++2a [expr.const]p12:
16497   //   An expression or conversion is potentially constant evaluated if it is
16498   switch (SemaRef.ExprEvalContexts.back().Context) {
16499     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16500       // -- a manifestly constant-evaluated expression,
16501     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16502     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16503     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16504       // -- a potentially-evaluated expression,
16505     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16506       // -- an immediate subexpression of a braced-init-list,
16507 
16508       // -- [FIXME] an expression of the form & cast-expression that occurs
16509       //    within a templated entity
16510       // -- a subexpression of one of the above that is not a subexpression of
16511       // a nested unevaluated operand.
16512       return true;
16513 
16514     case Sema::ExpressionEvaluationContext::Unevaluated:
16515     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16516       // Expressions in this context are never evaluated.
16517       return false;
16518   }
16519   llvm_unreachable("Invalid context");
16520 }
16521 
16522 /// Return true if this function has a calling convention that requires mangling
16523 /// in the size of the parameter pack.
16524 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16525   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16526   // we don't need parameter type sizes.
16527   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16528   if (!TT.isOSWindows() || !TT.isX86())
16529     return false;
16530 
16531   // If this is C++ and this isn't an extern "C" function, parameters do not
16532   // need to be complete. In this case, C++ mangling will apply, which doesn't
16533   // use the size of the parameters.
16534   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16535     return false;
16536 
16537   // Stdcall, fastcall, and vectorcall need this special treatment.
16538   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16539   switch (CC) {
16540   case CC_X86StdCall:
16541   case CC_X86FastCall:
16542   case CC_X86VectorCall:
16543     return true;
16544   default:
16545     break;
16546   }
16547   return false;
16548 }
16549 
16550 /// Require that all of the parameter types of function be complete. Normally,
16551 /// parameter types are only required to be complete when a function is called
16552 /// or defined, but to mangle functions with certain calling conventions, the
16553 /// mangler needs to know the size of the parameter list. In this situation,
16554 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16555 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16556 /// result in a linker error. Clang doesn't implement this behavior, and instead
16557 /// attempts to error at compile time.
16558 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16559                                                   SourceLocation Loc) {
16560   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16561     FunctionDecl *FD;
16562     ParmVarDecl *Param;
16563 
16564   public:
16565     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16566         : FD(FD), Param(Param) {}
16567 
16568     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16569       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16570       StringRef CCName;
16571       switch (CC) {
16572       case CC_X86StdCall:
16573         CCName = "stdcall";
16574         break;
16575       case CC_X86FastCall:
16576         CCName = "fastcall";
16577         break;
16578       case CC_X86VectorCall:
16579         CCName = "vectorcall";
16580         break;
16581       default:
16582         llvm_unreachable("CC does not need mangling");
16583       }
16584 
16585       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16586           << Param->getDeclName() << FD->getDeclName() << CCName;
16587     }
16588   };
16589 
16590   for (ParmVarDecl *Param : FD->parameters()) {
16591     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16592     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16593   }
16594 }
16595 
16596 namespace {
16597 enum class OdrUseContext {
16598   /// Declarations in this context are not odr-used.
16599   None,
16600   /// Declarations in this context are formally odr-used, but this is a
16601   /// dependent context.
16602   Dependent,
16603   /// Declarations in this context are odr-used but not actually used (yet).
16604   FormallyOdrUsed,
16605   /// Declarations in this context are used.
16606   Used
16607 };
16608 }
16609 
16610 /// Are we within a context in which references to resolved functions or to
16611 /// variables result in odr-use?
16612 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16613   OdrUseContext Result;
16614 
16615   switch (SemaRef.ExprEvalContexts.back().Context) {
16616     case Sema::ExpressionEvaluationContext::Unevaluated:
16617     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16618     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16619       return OdrUseContext::None;
16620 
16621     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16622     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16623       Result = OdrUseContext::Used;
16624       break;
16625 
16626     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16627       Result = OdrUseContext::FormallyOdrUsed;
16628       break;
16629 
16630     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16631       // A default argument formally results in odr-use, but doesn't actually
16632       // result in a use in any real sense until it itself is used.
16633       Result = OdrUseContext::FormallyOdrUsed;
16634       break;
16635   }
16636 
16637   if (SemaRef.CurContext->isDependentContext())
16638     return OdrUseContext::Dependent;
16639 
16640   return Result;
16641 }
16642 
16643 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16644   if (!Func->isConstexpr())
16645     return false;
16646 
16647   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
16648     return true;
16649   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
16650   return CCD && CCD->getInheritedConstructor();
16651 }
16652 
16653 /// Mark a function referenced, and check whether it is odr-used
16654 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16655 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16656                                   bool MightBeOdrUse) {
16657   assert(Func && "No function?");
16658 
16659   Func->setReferenced();
16660 
16661   // Recursive functions aren't really used until they're used from some other
16662   // context.
16663   bool IsRecursiveCall = CurContext == Func;
16664 
16665   // C++11 [basic.def.odr]p3:
16666   //   A function whose name appears as a potentially-evaluated expression is
16667   //   odr-used if it is the unique lookup result or the selected member of a
16668   //   set of overloaded functions [...].
16669   //
16670   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16671   // can just check that here.
16672   OdrUseContext OdrUse =
16673       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16674   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16675     OdrUse = OdrUseContext::FormallyOdrUsed;
16676 
16677   // Trivial default constructors and destructors are never actually used.
16678   // FIXME: What about other special members?
16679   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16680       OdrUse == OdrUseContext::Used) {
16681     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16682       if (Constructor->isDefaultConstructor())
16683         OdrUse = OdrUseContext::FormallyOdrUsed;
16684     if (isa<CXXDestructorDecl>(Func))
16685       OdrUse = OdrUseContext::FormallyOdrUsed;
16686   }
16687 
16688   // C++20 [expr.const]p12:
16689   //   A function [...] is needed for constant evaluation if it is [...] a
16690   //   constexpr function that is named by an expression that is potentially
16691   //   constant evaluated
16692   bool NeededForConstantEvaluation =
16693       isPotentiallyConstantEvaluatedContext(*this) &&
16694       isImplicitlyDefinableConstexprFunction(Func);
16695 
16696   // Determine whether we require a function definition to exist, per
16697   // C++11 [temp.inst]p3:
16698   //   Unless a function template specialization has been explicitly
16699   //   instantiated or explicitly specialized, the function template
16700   //   specialization is implicitly instantiated when the specialization is
16701   //   referenced in a context that requires a function definition to exist.
16702   // C++20 [temp.inst]p7:
16703   //   The existence of a definition of a [...] function is considered to
16704   //   affect the semantics of the program if the [...] function is needed for
16705   //   constant evaluation by an expression
16706   // C++20 [basic.def.odr]p10:
16707   //   Every program shall contain exactly one definition of every non-inline
16708   //   function or variable that is odr-used in that program outside of a
16709   //   discarded statement
16710   // C++20 [special]p1:
16711   //   The implementation will implicitly define [defaulted special members]
16712   //   if they are odr-used or needed for constant evaluation.
16713   //
16714   // Note that we skip the implicit instantiation of templates that are only
16715   // used in unused default arguments or by recursive calls to themselves.
16716   // This is formally non-conforming, but seems reasonable in practice.
16717   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16718                                              NeededForConstantEvaluation);
16719 
16720   // C++14 [temp.expl.spec]p6:
16721   //   If a template [...] is explicitly specialized then that specialization
16722   //   shall be declared before the first use of that specialization that would
16723   //   cause an implicit instantiation to take place, in every translation unit
16724   //   in which such a use occurs
16725   if (NeedDefinition &&
16726       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16727        Func->getMemberSpecializationInfo()))
16728     checkSpecializationVisibility(Loc, Func);
16729 
16730   if (getLangOpts().CUDA)
16731     CheckCUDACall(Loc, Func);
16732 
16733   if (getLangOpts().SYCLIsDevice)
16734     checkSYCLDeviceFunction(Loc, Func);
16735 
16736   // If we need a definition, try to create one.
16737   if (NeedDefinition && !Func->getBody()) {
16738     runWithSufficientStackSpace(Loc, [&] {
16739       if (CXXConstructorDecl *Constructor =
16740               dyn_cast<CXXConstructorDecl>(Func)) {
16741         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16742         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16743           if (Constructor->isDefaultConstructor()) {
16744             if (Constructor->isTrivial() &&
16745                 !Constructor->hasAttr<DLLExportAttr>())
16746               return;
16747             DefineImplicitDefaultConstructor(Loc, Constructor);
16748           } else if (Constructor->isCopyConstructor()) {
16749             DefineImplicitCopyConstructor(Loc, Constructor);
16750           } else if (Constructor->isMoveConstructor()) {
16751             DefineImplicitMoveConstructor(Loc, Constructor);
16752           }
16753         } else if (Constructor->getInheritedConstructor()) {
16754           DefineInheritingConstructor(Loc, Constructor);
16755         }
16756       } else if (CXXDestructorDecl *Destructor =
16757                      dyn_cast<CXXDestructorDecl>(Func)) {
16758         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16759         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16760           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16761             return;
16762           DefineImplicitDestructor(Loc, Destructor);
16763         }
16764         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16765           MarkVTableUsed(Loc, Destructor->getParent());
16766       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16767         if (MethodDecl->isOverloadedOperator() &&
16768             MethodDecl->getOverloadedOperator() == OO_Equal) {
16769           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16770           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16771             if (MethodDecl->isCopyAssignmentOperator())
16772               DefineImplicitCopyAssignment(Loc, MethodDecl);
16773             else if (MethodDecl->isMoveAssignmentOperator())
16774               DefineImplicitMoveAssignment(Loc, MethodDecl);
16775           }
16776         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16777                    MethodDecl->getParent()->isLambda()) {
16778           CXXConversionDecl *Conversion =
16779               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16780           if (Conversion->isLambdaToBlockPointerConversion())
16781             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16782           else
16783             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16784         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16785           MarkVTableUsed(Loc, MethodDecl->getParent());
16786       }
16787 
16788       if (Func->isDefaulted() && !Func->isDeleted()) {
16789         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16790         if (DCK != DefaultedComparisonKind::None)
16791           DefineDefaultedComparison(Loc, Func, DCK);
16792       }
16793 
16794       // Implicit instantiation of function templates and member functions of
16795       // class templates.
16796       if (Func->isImplicitlyInstantiable()) {
16797         TemplateSpecializationKind TSK =
16798             Func->getTemplateSpecializationKindForInstantiation();
16799         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16800         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16801         if (FirstInstantiation) {
16802           PointOfInstantiation = Loc;
16803           if (auto *MSI = Func->getMemberSpecializationInfo())
16804             MSI->setPointOfInstantiation(Loc);
16805             // FIXME: Notify listener.
16806           else
16807             Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16808         } else if (TSK != TSK_ImplicitInstantiation) {
16809           // Use the point of use as the point of instantiation, instead of the
16810           // point of explicit instantiation (which we track as the actual point
16811           // of instantiation). This gives better backtraces in diagnostics.
16812           PointOfInstantiation = Loc;
16813         }
16814 
16815         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16816             Func->isConstexpr()) {
16817           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16818               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16819               CodeSynthesisContexts.size())
16820             PendingLocalImplicitInstantiations.push_back(
16821                 std::make_pair(Func, PointOfInstantiation));
16822           else if (Func->isConstexpr())
16823             // Do not defer instantiations of constexpr functions, to avoid the
16824             // expression evaluator needing to call back into Sema if it sees a
16825             // call to such a function.
16826             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16827           else {
16828             Func->setInstantiationIsPending(true);
16829             PendingInstantiations.push_back(
16830                 std::make_pair(Func, PointOfInstantiation));
16831             // Notify the consumer that a function was implicitly instantiated.
16832             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16833           }
16834         }
16835       } else {
16836         // Walk redefinitions, as some of them may be instantiable.
16837         for (auto i : Func->redecls()) {
16838           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16839             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16840         }
16841       }
16842     });
16843   }
16844 
16845   // C++14 [except.spec]p17:
16846   //   An exception-specification is considered to be needed when:
16847   //   - the function is odr-used or, if it appears in an unevaluated operand,
16848   //     would be odr-used if the expression were potentially-evaluated;
16849   //
16850   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16851   // function is a pure virtual function we're calling, and in that case the
16852   // function was selected by overload resolution and we need to resolve its
16853   // exception specification for a different reason.
16854   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16855   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16856     ResolveExceptionSpec(Loc, FPT);
16857 
16858   // If this is the first "real" use, act on that.
16859   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16860     // Keep track of used but undefined functions.
16861     if (!Func->isDefined()) {
16862       if (mightHaveNonExternalLinkage(Func))
16863         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16864       else if (Func->getMostRecentDecl()->isInlined() &&
16865                !LangOpts.GNUInline &&
16866                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16867         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16868       else if (isExternalWithNoLinkageType(Func))
16869         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16870     }
16871 
16872     // Some x86 Windows calling conventions mangle the size of the parameter
16873     // pack into the name. Computing the size of the parameters requires the
16874     // parameter types to be complete. Check that now.
16875     if (funcHasParameterSizeMangling(*this, Func))
16876       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16877 
16878     // In the MS C++ ABI, the compiler emits destructor variants where they are
16879     // used. If the destructor is used here but defined elsewhere, mark the
16880     // virtual base destructors referenced. If those virtual base destructors
16881     // are inline, this will ensure they are defined when emitting the complete
16882     // destructor variant. This checking may be redundant if the destructor is
16883     // provided later in this TU.
16884     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16885       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16886         CXXRecordDecl *Parent = Dtor->getParent();
16887         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16888           CheckCompleteDestructorVariant(Loc, Dtor);
16889       }
16890     }
16891 
16892     Func->markUsed(Context);
16893   }
16894 }
16895 
16896 /// Directly mark a variable odr-used. Given a choice, prefer to use
16897 /// MarkVariableReferenced since it does additional checks and then
16898 /// calls MarkVarDeclODRUsed.
16899 /// If the variable must be captured:
16900 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16901 ///  - else capture it in the DeclContext that maps to the
16902 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16903 static void
16904 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16905                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16906   // Keep track of used but undefined variables.
16907   // FIXME: We shouldn't suppress this warning for static data members.
16908   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16909       (!Var->isExternallyVisible() || Var->isInline() ||
16910        SemaRef.isExternalWithNoLinkageType(Var)) &&
16911       !(Var->isStaticDataMember() && Var->hasInit())) {
16912     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16913     if (old.isInvalid())
16914       old = Loc;
16915   }
16916   QualType CaptureType, DeclRefType;
16917   if (SemaRef.LangOpts.OpenMP)
16918     SemaRef.tryCaptureOpenMPLambdas(Var);
16919   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16920     /*EllipsisLoc*/ SourceLocation(),
16921     /*BuildAndDiagnose*/ true,
16922     CaptureType, DeclRefType,
16923     FunctionScopeIndexToStopAt);
16924 
16925   Var->markUsed(SemaRef.Context);
16926 }
16927 
16928 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16929                                              SourceLocation Loc,
16930                                              unsigned CapturingScopeIndex) {
16931   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16932 }
16933 
16934 static void
16935 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16936                                    ValueDecl *var, DeclContext *DC) {
16937   DeclContext *VarDC = var->getDeclContext();
16938 
16939   //  If the parameter still belongs to the translation unit, then
16940   //  we're actually just using one parameter in the declaration of
16941   //  the next.
16942   if (isa<ParmVarDecl>(var) &&
16943       isa<TranslationUnitDecl>(VarDC))
16944     return;
16945 
16946   // For C code, don't diagnose about capture if we're not actually in code
16947   // right now; it's impossible to write a non-constant expression outside of
16948   // function context, so we'll get other (more useful) diagnostics later.
16949   //
16950   // For C++, things get a bit more nasty... it would be nice to suppress this
16951   // diagnostic for certain cases like using a local variable in an array bound
16952   // for a member of a local class, but the correct predicate is not obvious.
16953   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16954     return;
16955 
16956   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16957   unsigned ContextKind = 3; // unknown
16958   if (isa<CXXMethodDecl>(VarDC) &&
16959       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16960     ContextKind = 2;
16961   } else if (isa<FunctionDecl>(VarDC)) {
16962     ContextKind = 0;
16963   } else if (isa<BlockDecl>(VarDC)) {
16964     ContextKind = 1;
16965   }
16966 
16967   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16968     << var << ValueKind << ContextKind << VarDC;
16969   S.Diag(var->getLocation(), diag::note_entity_declared_at)
16970       << var;
16971 
16972   // FIXME: Add additional diagnostic info about class etc. which prevents
16973   // capture.
16974 }
16975 
16976 
16977 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16978                                       bool &SubCapturesAreNested,
16979                                       QualType &CaptureType,
16980                                       QualType &DeclRefType) {
16981    // Check whether we've already captured it.
16982   if (CSI->CaptureMap.count(Var)) {
16983     // If we found a capture, any subcaptures are nested.
16984     SubCapturesAreNested = true;
16985 
16986     // Retrieve the capture type for this variable.
16987     CaptureType = CSI->getCapture(Var).getCaptureType();
16988 
16989     // Compute the type of an expression that refers to this variable.
16990     DeclRefType = CaptureType.getNonReferenceType();
16991 
16992     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16993     // are mutable in the sense that user can change their value - they are
16994     // private instances of the captured declarations.
16995     const Capture &Cap = CSI->getCapture(Var);
16996     if (Cap.isCopyCapture() &&
16997         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16998         !(isa<CapturedRegionScopeInfo>(CSI) &&
16999           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17000       DeclRefType.addConst();
17001     return true;
17002   }
17003   return false;
17004 }
17005 
17006 // Only block literals, captured statements, and lambda expressions can
17007 // capture; other scopes don't work.
17008 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17009                                  SourceLocation Loc,
17010                                  const bool Diagnose, Sema &S) {
17011   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17012     return getLambdaAwareParentOfDeclContext(DC);
17013   else if (Var->hasLocalStorage()) {
17014     if (Diagnose)
17015        diagnoseUncapturableValueReference(S, Loc, Var, DC);
17016   }
17017   return nullptr;
17018 }
17019 
17020 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17021 // certain types of variables (unnamed, variably modified types etc.)
17022 // so check for eligibility.
17023 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17024                                  SourceLocation Loc,
17025                                  const bool Diagnose, Sema &S) {
17026 
17027   bool IsBlock = isa<BlockScopeInfo>(CSI);
17028   bool IsLambda = isa<LambdaScopeInfo>(CSI);
17029 
17030   // Lambdas are not allowed to capture unnamed variables
17031   // (e.g. anonymous unions).
17032   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17033   // assuming that's the intent.
17034   if (IsLambda && !Var->getDeclName()) {
17035     if (Diagnose) {
17036       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17037       S.Diag(Var->getLocation(), diag::note_declared_at);
17038     }
17039     return false;
17040   }
17041 
17042   // Prohibit variably-modified types in blocks; they're difficult to deal with.
17043   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17044     if (Diagnose) {
17045       S.Diag(Loc, diag::err_ref_vm_type);
17046       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17047     }
17048     return false;
17049   }
17050   // Prohibit structs with flexible array members too.
17051   // We cannot capture what is in the tail end of the struct.
17052   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17053     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17054       if (Diagnose) {
17055         if (IsBlock)
17056           S.Diag(Loc, diag::err_ref_flexarray_type);
17057         else
17058           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17059         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17060       }
17061       return false;
17062     }
17063   }
17064   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17065   // Lambdas and captured statements are not allowed to capture __block
17066   // variables; they don't support the expected semantics.
17067   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17068     if (Diagnose) {
17069       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17070       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17071     }
17072     return false;
17073   }
17074   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17075   if (S.getLangOpts().OpenCL && IsBlock &&
17076       Var->getType()->isBlockPointerType()) {
17077     if (Diagnose)
17078       S.Diag(Loc, diag::err_opencl_block_ref_block);
17079     return false;
17080   }
17081 
17082   return true;
17083 }
17084 
17085 // Returns true if the capture by block was successful.
17086 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17087                                  SourceLocation Loc,
17088                                  const bool BuildAndDiagnose,
17089                                  QualType &CaptureType,
17090                                  QualType &DeclRefType,
17091                                  const bool Nested,
17092                                  Sema &S, bool Invalid) {
17093   bool ByRef = false;
17094 
17095   // Blocks are not allowed to capture arrays, excepting OpenCL.
17096   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17097   // (decayed to pointers).
17098   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17099     if (BuildAndDiagnose) {
17100       S.Diag(Loc, diag::err_ref_array_type);
17101       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17102       Invalid = true;
17103     } else {
17104       return false;
17105     }
17106   }
17107 
17108   // Forbid the block-capture of autoreleasing variables.
17109   if (!Invalid &&
17110       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17111     if (BuildAndDiagnose) {
17112       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17113         << /*block*/ 0;
17114       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17115       Invalid = true;
17116     } else {
17117       return false;
17118     }
17119   }
17120 
17121   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17122   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17123     QualType PointeeTy = PT->getPointeeType();
17124 
17125     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17126         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17127         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17128       if (BuildAndDiagnose) {
17129         SourceLocation VarLoc = Var->getLocation();
17130         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17131         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17132       }
17133     }
17134   }
17135 
17136   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17137   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17138       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17139     // Block capture by reference does not change the capture or
17140     // declaration reference types.
17141     ByRef = true;
17142   } else {
17143     // Block capture by copy introduces 'const'.
17144     CaptureType = CaptureType.getNonReferenceType().withConst();
17145     DeclRefType = CaptureType;
17146   }
17147 
17148   // Actually capture the variable.
17149   if (BuildAndDiagnose)
17150     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17151                     CaptureType, Invalid);
17152 
17153   return !Invalid;
17154 }
17155 
17156 
17157 /// Capture the given variable in the captured region.
17158 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17159                                     VarDecl *Var,
17160                                     SourceLocation Loc,
17161                                     const bool BuildAndDiagnose,
17162                                     QualType &CaptureType,
17163                                     QualType &DeclRefType,
17164                                     const bool RefersToCapturedVariable,
17165                                     Sema &S, bool Invalid) {
17166   // By default, capture variables by reference.
17167   bool ByRef = true;
17168   // Using an LValue reference type is consistent with Lambdas (see below).
17169   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17170     if (S.isOpenMPCapturedDecl(Var)) {
17171       bool HasConst = DeclRefType.isConstQualified();
17172       DeclRefType = DeclRefType.getUnqualifiedType();
17173       // Don't lose diagnostics about assignments to const.
17174       if (HasConst)
17175         DeclRefType.addConst();
17176     }
17177     // Do not capture firstprivates in tasks.
17178     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17179         OMPC_unknown)
17180       return true;
17181     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17182                                     RSI->OpenMPCaptureLevel);
17183   }
17184 
17185   if (ByRef)
17186     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17187   else
17188     CaptureType = DeclRefType;
17189 
17190   // Actually capture the variable.
17191   if (BuildAndDiagnose)
17192     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17193                     Loc, SourceLocation(), CaptureType, Invalid);
17194 
17195   return !Invalid;
17196 }
17197 
17198 /// Capture the given variable in the lambda.
17199 static bool captureInLambda(LambdaScopeInfo *LSI,
17200                             VarDecl *Var,
17201                             SourceLocation Loc,
17202                             const bool BuildAndDiagnose,
17203                             QualType &CaptureType,
17204                             QualType &DeclRefType,
17205                             const bool RefersToCapturedVariable,
17206                             const Sema::TryCaptureKind Kind,
17207                             SourceLocation EllipsisLoc,
17208                             const bool IsTopScope,
17209                             Sema &S, bool Invalid) {
17210   // Determine whether we are capturing by reference or by value.
17211   bool ByRef = false;
17212   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17213     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17214   } else {
17215     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17216   }
17217 
17218   // Compute the type of the field that will capture this variable.
17219   if (ByRef) {
17220     // C++11 [expr.prim.lambda]p15:
17221     //   An entity is captured by reference if it is implicitly or
17222     //   explicitly captured but not captured by copy. It is
17223     //   unspecified whether additional unnamed non-static data
17224     //   members are declared in the closure type for entities
17225     //   captured by reference.
17226     //
17227     // FIXME: It is not clear whether we want to build an lvalue reference
17228     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17229     // to do the former, while EDG does the latter. Core issue 1249 will
17230     // clarify, but for now we follow GCC because it's a more permissive and
17231     // easily defensible position.
17232     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17233   } else {
17234     // C++11 [expr.prim.lambda]p14:
17235     //   For each entity captured by copy, an unnamed non-static
17236     //   data member is declared in the closure type. The
17237     //   declaration order of these members is unspecified. The type
17238     //   of such a data member is the type of the corresponding
17239     //   captured entity if the entity is not a reference to an
17240     //   object, or the referenced type otherwise. [Note: If the
17241     //   captured entity is a reference to a function, the
17242     //   corresponding data member is also a reference to a
17243     //   function. - end note ]
17244     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17245       if (!RefType->getPointeeType()->isFunctionType())
17246         CaptureType = RefType->getPointeeType();
17247     }
17248 
17249     // Forbid the lambda copy-capture of autoreleasing variables.
17250     if (!Invalid &&
17251         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17252       if (BuildAndDiagnose) {
17253         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17254         S.Diag(Var->getLocation(), diag::note_previous_decl)
17255           << Var->getDeclName();
17256         Invalid = true;
17257       } else {
17258         return false;
17259       }
17260     }
17261 
17262     // Make sure that by-copy captures are of a complete and non-abstract type.
17263     if (!Invalid && BuildAndDiagnose) {
17264       if (!CaptureType->isDependentType() &&
17265           S.RequireCompleteSizedType(
17266               Loc, CaptureType,
17267               diag::err_capture_of_incomplete_or_sizeless_type,
17268               Var->getDeclName()))
17269         Invalid = true;
17270       else if (S.RequireNonAbstractType(Loc, CaptureType,
17271                                         diag::err_capture_of_abstract_type))
17272         Invalid = true;
17273     }
17274   }
17275 
17276   // Compute the type of a reference to this captured variable.
17277   if (ByRef)
17278     DeclRefType = CaptureType.getNonReferenceType();
17279   else {
17280     // C++ [expr.prim.lambda]p5:
17281     //   The closure type for a lambda-expression has a public inline
17282     //   function call operator [...]. This function call operator is
17283     //   declared const (9.3.1) if and only if the lambda-expression's
17284     //   parameter-declaration-clause is not followed by mutable.
17285     DeclRefType = CaptureType.getNonReferenceType();
17286     if (!LSI->Mutable && !CaptureType->isReferenceType())
17287       DeclRefType.addConst();
17288   }
17289 
17290   // Add the capture.
17291   if (BuildAndDiagnose)
17292     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17293                     Loc, EllipsisLoc, CaptureType, Invalid);
17294 
17295   return !Invalid;
17296 }
17297 
17298 bool Sema::tryCaptureVariable(
17299     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17300     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17301     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17302   // An init-capture is notionally from the context surrounding its
17303   // declaration, but its parent DC is the lambda class.
17304   DeclContext *VarDC = Var->getDeclContext();
17305   if (Var->isInitCapture())
17306     VarDC = VarDC->getParent();
17307 
17308   DeclContext *DC = CurContext;
17309   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17310       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17311   // We need to sync up the Declaration Context with the
17312   // FunctionScopeIndexToStopAt
17313   if (FunctionScopeIndexToStopAt) {
17314     unsigned FSIndex = FunctionScopes.size() - 1;
17315     while (FSIndex != MaxFunctionScopesIndex) {
17316       DC = getLambdaAwareParentOfDeclContext(DC);
17317       --FSIndex;
17318     }
17319   }
17320 
17321 
17322   // If the variable is declared in the current context, there is no need to
17323   // capture it.
17324   if (VarDC == DC) return true;
17325 
17326   // Capture global variables if it is required to use private copy of this
17327   // variable.
17328   bool IsGlobal = !Var->hasLocalStorage();
17329   if (IsGlobal &&
17330       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17331                                                 MaxFunctionScopesIndex)))
17332     return true;
17333   Var = Var->getCanonicalDecl();
17334 
17335   // Walk up the stack to determine whether we can capture the variable,
17336   // performing the "simple" checks that don't depend on type. We stop when
17337   // we've either hit the declared scope of the variable or find an existing
17338   // capture of that variable.  We start from the innermost capturing-entity
17339   // (the DC) and ensure that all intervening capturing-entities
17340   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17341   // declcontext can either capture the variable or have already captured
17342   // the variable.
17343   CaptureType = Var->getType();
17344   DeclRefType = CaptureType.getNonReferenceType();
17345   bool Nested = false;
17346   bool Explicit = (Kind != TryCapture_Implicit);
17347   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17348   do {
17349     // Only block literals, captured statements, and lambda expressions can
17350     // capture; other scopes don't work.
17351     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17352                                                               ExprLoc,
17353                                                               BuildAndDiagnose,
17354                                                               *this);
17355     // We need to check for the parent *first* because, if we *have*
17356     // private-captured a global variable, we need to recursively capture it in
17357     // intermediate blocks, lambdas, etc.
17358     if (!ParentDC) {
17359       if (IsGlobal) {
17360         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17361         break;
17362       }
17363       return true;
17364     }
17365 
17366     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17367     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17368 
17369 
17370     // Check whether we've already captured it.
17371     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17372                                              DeclRefType)) {
17373       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17374       break;
17375     }
17376     // If we are instantiating a generic lambda call operator body,
17377     // we do not want to capture new variables.  What was captured
17378     // during either a lambdas transformation or initial parsing
17379     // should be used.
17380     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17381       if (BuildAndDiagnose) {
17382         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17383         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17384           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17385           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17386           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17387         } else
17388           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17389       }
17390       return true;
17391     }
17392 
17393     // Try to capture variable-length arrays types.
17394     if (Var->getType()->isVariablyModifiedType()) {
17395       // We're going to walk down into the type and look for VLA
17396       // expressions.
17397       QualType QTy = Var->getType();
17398       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17399         QTy = PVD->getOriginalType();
17400       captureVariablyModifiedType(Context, QTy, CSI);
17401     }
17402 
17403     if (getLangOpts().OpenMP) {
17404       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17405         // OpenMP private variables should not be captured in outer scope, so
17406         // just break here. Similarly, global variables that are captured in a
17407         // target region should not be captured outside the scope of the region.
17408         if (RSI->CapRegionKind == CR_OpenMP) {
17409           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17410               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17411           // If the variable is private (i.e. not captured) and has variably
17412           // modified type, we still need to capture the type for correct
17413           // codegen in all regions, associated with the construct. Currently,
17414           // it is captured in the innermost captured region only.
17415           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17416               Var->getType()->isVariablyModifiedType()) {
17417             QualType QTy = Var->getType();
17418             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17419               QTy = PVD->getOriginalType();
17420             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17421                  I < E; ++I) {
17422               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17423                   FunctionScopes[FunctionScopesIndex - I]);
17424               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17425                      "Wrong number of captured regions associated with the "
17426                      "OpenMP construct.");
17427               captureVariablyModifiedType(Context, QTy, OuterRSI);
17428             }
17429           }
17430           bool IsTargetCap =
17431               IsOpenMPPrivateDecl != OMPC_private &&
17432               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17433                                          RSI->OpenMPCaptureLevel);
17434           // Do not capture global if it is not privatized in outer regions.
17435           bool IsGlobalCap =
17436               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17437                                                      RSI->OpenMPCaptureLevel);
17438 
17439           // When we detect target captures we are looking from inside the
17440           // target region, therefore we need to propagate the capture from the
17441           // enclosing region. Therefore, the capture is not initially nested.
17442           if (IsTargetCap)
17443             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17444 
17445           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17446               (IsGlobal && !IsGlobalCap)) {
17447             Nested = !IsTargetCap;
17448             DeclRefType = DeclRefType.getUnqualifiedType();
17449             CaptureType = Context.getLValueReferenceType(DeclRefType);
17450             break;
17451           }
17452         }
17453       }
17454     }
17455     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17456       // No capture-default, and this is not an explicit capture
17457       // so cannot capture this variable.
17458       if (BuildAndDiagnose) {
17459         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17460         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17461         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17462           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17463                diag::note_lambda_decl);
17464         // FIXME: If we error out because an outer lambda can not implicitly
17465         // capture a variable that an inner lambda explicitly captures, we
17466         // should have the inner lambda do the explicit capture - because
17467         // it makes for cleaner diagnostics later.  This would purely be done
17468         // so that the diagnostic does not misleadingly claim that a variable
17469         // can not be captured by a lambda implicitly even though it is captured
17470         // explicitly.  Suggestion:
17471         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17472         //    at the function head
17473         //  - cache the StartingDeclContext - this must be a lambda
17474         //  - captureInLambda in the innermost lambda the variable.
17475       }
17476       return true;
17477     }
17478 
17479     FunctionScopesIndex--;
17480     DC = ParentDC;
17481     Explicit = false;
17482   } while (!VarDC->Equals(DC));
17483 
17484   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17485   // computing the type of the capture at each step, checking type-specific
17486   // requirements, and adding captures if requested.
17487   // If the variable had already been captured previously, we start capturing
17488   // at the lambda nested within that one.
17489   bool Invalid = false;
17490   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17491        ++I) {
17492     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17493 
17494     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17495     // certain types of variables (unnamed, variably modified types etc.)
17496     // so check for eligibility.
17497     if (!Invalid)
17498       Invalid =
17499           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17500 
17501     // After encountering an error, if we're actually supposed to capture, keep
17502     // capturing in nested contexts to suppress any follow-on diagnostics.
17503     if (Invalid && !BuildAndDiagnose)
17504       return true;
17505 
17506     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17507       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17508                                DeclRefType, Nested, *this, Invalid);
17509       Nested = true;
17510     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17511       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17512                                          CaptureType, DeclRefType, Nested,
17513                                          *this, Invalid);
17514       Nested = true;
17515     } else {
17516       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17517       Invalid =
17518           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17519                            DeclRefType, Nested, Kind, EllipsisLoc,
17520                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17521       Nested = true;
17522     }
17523 
17524     if (Invalid && !BuildAndDiagnose)
17525       return true;
17526   }
17527   return Invalid;
17528 }
17529 
17530 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17531                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17532   QualType CaptureType;
17533   QualType DeclRefType;
17534   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17535                             /*BuildAndDiagnose=*/true, CaptureType,
17536                             DeclRefType, nullptr);
17537 }
17538 
17539 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17540   QualType CaptureType;
17541   QualType DeclRefType;
17542   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17543                              /*BuildAndDiagnose=*/false, CaptureType,
17544                              DeclRefType, nullptr);
17545 }
17546 
17547 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17548   QualType CaptureType;
17549   QualType DeclRefType;
17550 
17551   // Determine whether we can capture this variable.
17552   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17553                          /*BuildAndDiagnose=*/false, CaptureType,
17554                          DeclRefType, nullptr))
17555     return QualType();
17556 
17557   return DeclRefType;
17558 }
17559 
17560 namespace {
17561 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17562 // The produced TemplateArgumentListInfo* points to data stored within this
17563 // object, so should only be used in contexts where the pointer will not be
17564 // used after the CopiedTemplateArgs object is destroyed.
17565 class CopiedTemplateArgs {
17566   bool HasArgs;
17567   TemplateArgumentListInfo TemplateArgStorage;
17568 public:
17569   template<typename RefExpr>
17570   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17571     if (HasArgs)
17572       E->copyTemplateArgumentsInto(TemplateArgStorage);
17573   }
17574   operator TemplateArgumentListInfo*()
17575 #ifdef __has_cpp_attribute
17576 #if __has_cpp_attribute(clang::lifetimebound)
17577   [[clang::lifetimebound]]
17578 #endif
17579 #endif
17580   {
17581     return HasArgs ? &TemplateArgStorage : nullptr;
17582   }
17583 };
17584 }
17585 
17586 /// Walk the set of potential results of an expression and mark them all as
17587 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17588 ///
17589 /// \return A new expression if we found any potential results, ExprEmpty() if
17590 ///         not, and ExprError() if we diagnosed an error.
17591 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17592                                                       NonOdrUseReason NOUR) {
17593   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17594   // an object that satisfies the requirements for appearing in a
17595   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17596   // is immediately applied."  This function handles the lvalue-to-rvalue
17597   // conversion part.
17598   //
17599   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17600   // transform it into the relevant kind of non-odr-use node and rebuild the
17601   // tree of nodes leading to it.
17602   //
17603   // This is a mini-TreeTransform that only transforms a restricted subset of
17604   // nodes (and only certain operands of them).
17605 
17606   // Rebuild a subexpression.
17607   auto Rebuild = [&](Expr *Sub) {
17608     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17609   };
17610 
17611   // Check whether a potential result satisfies the requirements of NOUR.
17612   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17613     // Any entity other than a VarDecl is always odr-used whenever it's named
17614     // in a potentially-evaluated expression.
17615     auto *VD = dyn_cast<VarDecl>(D);
17616     if (!VD)
17617       return true;
17618 
17619     // C++2a [basic.def.odr]p4:
17620     //   A variable x whose name appears as a potentially-evalauted expression
17621     //   e is odr-used by e unless
17622     //   -- x is a reference that is usable in constant expressions, or
17623     //   -- x is a variable of non-reference type that is usable in constant
17624     //      expressions and has no mutable subobjects, and e is an element of
17625     //      the set of potential results of an expression of
17626     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17627     //      conversion is applied, or
17628     //   -- x is a variable of non-reference type, and e is an element of the
17629     //      set of potential results of a discarded-value expression to which
17630     //      the lvalue-to-rvalue conversion is not applied
17631     //
17632     // We check the first bullet and the "potentially-evaluated" condition in
17633     // BuildDeclRefExpr. We check the type requirements in the second bullet
17634     // in CheckLValueToRValueConversionOperand below.
17635     switch (NOUR) {
17636     case NOUR_None:
17637     case NOUR_Unevaluated:
17638       llvm_unreachable("unexpected non-odr-use-reason");
17639 
17640     case NOUR_Constant:
17641       // Constant references were handled when they were built.
17642       if (VD->getType()->isReferenceType())
17643         return true;
17644       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17645         if (RD->hasMutableFields())
17646           return true;
17647       if (!VD->isUsableInConstantExpressions(S.Context))
17648         return true;
17649       break;
17650 
17651     case NOUR_Discarded:
17652       if (VD->getType()->isReferenceType())
17653         return true;
17654       break;
17655     }
17656     return false;
17657   };
17658 
17659   // Mark that this expression does not constitute an odr-use.
17660   auto MarkNotOdrUsed = [&] {
17661     S.MaybeODRUseExprs.remove(E);
17662     if (LambdaScopeInfo *LSI = S.getCurLambda())
17663       LSI->markVariableExprAsNonODRUsed(E);
17664   };
17665 
17666   // C++2a [basic.def.odr]p2:
17667   //   The set of potential results of an expression e is defined as follows:
17668   switch (E->getStmtClass()) {
17669   //   -- If e is an id-expression, ...
17670   case Expr::DeclRefExprClass: {
17671     auto *DRE = cast<DeclRefExpr>(E);
17672     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17673       break;
17674 
17675     // Rebuild as a non-odr-use DeclRefExpr.
17676     MarkNotOdrUsed();
17677     return DeclRefExpr::Create(
17678         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17679         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17680         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17681         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17682   }
17683 
17684   case Expr::FunctionParmPackExprClass: {
17685     auto *FPPE = cast<FunctionParmPackExpr>(E);
17686     // If any of the declarations in the pack is odr-used, then the expression
17687     // as a whole constitutes an odr-use.
17688     for (VarDecl *D : *FPPE)
17689       if (IsPotentialResultOdrUsed(D))
17690         return ExprEmpty();
17691 
17692     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17693     // nothing cares about whether we marked this as an odr-use, but it might
17694     // be useful for non-compiler tools.
17695     MarkNotOdrUsed();
17696     break;
17697   }
17698 
17699   //   -- If e is a subscripting operation with an array operand...
17700   case Expr::ArraySubscriptExprClass: {
17701     auto *ASE = cast<ArraySubscriptExpr>(E);
17702     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17703     if (!OldBase->getType()->isArrayType())
17704       break;
17705     ExprResult Base = Rebuild(OldBase);
17706     if (!Base.isUsable())
17707       return Base;
17708     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17709     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17710     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17711     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17712                                      ASE->getRBracketLoc());
17713   }
17714 
17715   case Expr::MemberExprClass: {
17716     auto *ME = cast<MemberExpr>(E);
17717     // -- If e is a class member access expression [...] naming a non-static
17718     //    data member...
17719     if (isa<FieldDecl>(ME->getMemberDecl())) {
17720       ExprResult Base = Rebuild(ME->getBase());
17721       if (!Base.isUsable())
17722         return Base;
17723       return MemberExpr::Create(
17724           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17725           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17726           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17727           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17728           ME->getObjectKind(), ME->isNonOdrUse());
17729     }
17730 
17731     if (ME->getMemberDecl()->isCXXInstanceMember())
17732       break;
17733 
17734     // -- If e is a class member access expression naming a static data member,
17735     //    ...
17736     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17737       break;
17738 
17739     // Rebuild as a non-odr-use MemberExpr.
17740     MarkNotOdrUsed();
17741     return MemberExpr::Create(
17742         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17743         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17744         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17745         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17746     return ExprEmpty();
17747   }
17748 
17749   case Expr::BinaryOperatorClass: {
17750     auto *BO = cast<BinaryOperator>(E);
17751     Expr *LHS = BO->getLHS();
17752     Expr *RHS = BO->getRHS();
17753     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17754     if (BO->getOpcode() == BO_PtrMemD) {
17755       ExprResult Sub = Rebuild(LHS);
17756       if (!Sub.isUsable())
17757         return Sub;
17758       LHS = Sub.get();
17759     //   -- If e is a comma expression, ...
17760     } else if (BO->getOpcode() == BO_Comma) {
17761       ExprResult Sub = Rebuild(RHS);
17762       if (!Sub.isUsable())
17763         return Sub;
17764       RHS = Sub.get();
17765     } else {
17766       break;
17767     }
17768     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17769                         LHS, RHS);
17770   }
17771 
17772   //   -- If e has the form (e1)...
17773   case Expr::ParenExprClass: {
17774     auto *PE = cast<ParenExpr>(E);
17775     ExprResult Sub = Rebuild(PE->getSubExpr());
17776     if (!Sub.isUsable())
17777       return Sub;
17778     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17779   }
17780 
17781   //   -- If e is a glvalue conditional expression, ...
17782   // We don't apply this to a binary conditional operator. FIXME: Should we?
17783   case Expr::ConditionalOperatorClass: {
17784     auto *CO = cast<ConditionalOperator>(E);
17785     ExprResult LHS = Rebuild(CO->getLHS());
17786     if (LHS.isInvalid())
17787       return ExprError();
17788     ExprResult RHS = Rebuild(CO->getRHS());
17789     if (RHS.isInvalid())
17790       return ExprError();
17791     if (!LHS.isUsable() && !RHS.isUsable())
17792       return ExprEmpty();
17793     if (!LHS.isUsable())
17794       LHS = CO->getLHS();
17795     if (!RHS.isUsable())
17796       RHS = CO->getRHS();
17797     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17798                                 CO->getCond(), LHS.get(), RHS.get());
17799   }
17800 
17801   // [Clang extension]
17802   //   -- If e has the form __extension__ e1...
17803   case Expr::UnaryOperatorClass: {
17804     auto *UO = cast<UnaryOperator>(E);
17805     if (UO->getOpcode() != UO_Extension)
17806       break;
17807     ExprResult Sub = Rebuild(UO->getSubExpr());
17808     if (!Sub.isUsable())
17809       return Sub;
17810     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17811                           Sub.get());
17812   }
17813 
17814   // [Clang extension]
17815   //   -- If e has the form _Generic(...), the set of potential results is the
17816   //      union of the sets of potential results of the associated expressions.
17817   case Expr::GenericSelectionExprClass: {
17818     auto *GSE = cast<GenericSelectionExpr>(E);
17819 
17820     SmallVector<Expr *, 4> AssocExprs;
17821     bool AnyChanged = false;
17822     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17823       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17824       if (AssocExpr.isInvalid())
17825         return ExprError();
17826       if (AssocExpr.isUsable()) {
17827         AssocExprs.push_back(AssocExpr.get());
17828         AnyChanged = true;
17829       } else {
17830         AssocExprs.push_back(OrigAssocExpr);
17831       }
17832     }
17833 
17834     return AnyChanged ? S.CreateGenericSelectionExpr(
17835                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17836                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17837                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17838                       : ExprEmpty();
17839   }
17840 
17841   // [Clang extension]
17842   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17843   //      results is the union of the sets of potential results of the
17844   //      second and third subexpressions.
17845   case Expr::ChooseExprClass: {
17846     auto *CE = cast<ChooseExpr>(E);
17847 
17848     ExprResult LHS = Rebuild(CE->getLHS());
17849     if (LHS.isInvalid())
17850       return ExprError();
17851 
17852     ExprResult RHS = Rebuild(CE->getLHS());
17853     if (RHS.isInvalid())
17854       return ExprError();
17855 
17856     if (!LHS.get() && !RHS.get())
17857       return ExprEmpty();
17858     if (!LHS.isUsable())
17859       LHS = CE->getLHS();
17860     if (!RHS.isUsable())
17861       RHS = CE->getRHS();
17862 
17863     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17864                              RHS.get(), CE->getRParenLoc());
17865   }
17866 
17867   // Step through non-syntactic nodes.
17868   case Expr::ConstantExprClass: {
17869     auto *CE = cast<ConstantExpr>(E);
17870     ExprResult Sub = Rebuild(CE->getSubExpr());
17871     if (!Sub.isUsable())
17872       return Sub;
17873     return ConstantExpr::Create(S.Context, Sub.get());
17874   }
17875 
17876   // We could mostly rely on the recursive rebuilding to rebuild implicit
17877   // casts, but not at the top level, so rebuild them here.
17878   case Expr::ImplicitCastExprClass: {
17879     auto *ICE = cast<ImplicitCastExpr>(E);
17880     // Only step through the narrow set of cast kinds we expect to encounter.
17881     // Anything else suggests we've left the region in which potential results
17882     // can be found.
17883     switch (ICE->getCastKind()) {
17884     case CK_NoOp:
17885     case CK_DerivedToBase:
17886     case CK_UncheckedDerivedToBase: {
17887       ExprResult Sub = Rebuild(ICE->getSubExpr());
17888       if (!Sub.isUsable())
17889         return Sub;
17890       CXXCastPath Path(ICE->path());
17891       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17892                                  ICE->getValueKind(), &Path);
17893     }
17894 
17895     default:
17896       break;
17897     }
17898     break;
17899   }
17900 
17901   default:
17902     break;
17903   }
17904 
17905   // Can't traverse through this node. Nothing to do.
17906   return ExprEmpty();
17907 }
17908 
17909 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17910   // Check whether the operand is or contains an object of non-trivial C union
17911   // type.
17912   if (E->getType().isVolatileQualified() &&
17913       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17914        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17915     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17916                           Sema::NTCUC_LValueToRValueVolatile,
17917                           NTCUK_Destruct|NTCUK_Copy);
17918 
17919   // C++2a [basic.def.odr]p4:
17920   //   [...] an expression of non-volatile-qualified non-class type to which
17921   //   the lvalue-to-rvalue conversion is applied [...]
17922   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17923     return E;
17924 
17925   ExprResult Result =
17926       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17927   if (Result.isInvalid())
17928     return ExprError();
17929   return Result.get() ? Result : E;
17930 }
17931 
17932 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17933   Res = CorrectDelayedTyposInExpr(Res);
17934 
17935   if (!Res.isUsable())
17936     return Res;
17937 
17938   // If a constant-expression is a reference to a variable where we delay
17939   // deciding whether it is an odr-use, just assume we will apply the
17940   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
17941   // (a non-type template argument), we have special handling anyway.
17942   return CheckLValueToRValueConversionOperand(Res.get());
17943 }
17944 
17945 void Sema::CleanupVarDeclMarking() {
17946   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17947   // call.
17948   MaybeODRUseExprSet LocalMaybeODRUseExprs;
17949   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17950 
17951   for (Expr *E : LocalMaybeODRUseExprs) {
17952     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17953       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17954                          DRE->getLocation(), *this);
17955     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17956       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17957                          *this);
17958     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17959       for (VarDecl *VD : *FP)
17960         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17961     } else {
17962       llvm_unreachable("Unexpected expression");
17963     }
17964   }
17965 
17966   assert(MaybeODRUseExprs.empty() &&
17967          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17968 }
17969 
17970 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17971                                     VarDecl *Var, Expr *E) {
17972   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
17973           isa<FunctionParmPackExpr>(E)) &&
17974          "Invalid Expr argument to DoMarkVarDeclReferenced");
17975   Var->setReferenced();
17976 
17977   if (Var->isInvalidDecl())
17978     return;
17979 
17980   // Record a CUDA/HIP static device/constant variable if it is referenced
17981   // by host code. This is done conservatively, when the variable is referenced
17982   // in any of the following contexts:
17983   //   - a non-function context
17984   //   - a host function
17985   //   - a host device function
17986   // This also requires the reference of the static device/constant variable by
17987   // host code to be visible in the device compilation for the compiler to be
17988   // able to externalize the static device/constant variable.
17989   if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) {
17990     auto *CurContext = SemaRef.CurContext;
17991     if (!CurContext || !isa<FunctionDecl>(CurContext) ||
17992         cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() ||
17993         (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() &&
17994          !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>()))
17995       SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var);
17996   }
17997 
17998   auto *MSI = Var->getMemberSpecializationInfo();
17999   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18000                                        : Var->getTemplateSpecializationKind();
18001 
18002   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18003   bool UsableInConstantExpr =
18004       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18005 
18006   // C++20 [expr.const]p12:
18007   //   A variable [...] is needed for constant evaluation if it is [...] a
18008   //   variable whose name appears as a potentially constant evaluated
18009   //   expression that is either a contexpr variable or is of non-volatile
18010   //   const-qualified integral type or of reference type
18011   bool NeededForConstantEvaluation =
18012       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18013 
18014   bool NeedDefinition =
18015       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18016 
18017   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
18018          "Can't instantiate a partial template specialization.");
18019 
18020   // If this might be a member specialization of a static data member, check
18021   // the specialization is visible. We already did the checks for variable
18022   // template specializations when we created them.
18023   if (NeedDefinition && TSK != TSK_Undeclared &&
18024       !isa<VarTemplateSpecializationDecl>(Var))
18025     SemaRef.checkSpecializationVisibility(Loc, Var);
18026 
18027   // Perform implicit instantiation of static data members, static data member
18028   // templates of class templates, and variable template specializations. Delay
18029   // instantiations of variable templates, except for those that could be used
18030   // in a constant expression.
18031   if (NeedDefinition && isTemplateInstantiation(TSK)) {
18032     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18033     // instantiation declaration if a variable is usable in a constant
18034     // expression (among other cases).
18035     bool TryInstantiating =
18036         TSK == TSK_ImplicitInstantiation ||
18037         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18038 
18039     if (TryInstantiating) {
18040       SourceLocation PointOfInstantiation =
18041           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18042       bool FirstInstantiation = PointOfInstantiation.isInvalid();
18043       if (FirstInstantiation) {
18044         PointOfInstantiation = Loc;
18045         if (MSI)
18046           MSI->setPointOfInstantiation(PointOfInstantiation);
18047           // FIXME: Notify listener.
18048         else
18049           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18050       }
18051 
18052       if (UsableInConstantExpr) {
18053         // Do not defer instantiations of variables that could be used in a
18054         // constant expression.
18055         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18056           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18057         });
18058       } else if (FirstInstantiation ||
18059                  isa<VarTemplateSpecializationDecl>(Var)) {
18060         // FIXME: For a specialization of a variable template, we don't
18061         // distinguish between "declaration and type implicitly instantiated"
18062         // and "implicit instantiation of definition requested", so we have
18063         // no direct way to avoid enqueueing the pending instantiation
18064         // multiple times.
18065         SemaRef.PendingInstantiations
18066             .push_back(std::make_pair(Var, PointOfInstantiation));
18067       }
18068     }
18069   }
18070 
18071   // C++2a [basic.def.odr]p4:
18072   //   A variable x whose name appears as a potentially-evaluated expression e
18073   //   is odr-used by e unless
18074   //   -- x is a reference that is usable in constant expressions
18075   //   -- x is a variable of non-reference type that is usable in constant
18076   //      expressions and has no mutable subobjects [FIXME], and e is an
18077   //      element of the set of potential results of an expression of
18078   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18079   //      conversion is applied
18080   //   -- x is a variable of non-reference type, and e is an element of the set
18081   //      of potential results of a discarded-value expression to which the
18082   //      lvalue-to-rvalue conversion is not applied [FIXME]
18083   //
18084   // We check the first part of the second bullet here, and
18085   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18086   // FIXME: To get the third bullet right, we need to delay this even for
18087   // variables that are not usable in constant expressions.
18088 
18089   // If we already know this isn't an odr-use, there's nothing more to do.
18090   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18091     if (DRE->isNonOdrUse())
18092       return;
18093   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18094     if (ME->isNonOdrUse())
18095       return;
18096 
18097   switch (OdrUse) {
18098   case OdrUseContext::None:
18099     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18100            "missing non-odr-use marking for unevaluated decl ref");
18101     break;
18102 
18103   case OdrUseContext::FormallyOdrUsed:
18104     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18105     // behavior.
18106     break;
18107 
18108   case OdrUseContext::Used:
18109     // If we might later find that this expression isn't actually an odr-use,
18110     // delay the marking.
18111     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18112       SemaRef.MaybeODRUseExprs.insert(E);
18113     else
18114       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18115     break;
18116 
18117   case OdrUseContext::Dependent:
18118     // If this is a dependent context, we don't need to mark variables as
18119     // odr-used, but we may still need to track them for lambda capture.
18120     // FIXME: Do we also need to do this inside dependent typeid expressions
18121     // (which are modeled as unevaluated at this point)?
18122     const bool RefersToEnclosingScope =
18123         (SemaRef.CurContext != Var->getDeclContext() &&
18124          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18125     if (RefersToEnclosingScope) {
18126       LambdaScopeInfo *const LSI =
18127           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18128       if (LSI && (!LSI->CallOperator ||
18129                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18130         // If a variable could potentially be odr-used, defer marking it so
18131         // until we finish analyzing the full expression for any
18132         // lvalue-to-rvalue
18133         // or discarded value conversions that would obviate odr-use.
18134         // Add it to the list of potential captures that will be analyzed
18135         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18136         // unless the variable is a reference that was initialized by a constant
18137         // expression (this will never need to be captured or odr-used).
18138         //
18139         // FIXME: We can simplify this a lot after implementing P0588R1.
18140         assert(E && "Capture variable should be used in an expression.");
18141         if (!Var->getType()->isReferenceType() ||
18142             !Var->isUsableInConstantExpressions(SemaRef.Context))
18143           LSI->addPotentialCapture(E->IgnoreParens());
18144       }
18145     }
18146     break;
18147   }
18148 }
18149 
18150 /// Mark a variable referenced, and check whether it is odr-used
18151 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18152 /// used directly for normal expressions referring to VarDecl.
18153 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18154   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18155 }
18156 
18157 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18158                                Decl *D, Expr *E, bool MightBeOdrUse) {
18159   if (SemaRef.isInOpenMPDeclareTargetContext())
18160     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18161 
18162   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18163     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18164     return;
18165   }
18166 
18167   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18168 
18169   // If this is a call to a method via a cast, also mark the method in the
18170   // derived class used in case codegen can devirtualize the call.
18171   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18172   if (!ME)
18173     return;
18174   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18175   if (!MD)
18176     return;
18177   // Only attempt to devirtualize if this is truly a virtual call.
18178   bool IsVirtualCall = MD->isVirtual() &&
18179                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18180   if (!IsVirtualCall)
18181     return;
18182 
18183   // If it's possible to devirtualize the call, mark the called function
18184   // referenced.
18185   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18186       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18187   if (DM)
18188     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18189 }
18190 
18191 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18192 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18193   // TODO: update this with DR# once a defect report is filed.
18194   // C++11 defect. The address of a pure member should not be an ODR use, even
18195   // if it's a qualified reference.
18196   bool OdrUse = true;
18197   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18198     if (Method->isVirtual() &&
18199         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18200       OdrUse = false;
18201 
18202   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18203     if (!isConstantEvaluated() && FD->isConsteval() &&
18204         !RebuildingImmediateInvocation)
18205       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18206   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18207 }
18208 
18209 /// Perform reference-marking and odr-use handling for a MemberExpr.
18210 void Sema::MarkMemberReferenced(MemberExpr *E) {
18211   // C++11 [basic.def.odr]p2:
18212   //   A non-overloaded function whose name appears as a potentially-evaluated
18213   //   expression or a member of a set of candidate functions, if selected by
18214   //   overload resolution when referred to from a potentially-evaluated
18215   //   expression, is odr-used, unless it is a pure virtual function and its
18216   //   name is not explicitly qualified.
18217   bool MightBeOdrUse = true;
18218   if (E->performsVirtualDispatch(getLangOpts())) {
18219     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18220       if (Method->isPure())
18221         MightBeOdrUse = false;
18222   }
18223   SourceLocation Loc =
18224       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18225   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18226 }
18227 
18228 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18229 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18230   for (VarDecl *VD : *E)
18231     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18232 }
18233 
18234 /// Perform marking for a reference to an arbitrary declaration.  It
18235 /// marks the declaration referenced, and performs odr-use checking for
18236 /// functions and variables. This method should not be used when building a
18237 /// normal expression which refers to a variable.
18238 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18239                                  bool MightBeOdrUse) {
18240   if (MightBeOdrUse) {
18241     if (auto *VD = dyn_cast<VarDecl>(D)) {
18242       MarkVariableReferenced(Loc, VD);
18243       return;
18244     }
18245   }
18246   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18247     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18248     return;
18249   }
18250   D->setReferenced();
18251 }
18252 
18253 namespace {
18254   // Mark all of the declarations used by a type as referenced.
18255   // FIXME: Not fully implemented yet! We need to have a better understanding
18256   // of when we're entering a context we should not recurse into.
18257   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18258   // TreeTransforms rebuilding the type in a new context. Rather than
18259   // duplicating the TreeTransform logic, we should consider reusing it here.
18260   // Currently that causes problems when rebuilding LambdaExprs.
18261   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18262     Sema &S;
18263     SourceLocation Loc;
18264 
18265   public:
18266     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18267 
18268     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18269 
18270     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18271   };
18272 }
18273 
18274 bool MarkReferencedDecls::TraverseTemplateArgument(
18275     const TemplateArgument &Arg) {
18276   {
18277     // A non-type template argument is a constant-evaluated context.
18278     EnterExpressionEvaluationContext Evaluated(
18279         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18280     if (Arg.getKind() == TemplateArgument::Declaration) {
18281       if (Decl *D = Arg.getAsDecl())
18282         S.MarkAnyDeclReferenced(Loc, D, true);
18283     } else if (Arg.getKind() == TemplateArgument::Expression) {
18284       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18285     }
18286   }
18287 
18288   return Inherited::TraverseTemplateArgument(Arg);
18289 }
18290 
18291 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18292   MarkReferencedDecls Marker(*this, Loc);
18293   Marker.TraverseType(T);
18294 }
18295 
18296 namespace {
18297 /// Helper class that marks all of the declarations referenced by
18298 /// potentially-evaluated subexpressions as "referenced".
18299 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18300 public:
18301   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18302   bool SkipLocalVariables;
18303 
18304   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18305       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18306 
18307   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18308     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18309   }
18310 
18311   void VisitDeclRefExpr(DeclRefExpr *E) {
18312     // If we were asked not to visit local variables, don't.
18313     if (SkipLocalVariables) {
18314       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18315         if (VD->hasLocalStorage())
18316           return;
18317     }
18318     S.MarkDeclRefReferenced(E);
18319   }
18320 
18321   void VisitMemberExpr(MemberExpr *E) {
18322     S.MarkMemberReferenced(E);
18323     Visit(E->getBase());
18324   }
18325 };
18326 } // namespace
18327 
18328 /// Mark any declarations that appear within this expression or any
18329 /// potentially-evaluated subexpressions as "referenced".
18330 ///
18331 /// \param SkipLocalVariables If true, don't mark local variables as
18332 /// 'referenced'.
18333 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18334                                             bool SkipLocalVariables) {
18335   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18336 }
18337 
18338 /// Emit a diagnostic that describes an effect on the run-time behavior
18339 /// of the program being compiled.
18340 ///
18341 /// This routine emits the given diagnostic when the code currently being
18342 /// type-checked is "potentially evaluated", meaning that there is a
18343 /// possibility that the code will actually be executable. Code in sizeof()
18344 /// expressions, code used only during overload resolution, etc., are not
18345 /// potentially evaluated. This routine will suppress such diagnostics or,
18346 /// in the absolutely nutty case of potentially potentially evaluated
18347 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18348 /// later.
18349 ///
18350 /// This routine should be used for all diagnostics that describe the run-time
18351 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18352 /// Failure to do so will likely result in spurious diagnostics or failures
18353 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18354 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18355                                const PartialDiagnostic &PD) {
18356   switch (ExprEvalContexts.back().Context) {
18357   case ExpressionEvaluationContext::Unevaluated:
18358   case ExpressionEvaluationContext::UnevaluatedList:
18359   case ExpressionEvaluationContext::UnevaluatedAbstract:
18360   case ExpressionEvaluationContext::DiscardedStatement:
18361     // The argument will never be evaluated, so don't complain.
18362     break;
18363 
18364   case ExpressionEvaluationContext::ConstantEvaluated:
18365     // Relevant diagnostics should be produced by constant evaluation.
18366     break;
18367 
18368   case ExpressionEvaluationContext::PotentiallyEvaluated:
18369   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18370     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18371       FunctionScopes.back()->PossiblyUnreachableDiags.
18372         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18373       return true;
18374     }
18375 
18376     // The initializer of a constexpr variable or of the first declaration of a
18377     // static data member is not syntactically a constant evaluated constant,
18378     // but nonetheless is always required to be a constant expression, so we
18379     // can skip diagnosing.
18380     // FIXME: Using the mangling context here is a hack.
18381     if (auto *VD = dyn_cast_or_null<VarDecl>(
18382             ExprEvalContexts.back().ManglingContextDecl)) {
18383       if (VD->isConstexpr() ||
18384           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18385         break;
18386       // FIXME: For any other kind of variable, we should build a CFG for its
18387       // initializer and check whether the context in question is reachable.
18388     }
18389 
18390     Diag(Loc, PD);
18391     return true;
18392   }
18393 
18394   return false;
18395 }
18396 
18397 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18398                                const PartialDiagnostic &PD) {
18399   return DiagRuntimeBehavior(
18400       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18401 }
18402 
18403 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18404                                CallExpr *CE, FunctionDecl *FD) {
18405   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18406     return false;
18407 
18408   // If we're inside a decltype's expression, don't check for a valid return
18409   // type or construct temporaries until we know whether this is the last call.
18410   if (ExprEvalContexts.back().ExprContext ==
18411       ExpressionEvaluationContextRecord::EK_Decltype) {
18412     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18413     return false;
18414   }
18415 
18416   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18417     FunctionDecl *FD;
18418     CallExpr *CE;
18419 
18420   public:
18421     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18422       : FD(FD), CE(CE) { }
18423 
18424     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18425       if (!FD) {
18426         S.Diag(Loc, diag::err_call_incomplete_return)
18427           << T << CE->getSourceRange();
18428         return;
18429       }
18430 
18431       S.Diag(Loc, diag::err_call_function_incomplete_return)
18432           << CE->getSourceRange() << FD << T;
18433       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18434           << FD->getDeclName();
18435     }
18436   } Diagnoser(FD, CE);
18437 
18438   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18439     return true;
18440 
18441   return false;
18442 }
18443 
18444 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18445 // will prevent this condition from triggering, which is what we want.
18446 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18447   SourceLocation Loc;
18448 
18449   unsigned diagnostic = diag::warn_condition_is_assignment;
18450   bool IsOrAssign = false;
18451 
18452   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18453     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18454       return;
18455 
18456     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18457 
18458     // Greylist some idioms by putting them into a warning subcategory.
18459     if (ObjCMessageExpr *ME
18460           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18461       Selector Sel = ME->getSelector();
18462 
18463       // self = [<foo> init...]
18464       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18465         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18466 
18467       // <foo> = [<bar> nextObject]
18468       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18469         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18470     }
18471 
18472     Loc = Op->getOperatorLoc();
18473   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18474     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18475       return;
18476 
18477     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18478     Loc = Op->getOperatorLoc();
18479   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18480     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18481   else {
18482     // Not an assignment.
18483     return;
18484   }
18485 
18486   Diag(Loc, diagnostic) << E->getSourceRange();
18487 
18488   SourceLocation Open = E->getBeginLoc();
18489   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18490   Diag(Loc, diag::note_condition_assign_silence)
18491         << FixItHint::CreateInsertion(Open, "(")
18492         << FixItHint::CreateInsertion(Close, ")");
18493 
18494   if (IsOrAssign)
18495     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18496       << FixItHint::CreateReplacement(Loc, "!=");
18497   else
18498     Diag(Loc, diag::note_condition_assign_to_comparison)
18499       << FixItHint::CreateReplacement(Loc, "==");
18500 }
18501 
18502 /// Redundant parentheses over an equality comparison can indicate
18503 /// that the user intended an assignment used as condition.
18504 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18505   // Don't warn if the parens came from a macro.
18506   SourceLocation parenLoc = ParenE->getBeginLoc();
18507   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18508     return;
18509   // Don't warn for dependent expressions.
18510   if (ParenE->isTypeDependent())
18511     return;
18512 
18513   Expr *E = ParenE->IgnoreParens();
18514 
18515   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18516     if (opE->getOpcode() == BO_EQ &&
18517         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18518                                                            == Expr::MLV_Valid) {
18519       SourceLocation Loc = opE->getOperatorLoc();
18520 
18521       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18522       SourceRange ParenERange = ParenE->getSourceRange();
18523       Diag(Loc, diag::note_equality_comparison_silence)
18524         << FixItHint::CreateRemoval(ParenERange.getBegin())
18525         << FixItHint::CreateRemoval(ParenERange.getEnd());
18526       Diag(Loc, diag::note_equality_comparison_to_assign)
18527         << FixItHint::CreateReplacement(Loc, "=");
18528     }
18529 }
18530 
18531 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18532                                        bool IsConstexpr) {
18533   DiagnoseAssignmentAsCondition(E);
18534   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18535     DiagnoseEqualityWithExtraParens(parenE);
18536 
18537   ExprResult result = CheckPlaceholderExpr(E);
18538   if (result.isInvalid()) return ExprError();
18539   E = result.get();
18540 
18541   if (!E->isTypeDependent()) {
18542     if (getLangOpts().CPlusPlus)
18543       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18544 
18545     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18546     if (ERes.isInvalid())
18547       return ExprError();
18548     E = ERes.get();
18549 
18550     QualType T = E->getType();
18551     if (!T->isScalarType()) { // C99 6.8.4.1p1
18552       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18553         << T << E->getSourceRange();
18554       return ExprError();
18555     }
18556     CheckBoolLikeConversion(E, Loc);
18557   }
18558 
18559   return E;
18560 }
18561 
18562 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18563                                            Expr *SubExpr, ConditionKind CK) {
18564   // Empty conditions are valid in for-statements.
18565   if (!SubExpr)
18566     return ConditionResult();
18567 
18568   ExprResult Cond;
18569   switch (CK) {
18570   case ConditionKind::Boolean:
18571     Cond = CheckBooleanCondition(Loc, SubExpr);
18572     break;
18573 
18574   case ConditionKind::ConstexprIf:
18575     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18576     break;
18577 
18578   case ConditionKind::Switch:
18579     Cond = CheckSwitchCondition(Loc, SubExpr);
18580     break;
18581   }
18582   if (Cond.isInvalid()) {
18583     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
18584                               {SubExpr});
18585     if (!Cond.get())
18586       return ConditionError();
18587   }
18588   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18589   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18590   if (!FullExpr.get())
18591     return ConditionError();
18592 
18593   return ConditionResult(*this, nullptr, FullExpr,
18594                          CK == ConditionKind::ConstexprIf);
18595 }
18596 
18597 namespace {
18598   /// A visitor for rebuilding a call to an __unknown_any expression
18599   /// to have an appropriate type.
18600   struct RebuildUnknownAnyFunction
18601     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18602 
18603     Sema &S;
18604 
18605     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18606 
18607     ExprResult VisitStmt(Stmt *S) {
18608       llvm_unreachable("unexpected statement!");
18609     }
18610 
18611     ExprResult VisitExpr(Expr *E) {
18612       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18613         << E->getSourceRange();
18614       return ExprError();
18615     }
18616 
18617     /// Rebuild an expression which simply semantically wraps another
18618     /// expression which it shares the type and value kind of.
18619     template <class T> ExprResult rebuildSugarExpr(T *E) {
18620       ExprResult SubResult = Visit(E->getSubExpr());
18621       if (SubResult.isInvalid()) return ExprError();
18622 
18623       Expr *SubExpr = SubResult.get();
18624       E->setSubExpr(SubExpr);
18625       E->setType(SubExpr->getType());
18626       E->setValueKind(SubExpr->getValueKind());
18627       assert(E->getObjectKind() == OK_Ordinary);
18628       return E;
18629     }
18630 
18631     ExprResult VisitParenExpr(ParenExpr *E) {
18632       return rebuildSugarExpr(E);
18633     }
18634 
18635     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18636       return rebuildSugarExpr(E);
18637     }
18638 
18639     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18640       ExprResult SubResult = Visit(E->getSubExpr());
18641       if (SubResult.isInvalid()) return ExprError();
18642 
18643       Expr *SubExpr = SubResult.get();
18644       E->setSubExpr(SubExpr);
18645       E->setType(S.Context.getPointerType(SubExpr->getType()));
18646       assert(E->getValueKind() == VK_RValue);
18647       assert(E->getObjectKind() == OK_Ordinary);
18648       return E;
18649     }
18650 
18651     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18652       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18653 
18654       E->setType(VD->getType());
18655 
18656       assert(E->getValueKind() == VK_RValue);
18657       if (S.getLangOpts().CPlusPlus &&
18658           !(isa<CXXMethodDecl>(VD) &&
18659             cast<CXXMethodDecl>(VD)->isInstance()))
18660         E->setValueKind(VK_LValue);
18661 
18662       return E;
18663     }
18664 
18665     ExprResult VisitMemberExpr(MemberExpr *E) {
18666       return resolveDecl(E, E->getMemberDecl());
18667     }
18668 
18669     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18670       return resolveDecl(E, E->getDecl());
18671     }
18672   };
18673 }
18674 
18675 /// Given a function expression of unknown-any type, try to rebuild it
18676 /// to have a function type.
18677 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18678   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18679   if (Result.isInvalid()) return ExprError();
18680   return S.DefaultFunctionArrayConversion(Result.get());
18681 }
18682 
18683 namespace {
18684   /// A visitor for rebuilding an expression of type __unknown_anytype
18685   /// into one which resolves the type directly on the referring
18686   /// expression.  Strict preservation of the original source
18687   /// structure is not a goal.
18688   struct RebuildUnknownAnyExpr
18689     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18690 
18691     Sema &S;
18692 
18693     /// The current destination type.
18694     QualType DestType;
18695 
18696     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18697       : S(S), DestType(CastType) {}
18698 
18699     ExprResult VisitStmt(Stmt *S) {
18700       llvm_unreachable("unexpected statement!");
18701     }
18702 
18703     ExprResult VisitExpr(Expr *E) {
18704       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18705         << E->getSourceRange();
18706       return ExprError();
18707     }
18708 
18709     ExprResult VisitCallExpr(CallExpr *E);
18710     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18711 
18712     /// Rebuild an expression which simply semantically wraps another
18713     /// expression which it shares the type and value kind of.
18714     template <class T> ExprResult rebuildSugarExpr(T *E) {
18715       ExprResult SubResult = Visit(E->getSubExpr());
18716       if (SubResult.isInvalid()) return ExprError();
18717       Expr *SubExpr = SubResult.get();
18718       E->setSubExpr(SubExpr);
18719       E->setType(SubExpr->getType());
18720       E->setValueKind(SubExpr->getValueKind());
18721       assert(E->getObjectKind() == OK_Ordinary);
18722       return E;
18723     }
18724 
18725     ExprResult VisitParenExpr(ParenExpr *E) {
18726       return rebuildSugarExpr(E);
18727     }
18728 
18729     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18730       return rebuildSugarExpr(E);
18731     }
18732 
18733     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18734       const PointerType *Ptr = DestType->getAs<PointerType>();
18735       if (!Ptr) {
18736         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18737           << E->getSourceRange();
18738         return ExprError();
18739       }
18740 
18741       if (isa<CallExpr>(E->getSubExpr())) {
18742         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18743           << E->getSourceRange();
18744         return ExprError();
18745       }
18746 
18747       assert(E->getValueKind() == VK_RValue);
18748       assert(E->getObjectKind() == OK_Ordinary);
18749       E->setType(DestType);
18750 
18751       // Build the sub-expression as if it were an object of the pointee type.
18752       DestType = Ptr->getPointeeType();
18753       ExprResult SubResult = Visit(E->getSubExpr());
18754       if (SubResult.isInvalid()) return ExprError();
18755       E->setSubExpr(SubResult.get());
18756       return E;
18757     }
18758 
18759     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18760 
18761     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18762 
18763     ExprResult VisitMemberExpr(MemberExpr *E) {
18764       return resolveDecl(E, E->getMemberDecl());
18765     }
18766 
18767     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18768       return resolveDecl(E, E->getDecl());
18769     }
18770   };
18771 }
18772 
18773 /// Rebuilds a call expression which yielded __unknown_anytype.
18774 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18775   Expr *CalleeExpr = E->getCallee();
18776 
18777   enum FnKind {
18778     FK_MemberFunction,
18779     FK_FunctionPointer,
18780     FK_BlockPointer
18781   };
18782 
18783   FnKind Kind;
18784   QualType CalleeType = CalleeExpr->getType();
18785   if (CalleeType == S.Context.BoundMemberTy) {
18786     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18787     Kind = FK_MemberFunction;
18788     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18789   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18790     CalleeType = Ptr->getPointeeType();
18791     Kind = FK_FunctionPointer;
18792   } else {
18793     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18794     Kind = FK_BlockPointer;
18795   }
18796   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18797 
18798   // Verify that this is a legal result type of a function.
18799   if (DestType->isArrayType() || DestType->isFunctionType()) {
18800     unsigned diagID = diag::err_func_returning_array_function;
18801     if (Kind == FK_BlockPointer)
18802       diagID = diag::err_block_returning_array_function;
18803 
18804     S.Diag(E->getExprLoc(), diagID)
18805       << DestType->isFunctionType() << DestType;
18806     return ExprError();
18807   }
18808 
18809   // Otherwise, go ahead and set DestType as the call's result.
18810   E->setType(DestType.getNonLValueExprType(S.Context));
18811   E->setValueKind(Expr::getValueKindForType(DestType));
18812   assert(E->getObjectKind() == OK_Ordinary);
18813 
18814   // Rebuild the function type, replacing the result type with DestType.
18815   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18816   if (Proto) {
18817     // __unknown_anytype(...) is a special case used by the debugger when
18818     // it has no idea what a function's signature is.
18819     //
18820     // We want to build this call essentially under the K&R
18821     // unprototyped rules, but making a FunctionNoProtoType in C++
18822     // would foul up all sorts of assumptions.  However, we cannot
18823     // simply pass all arguments as variadic arguments, nor can we
18824     // portably just call the function under a non-variadic type; see
18825     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18826     // However, it turns out that in practice it is generally safe to
18827     // call a function declared as "A foo(B,C,D);" under the prototype
18828     // "A foo(B,C,D,...);".  The only known exception is with the
18829     // Windows ABI, where any variadic function is implicitly cdecl
18830     // regardless of its normal CC.  Therefore we change the parameter
18831     // types to match the types of the arguments.
18832     //
18833     // This is a hack, but it is far superior to moving the
18834     // corresponding target-specific code from IR-gen to Sema/AST.
18835 
18836     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18837     SmallVector<QualType, 8> ArgTypes;
18838     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18839       ArgTypes.reserve(E->getNumArgs());
18840       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18841         Expr *Arg = E->getArg(i);
18842         QualType ArgType = Arg->getType();
18843         if (E->isLValue()) {
18844           ArgType = S.Context.getLValueReferenceType(ArgType);
18845         } else if (E->isXValue()) {
18846           ArgType = S.Context.getRValueReferenceType(ArgType);
18847         }
18848         ArgTypes.push_back(ArgType);
18849       }
18850       ParamTypes = ArgTypes;
18851     }
18852     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18853                                          Proto->getExtProtoInfo());
18854   } else {
18855     DestType = S.Context.getFunctionNoProtoType(DestType,
18856                                                 FnType->getExtInfo());
18857   }
18858 
18859   // Rebuild the appropriate pointer-to-function type.
18860   switch (Kind) {
18861   case FK_MemberFunction:
18862     // Nothing to do.
18863     break;
18864 
18865   case FK_FunctionPointer:
18866     DestType = S.Context.getPointerType(DestType);
18867     break;
18868 
18869   case FK_BlockPointer:
18870     DestType = S.Context.getBlockPointerType(DestType);
18871     break;
18872   }
18873 
18874   // Finally, we can recurse.
18875   ExprResult CalleeResult = Visit(CalleeExpr);
18876   if (!CalleeResult.isUsable()) return ExprError();
18877   E->setCallee(CalleeResult.get());
18878 
18879   // Bind a temporary if necessary.
18880   return S.MaybeBindToTemporary(E);
18881 }
18882 
18883 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18884   // Verify that this is a legal result type of a call.
18885   if (DestType->isArrayType() || DestType->isFunctionType()) {
18886     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18887       << DestType->isFunctionType() << DestType;
18888     return ExprError();
18889   }
18890 
18891   // Rewrite the method result type if available.
18892   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18893     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18894     Method->setReturnType(DestType);
18895   }
18896 
18897   // Change the type of the message.
18898   E->setType(DestType.getNonReferenceType());
18899   E->setValueKind(Expr::getValueKindForType(DestType));
18900 
18901   return S.MaybeBindToTemporary(E);
18902 }
18903 
18904 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18905   // The only case we should ever see here is a function-to-pointer decay.
18906   if (E->getCastKind() == CK_FunctionToPointerDecay) {
18907     assert(E->getValueKind() == VK_RValue);
18908     assert(E->getObjectKind() == OK_Ordinary);
18909 
18910     E->setType(DestType);
18911 
18912     // Rebuild the sub-expression as the pointee (function) type.
18913     DestType = DestType->castAs<PointerType>()->getPointeeType();
18914 
18915     ExprResult Result = Visit(E->getSubExpr());
18916     if (!Result.isUsable()) return ExprError();
18917 
18918     E->setSubExpr(Result.get());
18919     return E;
18920   } else if (E->getCastKind() == CK_LValueToRValue) {
18921     assert(E->getValueKind() == VK_RValue);
18922     assert(E->getObjectKind() == OK_Ordinary);
18923 
18924     assert(isa<BlockPointerType>(E->getType()));
18925 
18926     E->setType(DestType);
18927 
18928     // The sub-expression has to be a lvalue reference, so rebuild it as such.
18929     DestType = S.Context.getLValueReferenceType(DestType);
18930 
18931     ExprResult Result = Visit(E->getSubExpr());
18932     if (!Result.isUsable()) return ExprError();
18933 
18934     E->setSubExpr(Result.get());
18935     return E;
18936   } else {
18937     llvm_unreachable("Unhandled cast type!");
18938   }
18939 }
18940 
18941 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18942   ExprValueKind ValueKind = VK_LValue;
18943   QualType Type = DestType;
18944 
18945   // We know how to make this work for certain kinds of decls:
18946 
18947   //  - functions
18948   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18949     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18950       DestType = Ptr->getPointeeType();
18951       ExprResult Result = resolveDecl(E, VD);
18952       if (Result.isInvalid()) return ExprError();
18953       return S.ImpCastExprToType(Result.get(), Type,
18954                                  CK_FunctionToPointerDecay, VK_RValue);
18955     }
18956 
18957     if (!Type->isFunctionType()) {
18958       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18959         << VD << E->getSourceRange();
18960       return ExprError();
18961     }
18962     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18963       // We must match the FunctionDecl's type to the hack introduced in
18964       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18965       // type. See the lengthy commentary in that routine.
18966       QualType FDT = FD->getType();
18967       const FunctionType *FnType = FDT->castAs<FunctionType>();
18968       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18969       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18970       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18971         SourceLocation Loc = FD->getLocation();
18972         FunctionDecl *NewFD = FunctionDecl::Create(
18973             S.Context, FD->getDeclContext(), Loc, Loc,
18974             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18975             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18976             /*ConstexprKind*/ CSK_unspecified);
18977 
18978         if (FD->getQualifier())
18979           NewFD->setQualifierInfo(FD->getQualifierLoc());
18980 
18981         SmallVector<ParmVarDecl*, 16> Params;
18982         for (const auto &AI : FT->param_types()) {
18983           ParmVarDecl *Param =
18984             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18985           Param->setScopeInfo(0, Params.size());
18986           Params.push_back(Param);
18987         }
18988         NewFD->setParams(Params);
18989         DRE->setDecl(NewFD);
18990         VD = DRE->getDecl();
18991       }
18992     }
18993 
18994     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18995       if (MD->isInstance()) {
18996         ValueKind = VK_RValue;
18997         Type = S.Context.BoundMemberTy;
18998       }
18999 
19000     // Function references aren't l-values in C.
19001     if (!S.getLangOpts().CPlusPlus)
19002       ValueKind = VK_RValue;
19003 
19004   //  - variables
19005   } else if (isa<VarDecl>(VD)) {
19006     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19007       Type = RefTy->getPointeeType();
19008     } else if (Type->isFunctionType()) {
19009       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19010         << VD << E->getSourceRange();
19011       return ExprError();
19012     }
19013 
19014   //  - nothing else
19015   } else {
19016     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19017       << VD << E->getSourceRange();
19018     return ExprError();
19019   }
19020 
19021   // Modifying the declaration like this is friendly to IR-gen but
19022   // also really dangerous.
19023   VD->setType(DestType);
19024   E->setType(Type);
19025   E->setValueKind(ValueKind);
19026   return E;
19027 }
19028 
19029 /// Check a cast of an unknown-any type.  We intentionally only
19030 /// trigger this for C-style casts.
19031 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19032                                      Expr *CastExpr, CastKind &CastKind,
19033                                      ExprValueKind &VK, CXXCastPath &Path) {
19034   // The type we're casting to must be either void or complete.
19035   if (!CastType->isVoidType() &&
19036       RequireCompleteType(TypeRange.getBegin(), CastType,
19037                           diag::err_typecheck_cast_to_incomplete))
19038     return ExprError();
19039 
19040   // Rewrite the casted expression from scratch.
19041   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19042   if (!result.isUsable()) return ExprError();
19043 
19044   CastExpr = result.get();
19045   VK = CastExpr->getValueKind();
19046   CastKind = CK_NoOp;
19047 
19048   return CastExpr;
19049 }
19050 
19051 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19052   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19053 }
19054 
19055 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19056                                     Expr *arg, QualType &paramType) {
19057   // If the syntactic form of the argument is not an explicit cast of
19058   // any sort, just do default argument promotion.
19059   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19060   if (!castArg) {
19061     ExprResult result = DefaultArgumentPromotion(arg);
19062     if (result.isInvalid()) return ExprError();
19063     paramType = result.get()->getType();
19064     return result;
19065   }
19066 
19067   // Otherwise, use the type that was written in the explicit cast.
19068   assert(!arg->hasPlaceholderType());
19069   paramType = castArg->getTypeAsWritten();
19070 
19071   // Copy-initialize a parameter of that type.
19072   InitializedEntity entity =
19073     InitializedEntity::InitializeParameter(Context, paramType,
19074                                            /*consumed*/ false);
19075   return PerformCopyInitialization(entity, callLoc, arg);
19076 }
19077 
19078 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19079   Expr *orig = E;
19080   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19081   while (true) {
19082     E = E->IgnoreParenImpCasts();
19083     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19084       E = call->getCallee();
19085       diagID = diag::err_uncasted_call_of_unknown_any;
19086     } else {
19087       break;
19088     }
19089   }
19090 
19091   SourceLocation loc;
19092   NamedDecl *d;
19093   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19094     loc = ref->getLocation();
19095     d = ref->getDecl();
19096   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19097     loc = mem->getMemberLoc();
19098     d = mem->getMemberDecl();
19099   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19100     diagID = diag::err_uncasted_call_of_unknown_any;
19101     loc = msg->getSelectorStartLoc();
19102     d = msg->getMethodDecl();
19103     if (!d) {
19104       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19105         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19106         << orig->getSourceRange();
19107       return ExprError();
19108     }
19109   } else {
19110     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19111       << E->getSourceRange();
19112     return ExprError();
19113   }
19114 
19115   S.Diag(loc, diagID) << d << orig->getSourceRange();
19116 
19117   // Never recoverable.
19118   return ExprError();
19119 }
19120 
19121 /// Check for operands with placeholder types and complain if found.
19122 /// Returns ExprError() if there was an error and no recovery was possible.
19123 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19124   if (!Context.isDependenceAllowed()) {
19125     // C cannot handle TypoExpr nodes on either side of a binop because it
19126     // doesn't handle dependent types properly, so make sure any TypoExprs have
19127     // been dealt with before checking the operands.
19128     ExprResult Result = CorrectDelayedTyposInExpr(E);
19129     if (!Result.isUsable()) return ExprError();
19130     E = Result.get();
19131   }
19132 
19133   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19134   if (!placeholderType) return E;
19135 
19136   switch (placeholderType->getKind()) {
19137 
19138   // Overloaded expressions.
19139   case BuiltinType::Overload: {
19140     // Try to resolve a single function template specialization.
19141     // This is obligatory.
19142     ExprResult Result = E;
19143     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19144       return Result;
19145 
19146     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19147     // leaves Result unchanged on failure.
19148     Result = E;
19149     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19150       return Result;
19151 
19152     // If that failed, try to recover with a call.
19153     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19154                          /*complain*/ true);
19155     return Result;
19156   }
19157 
19158   // Bound member functions.
19159   case BuiltinType::BoundMember: {
19160     ExprResult result = E;
19161     const Expr *BME = E->IgnoreParens();
19162     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19163     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19164     if (isa<CXXPseudoDestructorExpr>(BME)) {
19165       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19166     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19167       if (ME->getMemberNameInfo().getName().getNameKind() ==
19168           DeclarationName::CXXDestructorName)
19169         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19170     }
19171     tryToRecoverWithCall(result, PD,
19172                          /*complain*/ true);
19173     return result;
19174   }
19175 
19176   // ARC unbridged casts.
19177   case BuiltinType::ARCUnbridgedCast: {
19178     Expr *realCast = stripARCUnbridgedCast(E);
19179     diagnoseARCUnbridgedCast(realCast);
19180     return realCast;
19181   }
19182 
19183   // Expressions of unknown type.
19184   case BuiltinType::UnknownAny:
19185     return diagnoseUnknownAnyExpr(*this, E);
19186 
19187   // Pseudo-objects.
19188   case BuiltinType::PseudoObject:
19189     return checkPseudoObjectRValue(E);
19190 
19191   case BuiltinType::BuiltinFn: {
19192     // Accept __noop without parens by implicitly converting it to a call expr.
19193     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19194     if (DRE) {
19195       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19196       if (FD->getBuiltinID() == Builtin::BI__noop) {
19197         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19198                               CK_BuiltinFnToFnPtr)
19199                 .get();
19200         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19201                                 VK_RValue, SourceLocation(),
19202                                 FPOptionsOverride());
19203       }
19204     }
19205 
19206     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19207     return ExprError();
19208   }
19209 
19210   case BuiltinType::IncompleteMatrixIdx:
19211     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19212              ->getRowIdx()
19213              ->getBeginLoc(),
19214          diag::err_matrix_incomplete_index);
19215     return ExprError();
19216 
19217   // Expressions of unknown type.
19218   case BuiltinType::OMPArraySection:
19219     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19220     return ExprError();
19221 
19222   // Expressions of unknown type.
19223   case BuiltinType::OMPArrayShaping:
19224     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19225 
19226   case BuiltinType::OMPIterator:
19227     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19228 
19229   // Everything else should be impossible.
19230 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19231   case BuiltinType::Id:
19232 #include "clang/Basic/OpenCLImageTypes.def"
19233 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19234   case BuiltinType::Id:
19235 #include "clang/Basic/OpenCLExtensionTypes.def"
19236 #define SVE_TYPE(Name, Id, SingletonId) \
19237   case BuiltinType::Id:
19238 #include "clang/Basic/AArch64SVEACLETypes.def"
19239 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \
19240   case BuiltinType::Id:
19241 #include "clang/Basic/PPCTypes.def"
19242 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19243 #define PLACEHOLDER_TYPE(Id, SingletonId)
19244 #include "clang/AST/BuiltinTypes.def"
19245     break;
19246   }
19247 
19248   llvm_unreachable("invalid placeholder type!");
19249 }
19250 
19251 bool Sema::CheckCaseExpression(Expr *E) {
19252   if (E->isTypeDependent())
19253     return true;
19254   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19255     return E->getType()->isIntegralOrEnumerationType();
19256   return false;
19257 }
19258 
19259 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19260 ExprResult
19261 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19262   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19263          "Unknown Objective-C Boolean value!");
19264   QualType BoolT = Context.ObjCBuiltinBoolTy;
19265   if (!Context.getBOOLDecl()) {
19266     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19267                         Sema::LookupOrdinaryName);
19268     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19269       NamedDecl *ND = Result.getFoundDecl();
19270       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19271         Context.setBOOLDecl(TD);
19272     }
19273   }
19274   if (Context.getBOOLDecl())
19275     BoolT = Context.getBOOLType();
19276   return new (Context)
19277       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19278 }
19279 
19280 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19281     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19282     SourceLocation RParen) {
19283 
19284   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19285 
19286   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19287     return Spec.getPlatform() == Platform;
19288   });
19289 
19290   VersionTuple Version;
19291   if (Spec != AvailSpecs.end())
19292     Version = Spec->getVersion();
19293 
19294   // The use of `@available` in the enclosing function should be analyzed to
19295   // warn when it's used inappropriately (i.e. not if(@available)).
19296   if (getCurFunctionOrMethodDecl())
19297     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19298   else if (getCurBlock() || getCurLambda())
19299     getCurFunction()->HasPotentialAvailabilityViolations = true;
19300 
19301   return new (Context)
19302       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19303 }
19304 
19305 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19306                                     ArrayRef<Expr *> SubExprs, QualType T) {
19307   if (!Context.getLangOpts().RecoveryAST)
19308     return ExprError();
19309 
19310   if (isSFINAEContext())
19311     return ExprError();
19312 
19313   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19314     // We don't know the concrete type, fallback to dependent type.
19315     T = Context.DependentTy;
19316   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19317 }
19318