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         if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3782           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3783         }
3784       } else if (getLangOpts().OpenCL &&
3785                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3786         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3787         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3788         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3789       }
3790     }
3791   } else if (!Literal.isIntegerLiteral()) {
3792     return ExprError();
3793   } else {
3794     QualType Ty;
3795 
3796     // 'long long' is a C99 or C++11 feature.
3797     if (!getLangOpts().C99 && Literal.isLongLong) {
3798       if (getLangOpts().CPlusPlus)
3799         Diag(Tok.getLocation(),
3800              getLangOpts().CPlusPlus11 ?
3801              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3802       else
3803         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3804     }
3805 
3806     // Get the value in the widest-possible width.
3807     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3808     llvm::APInt ResultVal(MaxWidth, 0);
3809 
3810     if (Literal.GetIntegerValue(ResultVal)) {
3811       // If this value didn't fit into uintmax_t, error and force to ull.
3812       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3813           << /* Unsigned */ 1;
3814       Ty = Context.UnsignedLongLongTy;
3815       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3816              "long long is not intmax_t?");
3817     } else {
3818       // If this value fits into a ULL, try to figure out what else it fits into
3819       // according to the rules of C99 6.4.4.1p5.
3820 
3821       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3822       // be an unsigned int.
3823       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3824 
3825       // Check from smallest to largest, picking the smallest type we can.
3826       unsigned Width = 0;
3827 
3828       // Microsoft specific integer suffixes are explicitly sized.
3829       if (Literal.MicrosoftInteger) {
3830         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3831           Width = 8;
3832           Ty = Context.CharTy;
3833         } else {
3834           Width = Literal.MicrosoftInteger;
3835           Ty = Context.getIntTypeForBitwidth(Width,
3836                                              /*Signed=*/!Literal.isUnsigned);
3837         }
3838       }
3839 
3840       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3841         // Are int/unsigned possibilities?
3842         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3843 
3844         // Does it fit in a unsigned int?
3845         if (ResultVal.isIntN(IntSize)) {
3846           // Does it fit in a signed int?
3847           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3848             Ty = Context.IntTy;
3849           else if (AllowUnsigned)
3850             Ty = Context.UnsignedIntTy;
3851           Width = IntSize;
3852         }
3853       }
3854 
3855       // Are long/unsigned long possibilities?
3856       if (Ty.isNull() && !Literal.isLongLong) {
3857         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3858 
3859         // Does it fit in a unsigned long?
3860         if (ResultVal.isIntN(LongSize)) {
3861           // Does it fit in a signed long?
3862           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3863             Ty = Context.LongTy;
3864           else if (AllowUnsigned)
3865             Ty = Context.UnsignedLongTy;
3866           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3867           // is compatible.
3868           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3869             const unsigned LongLongSize =
3870                 Context.getTargetInfo().getLongLongWidth();
3871             Diag(Tok.getLocation(),
3872                  getLangOpts().CPlusPlus
3873                      ? Literal.isLong
3874                            ? diag::warn_old_implicitly_unsigned_long_cxx
3875                            : /*C++98 UB*/ diag::
3876                                  ext_old_implicitly_unsigned_long_cxx
3877                      : diag::warn_old_implicitly_unsigned_long)
3878                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3879                                             : /*will be ill-formed*/ 1);
3880             Ty = Context.UnsignedLongTy;
3881           }
3882           Width = LongSize;
3883         }
3884       }
3885 
3886       // Check long long if needed.
3887       if (Ty.isNull()) {
3888         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3889 
3890         // Does it fit in a unsigned long long?
3891         if (ResultVal.isIntN(LongLongSize)) {
3892           // Does it fit in a signed long long?
3893           // To be compatible with MSVC, hex integer literals ending with the
3894           // LL or i64 suffix are always signed in Microsoft mode.
3895           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3896               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3897             Ty = Context.LongLongTy;
3898           else if (AllowUnsigned)
3899             Ty = Context.UnsignedLongLongTy;
3900           Width = LongLongSize;
3901         }
3902       }
3903 
3904       // If we still couldn't decide a type, we probably have something that
3905       // does not fit in a signed long long, but has no U suffix.
3906       if (Ty.isNull()) {
3907         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3908         Ty = Context.UnsignedLongLongTy;
3909         Width = Context.getTargetInfo().getLongLongWidth();
3910       }
3911 
3912       if (ResultVal.getBitWidth() != Width)
3913         ResultVal = ResultVal.trunc(Width);
3914     }
3915     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3916   }
3917 
3918   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3919   if (Literal.isImaginary) {
3920     Res = new (Context) ImaginaryLiteral(Res,
3921                                         Context.getComplexType(Res->getType()));
3922 
3923     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3924   }
3925   return Res;
3926 }
3927 
3928 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3929   assert(E && "ActOnParenExpr() missing expr");
3930   return new (Context) ParenExpr(L, R, E);
3931 }
3932 
3933 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3934                                          SourceLocation Loc,
3935                                          SourceRange ArgRange) {
3936   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3937   // scalar or vector data type argument..."
3938   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3939   // type (C99 6.2.5p18) or void.
3940   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3941     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3942       << T << ArgRange;
3943     return true;
3944   }
3945 
3946   assert((T->isVoidType() || !T->isIncompleteType()) &&
3947          "Scalar types should always be complete");
3948   return false;
3949 }
3950 
3951 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3952                                            SourceLocation Loc,
3953                                            SourceRange ArgRange,
3954                                            UnaryExprOrTypeTrait TraitKind) {
3955   // Invalid types must be hard errors for SFINAE in C++.
3956   if (S.LangOpts.CPlusPlus)
3957     return true;
3958 
3959   // C99 6.5.3.4p1:
3960   if (T->isFunctionType() &&
3961       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3962        TraitKind == UETT_PreferredAlignOf)) {
3963     // sizeof(function)/alignof(function) is allowed as an extension.
3964     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3965         << getTraitSpelling(TraitKind) << ArgRange;
3966     return false;
3967   }
3968 
3969   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3970   // this is an error (OpenCL v1.1 s6.3.k)
3971   if (T->isVoidType()) {
3972     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3973                                         : diag::ext_sizeof_alignof_void_type;
3974     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
3975     return false;
3976   }
3977 
3978   return true;
3979 }
3980 
3981 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3982                                              SourceLocation Loc,
3983                                              SourceRange ArgRange,
3984                                              UnaryExprOrTypeTrait TraitKind) {
3985   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3986   // runtime doesn't allow it.
3987   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3988     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3989       << T << (TraitKind == UETT_SizeOf)
3990       << ArgRange;
3991     return true;
3992   }
3993 
3994   return false;
3995 }
3996 
3997 /// Check whether E is a pointer from a decayed array type (the decayed
3998 /// pointer type is equal to T) and emit a warning if it is.
3999 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4000                                      Expr *E) {
4001   // Don't warn if the operation changed the type.
4002   if (T != E->getType())
4003     return;
4004 
4005   // Now look for array decays.
4006   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4007   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4008     return;
4009 
4010   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4011                                              << ICE->getType()
4012                                              << ICE->getSubExpr()->getType();
4013 }
4014 
4015 /// Check the constraints on expression operands to unary type expression
4016 /// and type traits.
4017 ///
4018 /// Completes any types necessary and validates the constraints on the operand
4019 /// expression. The logic mostly mirrors the type-based overload, but may modify
4020 /// the expression as it completes the type for that expression through template
4021 /// instantiation, etc.
4022 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4023                                             UnaryExprOrTypeTrait ExprKind) {
4024   QualType ExprTy = E->getType();
4025   assert(!ExprTy->isReferenceType());
4026 
4027   bool IsUnevaluatedOperand =
4028       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4029        ExprKind == UETT_PreferredAlignOf);
4030   if (IsUnevaluatedOperand) {
4031     ExprResult Result = CheckUnevaluatedOperand(E);
4032     if (Result.isInvalid())
4033       return true;
4034     E = Result.get();
4035   }
4036 
4037   if (ExprKind == UETT_VecStep)
4038     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4039                                         E->getSourceRange());
4040 
4041   // Explicitly list some types as extensions.
4042   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4043                                       E->getSourceRange(), ExprKind))
4044     return false;
4045 
4046   // 'alignof' applied to an expression only requires the base element type of
4047   // the expression to be complete. 'sizeof' requires the expression's type to
4048   // be complete (and will attempt to complete it if it's an array of unknown
4049   // bound).
4050   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4051     if (RequireCompleteSizedType(
4052             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4053             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4054             getTraitSpelling(ExprKind), E->getSourceRange()))
4055       return true;
4056   } else {
4057     if (RequireCompleteSizedExprType(
4058             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4059             getTraitSpelling(ExprKind), E->getSourceRange()))
4060       return true;
4061   }
4062 
4063   // Completing the expression's type may have changed it.
4064   ExprTy = E->getType();
4065   assert(!ExprTy->isReferenceType());
4066 
4067   if (ExprTy->isFunctionType()) {
4068     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4069         << getTraitSpelling(ExprKind) << E->getSourceRange();
4070     return true;
4071   }
4072 
4073   // The operand for sizeof and alignof is in an unevaluated expression context,
4074   // so side effects could result in unintended consequences.
4075   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4076       E->HasSideEffects(Context, false))
4077     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4078 
4079   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4080                                        E->getSourceRange(), ExprKind))
4081     return true;
4082 
4083   if (ExprKind == UETT_SizeOf) {
4084     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4085       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4086         QualType OType = PVD->getOriginalType();
4087         QualType Type = PVD->getType();
4088         if (Type->isPointerType() && OType->isArrayType()) {
4089           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4090             << Type << OType;
4091           Diag(PVD->getLocation(), diag::note_declared_at);
4092         }
4093       }
4094     }
4095 
4096     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4097     // decays into a pointer and returns an unintended result. This is most
4098     // likely a typo for "sizeof(array) op x".
4099     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4100       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4101                                BO->getLHS());
4102       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4103                                BO->getRHS());
4104     }
4105   }
4106 
4107   return false;
4108 }
4109 
4110 /// Check the constraints on operands to unary expression and type
4111 /// traits.
4112 ///
4113 /// This will complete any types necessary, and validate the various constraints
4114 /// on those operands.
4115 ///
4116 /// The UsualUnaryConversions() function is *not* called by this routine.
4117 /// C99 6.3.2.1p[2-4] all state:
4118 ///   Except when it is the operand of the sizeof operator ...
4119 ///
4120 /// C++ [expr.sizeof]p4
4121 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4122 ///   standard conversions are not applied to the operand of sizeof.
4123 ///
4124 /// This policy is followed for all of the unary trait expressions.
4125 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4126                                             SourceLocation OpLoc,
4127                                             SourceRange ExprRange,
4128                                             UnaryExprOrTypeTrait ExprKind) {
4129   if (ExprType->isDependentType())
4130     return false;
4131 
4132   // C++ [expr.sizeof]p2:
4133   //     When applied to a reference or a reference type, the result
4134   //     is the size of the referenced type.
4135   // C++11 [expr.alignof]p3:
4136   //     When alignof is applied to a reference type, the result
4137   //     shall be the alignment of the referenced type.
4138   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4139     ExprType = Ref->getPointeeType();
4140 
4141   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4142   //   When alignof or _Alignof is applied to an array type, the result
4143   //   is the alignment of the element type.
4144   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4145       ExprKind == UETT_OpenMPRequiredSimdAlign)
4146     ExprType = Context.getBaseElementType(ExprType);
4147 
4148   if (ExprKind == UETT_VecStep)
4149     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4150 
4151   // Explicitly list some types as extensions.
4152   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4153                                       ExprKind))
4154     return false;
4155 
4156   if (RequireCompleteSizedType(
4157           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4158           getTraitSpelling(ExprKind), ExprRange))
4159     return true;
4160 
4161   if (ExprType->isFunctionType()) {
4162     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4163         << getTraitSpelling(ExprKind) << ExprRange;
4164     return true;
4165   }
4166 
4167   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4168                                        ExprKind))
4169     return true;
4170 
4171   return false;
4172 }
4173 
4174 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4175   // Cannot know anything else if the expression is dependent.
4176   if (E->isTypeDependent())
4177     return false;
4178 
4179   if (E->getObjectKind() == OK_BitField) {
4180     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4181        << 1 << E->getSourceRange();
4182     return true;
4183   }
4184 
4185   ValueDecl *D = nullptr;
4186   Expr *Inner = E->IgnoreParens();
4187   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4188     D = DRE->getDecl();
4189   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4190     D = ME->getMemberDecl();
4191   }
4192 
4193   // If it's a field, require the containing struct to have a
4194   // complete definition so that we can compute the layout.
4195   //
4196   // This can happen in C++11 onwards, either by naming the member
4197   // in a way that is not transformed into a member access expression
4198   // (in an unevaluated operand, for instance), or by naming the member
4199   // in a trailing-return-type.
4200   //
4201   // For the record, since __alignof__ on expressions is a GCC
4202   // extension, GCC seems to permit this but always gives the
4203   // nonsensical answer 0.
4204   //
4205   // We don't really need the layout here --- we could instead just
4206   // directly check for all the appropriate alignment-lowing
4207   // attributes --- but that would require duplicating a lot of
4208   // logic that just isn't worth duplicating for such a marginal
4209   // use-case.
4210   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4211     // Fast path this check, since we at least know the record has a
4212     // definition if we can find a member of it.
4213     if (!FD->getParent()->isCompleteDefinition()) {
4214       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4215         << E->getSourceRange();
4216       return true;
4217     }
4218 
4219     // Otherwise, if it's a field, and the field doesn't have
4220     // reference type, then it must have a complete type (or be a
4221     // flexible array member, which we explicitly want to
4222     // white-list anyway), which makes the following checks trivial.
4223     if (!FD->getType()->isReferenceType())
4224       return false;
4225   }
4226 
4227   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4228 }
4229 
4230 bool Sema::CheckVecStepExpr(Expr *E) {
4231   E = E->IgnoreParens();
4232 
4233   // Cannot know anything else if the expression is dependent.
4234   if (E->isTypeDependent())
4235     return false;
4236 
4237   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4238 }
4239 
4240 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4241                                         CapturingScopeInfo *CSI) {
4242   assert(T->isVariablyModifiedType());
4243   assert(CSI != nullptr);
4244 
4245   // We're going to walk down into the type and look for VLA expressions.
4246   do {
4247     const Type *Ty = T.getTypePtr();
4248     switch (Ty->getTypeClass()) {
4249 #define TYPE(Class, Base)
4250 #define ABSTRACT_TYPE(Class, Base)
4251 #define NON_CANONICAL_TYPE(Class, Base)
4252 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4253 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4254 #include "clang/AST/TypeNodes.inc"
4255       T = QualType();
4256       break;
4257     // These types are never variably-modified.
4258     case Type::Builtin:
4259     case Type::Complex:
4260     case Type::Vector:
4261     case Type::ExtVector:
4262     case Type::ConstantMatrix:
4263     case Type::Record:
4264     case Type::Enum:
4265     case Type::Elaborated:
4266     case Type::TemplateSpecialization:
4267     case Type::ObjCObject:
4268     case Type::ObjCInterface:
4269     case Type::ObjCObjectPointer:
4270     case Type::ObjCTypeParam:
4271     case Type::Pipe:
4272     case Type::ExtInt:
4273       llvm_unreachable("type class is never variably-modified!");
4274     case Type::Adjusted:
4275       T = cast<AdjustedType>(Ty)->getOriginalType();
4276       break;
4277     case Type::Decayed:
4278       T = cast<DecayedType>(Ty)->getPointeeType();
4279       break;
4280     case Type::Pointer:
4281       T = cast<PointerType>(Ty)->getPointeeType();
4282       break;
4283     case Type::BlockPointer:
4284       T = cast<BlockPointerType>(Ty)->getPointeeType();
4285       break;
4286     case Type::LValueReference:
4287     case Type::RValueReference:
4288       T = cast<ReferenceType>(Ty)->getPointeeType();
4289       break;
4290     case Type::MemberPointer:
4291       T = cast<MemberPointerType>(Ty)->getPointeeType();
4292       break;
4293     case Type::ConstantArray:
4294     case Type::IncompleteArray:
4295       // Losing element qualification here is fine.
4296       T = cast<ArrayType>(Ty)->getElementType();
4297       break;
4298     case Type::VariableArray: {
4299       // Losing element qualification here is fine.
4300       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4301 
4302       // Unknown size indication requires no size computation.
4303       // Otherwise, evaluate and record it.
4304       auto Size = VAT->getSizeExpr();
4305       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4306           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4307         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4308 
4309       T = VAT->getElementType();
4310       break;
4311     }
4312     case Type::FunctionProto:
4313     case Type::FunctionNoProto:
4314       T = cast<FunctionType>(Ty)->getReturnType();
4315       break;
4316     case Type::Paren:
4317     case Type::TypeOf:
4318     case Type::UnaryTransform:
4319     case Type::Attributed:
4320     case Type::SubstTemplateTypeParm:
4321     case Type::MacroQualified:
4322       // Keep walking after single level desugaring.
4323       T = T.getSingleStepDesugaredType(Context);
4324       break;
4325     case Type::Typedef:
4326       T = cast<TypedefType>(Ty)->desugar();
4327       break;
4328     case Type::Decltype:
4329       T = cast<DecltypeType>(Ty)->desugar();
4330       break;
4331     case Type::Auto:
4332     case Type::DeducedTemplateSpecialization:
4333       T = cast<DeducedType>(Ty)->getDeducedType();
4334       break;
4335     case Type::TypeOfExpr:
4336       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4337       break;
4338     case Type::Atomic:
4339       T = cast<AtomicType>(Ty)->getValueType();
4340       break;
4341     }
4342   } while (!T.isNull() && T->isVariablyModifiedType());
4343 }
4344 
4345 /// Build a sizeof or alignof expression given a type operand.
4346 ExprResult
4347 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4348                                      SourceLocation OpLoc,
4349                                      UnaryExprOrTypeTrait ExprKind,
4350                                      SourceRange R) {
4351   if (!TInfo)
4352     return ExprError();
4353 
4354   QualType T = TInfo->getType();
4355 
4356   if (!T->isDependentType() &&
4357       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4358     return ExprError();
4359 
4360   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4361     if (auto *TT = T->getAs<TypedefType>()) {
4362       for (auto I = FunctionScopes.rbegin(),
4363                 E = std::prev(FunctionScopes.rend());
4364            I != E; ++I) {
4365         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4366         if (CSI == nullptr)
4367           break;
4368         DeclContext *DC = nullptr;
4369         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4370           DC = LSI->CallOperator;
4371         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4372           DC = CRSI->TheCapturedDecl;
4373         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4374           DC = BSI->TheDecl;
4375         if (DC) {
4376           if (DC->containsDecl(TT->getDecl()))
4377             break;
4378           captureVariablyModifiedType(Context, T, CSI);
4379         }
4380       }
4381     }
4382   }
4383 
4384   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4385   return new (Context) UnaryExprOrTypeTraitExpr(
4386       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4387 }
4388 
4389 /// Build a sizeof or alignof expression given an expression
4390 /// operand.
4391 ExprResult
4392 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4393                                      UnaryExprOrTypeTrait ExprKind) {
4394   ExprResult PE = CheckPlaceholderExpr(E);
4395   if (PE.isInvalid())
4396     return ExprError();
4397 
4398   E = PE.get();
4399 
4400   // Verify that the operand is valid.
4401   bool isInvalid = false;
4402   if (E->isTypeDependent()) {
4403     // Delay type-checking for type-dependent expressions.
4404   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4405     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4406   } else if (ExprKind == UETT_VecStep) {
4407     isInvalid = CheckVecStepExpr(E);
4408   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4409       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4410       isInvalid = true;
4411   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4412     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4413     isInvalid = true;
4414   } else {
4415     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4416   }
4417 
4418   if (isInvalid)
4419     return ExprError();
4420 
4421   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4422     PE = TransformToPotentiallyEvaluated(E);
4423     if (PE.isInvalid()) return ExprError();
4424     E = PE.get();
4425   }
4426 
4427   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4428   return new (Context) UnaryExprOrTypeTraitExpr(
4429       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4430 }
4431 
4432 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4433 /// expr and the same for @c alignof and @c __alignof
4434 /// Note that the ArgRange is invalid if isType is false.
4435 ExprResult
4436 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4437                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4438                                     void *TyOrEx, SourceRange ArgRange) {
4439   // If error parsing type, ignore.
4440   if (!TyOrEx) return ExprError();
4441 
4442   if (IsType) {
4443     TypeSourceInfo *TInfo;
4444     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4445     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4446   }
4447 
4448   Expr *ArgEx = (Expr *)TyOrEx;
4449   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4450   return Result;
4451 }
4452 
4453 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4454                                      bool IsReal) {
4455   if (V.get()->isTypeDependent())
4456     return S.Context.DependentTy;
4457 
4458   // _Real and _Imag are only l-values for normal l-values.
4459   if (V.get()->getObjectKind() != OK_Ordinary) {
4460     V = S.DefaultLvalueConversion(V.get());
4461     if (V.isInvalid())
4462       return QualType();
4463   }
4464 
4465   // These operators return the element type of a complex type.
4466   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4467     return CT->getElementType();
4468 
4469   // Otherwise they pass through real integer and floating point types here.
4470   if (V.get()->getType()->isArithmeticType())
4471     return V.get()->getType();
4472 
4473   // Test for placeholders.
4474   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4475   if (PR.isInvalid()) return QualType();
4476   if (PR.get() != V.get()) {
4477     V = PR;
4478     return CheckRealImagOperand(S, V, Loc, IsReal);
4479   }
4480 
4481   // Reject anything else.
4482   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4483     << (IsReal ? "__real" : "__imag");
4484   return QualType();
4485 }
4486 
4487 
4488 
4489 ExprResult
4490 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4491                           tok::TokenKind Kind, Expr *Input) {
4492   UnaryOperatorKind Opc;
4493   switch (Kind) {
4494   default: llvm_unreachable("Unknown unary op!");
4495   case tok::plusplus:   Opc = UO_PostInc; break;
4496   case tok::minusminus: Opc = UO_PostDec; break;
4497   }
4498 
4499   // Since this might is a postfix expression, get rid of ParenListExprs.
4500   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4501   if (Result.isInvalid()) return ExprError();
4502   Input = Result.get();
4503 
4504   return BuildUnaryOp(S, OpLoc, Opc, Input);
4505 }
4506 
4507 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4508 ///
4509 /// \return true on error
4510 static bool checkArithmeticOnObjCPointer(Sema &S,
4511                                          SourceLocation opLoc,
4512                                          Expr *op) {
4513   assert(op->getType()->isObjCObjectPointerType());
4514   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4515       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4516     return false;
4517 
4518   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4519     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4520     << op->getSourceRange();
4521   return true;
4522 }
4523 
4524 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4525   auto *BaseNoParens = Base->IgnoreParens();
4526   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4527     return MSProp->getPropertyDecl()->getType()->isArrayType();
4528   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4529 }
4530 
4531 ExprResult
4532 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4533                               Expr *idx, SourceLocation rbLoc) {
4534   if (base && !base->getType().isNull() &&
4535       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4536     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4537                                     SourceLocation(), /*Length*/ nullptr,
4538                                     /*Stride=*/nullptr, rbLoc);
4539 
4540   // Since this might be a postfix expression, get rid of ParenListExprs.
4541   if (isa<ParenListExpr>(base)) {
4542     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4543     if (result.isInvalid()) return ExprError();
4544     base = result.get();
4545   }
4546 
4547   // Check if base and idx form a MatrixSubscriptExpr.
4548   //
4549   // Helper to check for comma expressions, which are not allowed as indices for
4550   // matrix subscript expressions.
4551   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4552     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4553       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4554           << SourceRange(base->getBeginLoc(), rbLoc);
4555       return true;
4556     }
4557     return false;
4558   };
4559   // The matrix subscript operator ([][])is considered a single operator.
4560   // Separating the index expressions by parenthesis is not allowed.
4561   if (base->getType()->isSpecificPlaceholderType(
4562           BuiltinType::IncompleteMatrixIdx) &&
4563       !isa<MatrixSubscriptExpr>(base)) {
4564     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4565         << SourceRange(base->getBeginLoc(), rbLoc);
4566     return ExprError();
4567   }
4568   // If the base is a MatrixSubscriptExpr, try to create a new
4569   // MatrixSubscriptExpr.
4570   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4571   if (matSubscriptE) {
4572     if (CheckAndReportCommaError(idx))
4573       return ExprError();
4574 
4575     assert(matSubscriptE->isIncomplete() &&
4576            "base has to be an incomplete matrix subscript");
4577     return CreateBuiltinMatrixSubscriptExpr(
4578         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4579   }
4580 
4581   // Handle any non-overload placeholder types in the base and index
4582   // expressions.  We can't handle overloads here because the other
4583   // operand might be an overloadable type, in which case the overload
4584   // resolution for the operator overload should get the first crack
4585   // at the overload.
4586   bool IsMSPropertySubscript = false;
4587   if (base->getType()->isNonOverloadPlaceholderType()) {
4588     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4589     if (!IsMSPropertySubscript) {
4590       ExprResult result = CheckPlaceholderExpr(base);
4591       if (result.isInvalid())
4592         return ExprError();
4593       base = result.get();
4594     }
4595   }
4596 
4597   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4598   if (base->getType()->isMatrixType()) {
4599     if (CheckAndReportCommaError(idx))
4600       return ExprError();
4601 
4602     return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4603   }
4604 
4605   // A comma-expression as the index is deprecated in C++2a onwards.
4606   if (getLangOpts().CPlusPlus20 &&
4607       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4608        (isa<CXXOperatorCallExpr>(idx) &&
4609         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4610     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4611         << SourceRange(base->getBeginLoc(), rbLoc);
4612   }
4613 
4614   if (idx->getType()->isNonOverloadPlaceholderType()) {
4615     ExprResult result = CheckPlaceholderExpr(idx);
4616     if (result.isInvalid()) return ExprError();
4617     idx = result.get();
4618   }
4619 
4620   // Build an unanalyzed expression if either operand is type-dependent.
4621   if (getLangOpts().CPlusPlus &&
4622       (base->isTypeDependent() || idx->isTypeDependent())) {
4623     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4624                                             VK_LValue, OK_Ordinary, rbLoc);
4625   }
4626 
4627   // MSDN, property (C++)
4628   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4629   // This attribute can also be used in the declaration of an empty array in a
4630   // class or structure definition. For example:
4631   // __declspec(property(get=GetX, put=PutX)) int x[];
4632   // The above statement indicates that x[] can be used with one or more array
4633   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4634   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4635   if (IsMSPropertySubscript) {
4636     // Build MS property subscript expression if base is MS property reference
4637     // or MS property subscript.
4638     return new (Context) MSPropertySubscriptExpr(
4639         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4640   }
4641 
4642   // Use C++ overloaded-operator rules if either operand has record
4643   // type.  The spec says to do this if either type is *overloadable*,
4644   // but enum types can't declare subscript operators or conversion
4645   // operators, so there's nothing interesting for overload resolution
4646   // to do if there aren't any record types involved.
4647   //
4648   // ObjC pointers have their own subscripting logic that is not tied
4649   // to overload resolution and so should not take this path.
4650   if (getLangOpts().CPlusPlus &&
4651       (base->getType()->isRecordType() ||
4652        (!base->getType()->isObjCObjectPointerType() &&
4653         idx->getType()->isRecordType()))) {
4654     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4655   }
4656 
4657   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4658 
4659   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4660     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4661 
4662   return Res;
4663 }
4664 
4665 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4666   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4667   InitializationKind Kind =
4668       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4669   InitializationSequence InitSeq(*this, Entity, Kind, E);
4670   return InitSeq.Perform(*this, Entity, Kind, E);
4671 }
4672 
4673 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4674                                                   Expr *ColumnIdx,
4675                                                   SourceLocation RBLoc) {
4676   ExprResult BaseR = CheckPlaceholderExpr(Base);
4677   if (BaseR.isInvalid())
4678     return BaseR;
4679   Base = BaseR.get();
4680 
4681   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4682   if (RowR.isInvalid())
4683     return RowR;
4684   RowIdx = RowR.get();
4685 
4686   if (!ColumnIdx)
4687     return new (Context) MatrixSubscriptExpr(
4688         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4689 
4690   // Build an unanalyzed expression if any of the operands is type-dependent.
4691   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4692       ColumnIdx->isTypeDependent())
4693     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4694                                              Context.DependentTy, RBLoc);
4695 
4696   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4697   if (ColumnR.isInvalid())
4698     return ColumnR;
4699   ColumnIdx = ColumnR.get();
4700 
4701   // Check that IndexExpr is an integer expression. If it is a constant
4702   // expression, check that it is less than Dim (= the number of elements in the
4703   // corresponding dimension).
4704   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4705                           bool IsColumnIdx) -> Expr * {
4706     if (!IndexExpr->getType()->isIntegerType() &&
4707         !IndexExpr->isTypeDependent()) {
4708       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4709           << IsColumnIdx;
4710       return nullptr;
4711     }
4712 
4713     if (Optional<llvm::APSInt> Idx =
4714             IndexExpr->getIntegerConstantExpr(Context)) {
4715       if ((*Idx < 0 || *Idx >= Dim)) {
4716         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4717             << IsColumnIdx << Dim;
4718         return nullptr;
4719       }
4720     }
4721 
4722     ExprResult ConvExpr =
4723         tryConvertExprToType(IndexExpr, Context.getSizeType());
4724     assert(!ConvExpr.isInvalid() &&
4725            "should be able to convert any integer type to size type");
4726     return ConvExpr.get();
4727   };
4728 
4729   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4730   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4731   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4732   if (!RowIdx || !ColumnIdx)
4733     return ExprError();
4734 
4735   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4736                                            MTy->getElementType(), RBLoc);
4737 }
4738 
4739 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4740   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4741   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4742 
4743   // For expressions like `&(*s).b`, the base is recorded and what should be
4744   // checked.
4745   const MemberExpr *Member = nullptr;
4746   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4747     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4748 
4749   LastRecord.PossibleDerefs.erase(StrippedExpr);
4750 }
4751 
4752 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4753   if (isUnevaluatedContext())
4754     return;
4755 
4756   QualType ResultTy = E->getType();
4757   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4758 
4759   // Bail if the element is an array since it is not memory access.
4760   if (isa<ArrayType>(ResultTy))
4761     return;
4762 
4763   if (ResultTy->hasAttr(attr::NoDeref)) {
4764     LastRecord.PossibleDerefs.insert(E);
4765     return;
4766   }
4767 
4768   // Check if the base type is a pointer to a member access of a struct
4769   // marked with noderef.
4770   const Expr *Base = E->getBase();
4771   QualType BaseTy = Base->getType();
4772   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4773     // Not a pointer access
4774     return;
4775 
4776   const MemberExpr *Member = nullptr;
4777   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4778          Member->isArrow())
4779     Base = Member->getBase();
4780 
4781   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4782     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4783       LastRecord.PossibleDerefs.insert(E);
4784   }
4785 }
4786 
4787 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4788                                           Expr *LowerBound,
4789                                           SourceLocation ColonLocFirst,
4790                                           SourceLocation ColonLocSecond,
4791                                           Expr *Length, Expr *Stride,
4792                                           SourceLocation RBLoc) {
4793   if (Base->getType()->isPlaceholderType() &&
4794       !Base->getType()->isSpecificPlaceholderType(
4795           BuiltinType::OMPArraySection)) {
4796     ExprResult Result = CheckPlaceholderExpr(Base);
4797     if (Result.isInvalid())
4798       return ExprError();
4799     Base = Result.get();
4800   }
4801   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4802     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4803     if (Result.isInvalid())
4804       return ExprError();
4805     Result = DefaultLvalueConversion(Result.get());
4806     if (Result.isInvalid())
4807       return ExprError();
4808     LowerBound = Result.get();
4809   }
4810   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4811     ExprResult Result = CheckPlaceholderExpr(Length);
4812     if (Result.isInvalid())
4813       return ExprError();
4814     Result = DefaultLvalueConversion(Result.get());
4815     if (Result.isInvalid())
4816       return ExprError();
4817     Length = Result.get();
4818   }
4819   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4820     ExprResult Result = CheckPlaceholderExpr(Stride);
4821     if (Result.isInvalid())
4822       return ExprError();
4823     Result = DefaultLvalueConversion(Result.get());
4824     if (Result.isInvalid())
4825       return ExprError();
4826     Stride = Result.get();
4827   }
4828 
4829   // Build an unanalyzed expression if either operand is type-dependent.
4830   if (Base->isTypeDependent() ||
4831       (LowerBound &&
4832        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4833       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4834       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4835     return new (Context) OMPArraySectionExpr(
4836         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4837         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4838   }
4839 
4840   // Perform default conversions.
4841   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4842   QualType ResultTy;
4843   if (OriginalTy->isAnyPointerType()) {
4844     ResultTy = OriginalTy->getPointeeType();
4845   } else if (OriginalTy->isArrayType()) {
4846     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4847   } else {
4848     return ExprError(
4849         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4850         << Base->getSourceRange());
4851   }
4852   // C99 6.5.2.1p1
4853   if (LowerBound) {
4854     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4855                                                       LowerBound);
4856     if (Res.isInvalid())
4857       return ExprError(Diag(LowerBound->getExprLoc(),
4858                             diag::err_omp_typecheck_section_not_integer)
4859                        << 0 << LowerBound->getSourceRange());
4860     LowerBound = Res.get();
4861 
4862     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4863         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4864       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4865           << 0 << LowerBound->getSourceRange();
4866   }
4867   if (Length) {
4868     auto Res =
4869         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4870     if (Res.isInvalid())
4871       return ExprError(Diag(Length->getExprLoc(),
4872                             diag::err_omp_typecheck_section_not_integer)
4873                        << 1 << Length->getSourceRange());
4874     Length = Res.get();
4875 
4876     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4877         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4878       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4879           << 1 << Length->getSourceRange();
4880   }
4881   if (Stride) {
4882     ExprResult Res =
4883         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4884     if (Res.isInvalid())
4885       return ExprError(Diag(Stride->getExprLoc(),
4886                             diag::err_omp_typecheck_section_not_integer)
4887                        << 1 << Stride->getSourceRange());
4888     Stride = Res.get();
4889 
4890     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4891         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4892       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4893           << 1 << Stride->getSourceRange();
4894   }
4895 
4896   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4897   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4898   // type. Note that functions are not objects, and that (in C99 parlance)
4899   // incomplete types are not object types.
4900   if (ResultTy->isFunctionType()) {
4901     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4902         << ResultTy << Base->getSourceRange();
4903     return ExprError();
4904   }
4905 
4906   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4907                           diag::err_omp_section_incomplete_type, Base))
4908     return ExprError();
4909 
4910   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4911     Expr::EvalResult Result;
4912     if (LowerBound->EvaluateAsInt(Result, Context)) {
4913       // OpenMP 5.0, [2.1.5 Array Sections]
4914       // The array section must be a subset of the original array.
4915       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4916       if (LowerBoundValue.isNegative()) {
4917         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4918             << LowerBound->getSourceRange();
4919         return ExprError();
4920       }
4921     }
4922   }
4923 
4924   if (Length) {
4925     Expr::EvalResult Result;
4926     if (Length->EvaluateAsInt(Result, Context)) {
4927       // OpenMP 5.0, [2.1.5 Array Sections]
4928       // The length must evaluate to non-negative integers.
4929       llvm::APSInt LengthValue = Result.Val.getInt();
4930       if (LengthValue.isNegative()) {
4931         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4932             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4933             << Length->getSourceRange();
4934         return ExprError();
4935       }
4936     }
4937   } else if (ColonLocFirst.isValid() &&
4938              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4939                                       !OriginalTy->isVariableArrayType()))) {
4940     // OpenMP 5.0, [2.1.5 Array Sections]
4941     // When the size of the array dimension is not known, the length must be
4942     // specified explicitly.
4943     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
4944         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4945     return ExprError();
4946   }
4947 
4948   if (Stride) {
4949     Expr::EvalResult Result;
4950     if (Stride->EvaluateAsInt(Result, Context)) {
4951       // OpenMP 5.0, [2.1.5 Array Sections]
4952       // The stride must evaluate to a positive integer.
4953       llvm::APSInt StrideValue = Result.Val.getInt();
4954       if (!StrideValue.isStrictlyPositive()) {
4955         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
4956             << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
4957             << Stride->getSourceRange();
4958         return ExprError();
4959       }
4960     }
4961   }
4962 
4963   if (!Base->getType()->isSpecificPlaceholderType(
4964           BuiltinType::OMPArraySection)) {
4965     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4966     if (Result.isInvalid())
4967       return ExprError();
4968     Base = Result.get();
4969   }
4970   return new (Context) OMPArraySectionExpr(
4971       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
4972       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4973 }
4974 
4975 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
4976                                           SourceLocation RParenLoc,
4977                                           ArrayRef<Expr *> Dims,
4978                                           ArrayRef<SourceRange> Brackets) {
4979   if (Base->getType()->isPlaceholderType()) {
4980     ExprResult Result = CheckPlaceholderExpr(Base);
4981     if (Result.isInvalid())
4982       return ExprError();
4983     Result = DefaultLvalueConversion(Result.get());
4984     if (Result.isInvalid())
4985       return ExprError();
4986     Base = Result.get();
4987   }
4988   QualType BaseTy = Base->getType();
4989   // Delay analysis of the types/expressions if instantiation/specialization is
4990   // required.
4991   if (!BaseTy->isPointerType() && Base->isTypeDependent())
4992     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
4993                                        LParenLoc, RParenLoc, Dims, Brackets);
4994   if (!BaseTy->isPointerType() ||
4995       (!Base->isTypeDependent() &&
4996        BaseTy->getPointeeType()->isIncompleteType()))
4997     return ExprError(Diag(Base->getExprLoc(),
4998                           diag::err_omp_non_pointer_type_array_shaping_base)
4999                      << Base->getSourceRange());
5000 
5001   SmallVector<Expr *, 4> NewDims;
5002   bool ErrorFound = false;
5003   for (Expr *Dim : Dims) {
5004     if (Dim->getType()->isPlaceholderType()) {
5005       ExprResult Result = CheckPlaceholderExpr(Dim);
5006       if (Result.isInvalid()) {
5007         ErrorFound = true;
5008         continue;
5009       }
5010       Result = DefaultLvalueConversion(Result.get());
5011       if (Result.isInvalid()) {
5012         ErrorFound = true;
5013         continue;
5014       }
5015       Dim = Result.get();
5016     }
5017     if (!Dim->isTypeDependent()) {
5018       ExprResult Result =
5019           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5020       if (Result.isInvalid()) {
5021         ErrorFound = true;
5022         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5023             << Dim->getSourceRange();
5024         continue;
5025       }
5026       Dim = Result.get();
5027       Expr::EvalResult EvResult;
5028       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5029         // OpenMP 5.0, [2.1.4 Array Shaping]
5030         // Each si is an integral type expression that must evaluate to a
5031         // positive integer.
5032         llvm::APSInt Value = EvResult.Val.getInt();
5033         if (!Value.isStrictlyPositive()) {
5034           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5035               << Value.toString(/*Radix=*/10, /*Signed=*/true)
5036               << Dim->getSourceRange();
5037           ErrorFound = true;
5038           continue;
5039         }
5040       }
5041     }
5042     NewDims.push_back(Dim);
5043   }
5044   if (ErrorFound)
5045     return ExprError();
5046   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5047                                      LParenLoc, RParenLoc, NewDims, Brackets);
5048 }
5049 
5050 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5051                                       SourceLocation LLoc, SourceLocation RLoc,
5052                                       ArrayRef<OMPIteratorData> Data) {
5053   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5054   bool IsCorrect = true;
5055   for (const OMPIteratorData &D : Data) {
5056     TypeSourceInfo *TInfo = nullptr;
5057     SourceLocation StartLoc;
5058     QualType DeclTy;
5059     if (!D.Type.getAsOpaquePtr()) {
5060       // OpenMP 5.0, 2.1.6 Iterators
5061       // In an iterator-specifier, if the iterator-type is not specified then
5062       // the type of that iterator is of int type.
5063       DeclTy = Context.IntTy;
5064       StartLoc = D.DeclIdentLoc;
5065     } else {
5066       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5067       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5068     }
5069 
5070     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5071                              DeclTy->containsUnexpandedParameterPack() ||
5072                              DeclTy->isInstantiationDependentType();
5073     if (!IsDeclTyDependent) {
5074       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5075         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5076         // The iterator-type must be an integral or pointer type.
5077         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5078             << DeclTy;
5079         IsCorrect = false;
5080         continue;
5081       }
5082       if (DeclTy.isConstant(Context)) {
5083         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5084         // The iterator-type must not be const qualified.
5085         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5086             << DeclTy;
5087         IsCorrect = false;
5088         continue;
5089       }
5090     }
5091 
5092     // Iterator declaration.
5093     assert(D.DeclIdent && "Identifier expected.");
5094     // Always try to create iterator declarator to avoid extra error messages
5095     // about unknown declarations use.
5096     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5097                                D.DeclIdent, DeclTy, TInfo, SC_None);
5098     VD->setImplicit();
5099     if (S) {
5100       // Check for conflicting previous declaration.
5101       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5102       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5103                             ForVisibleRedeclaration);
5104       Previous.suppressDiagnostics();
5105       LookupName(Previous, S);
5106 
5107       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5108                            /*AllowInlineNamespace=*/false);
5109       if (!Previous.empty()) {
5110         NamedDecl *Old = Previous.getRepresentativeDecl();
5111         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5112         Diag(Old->getLocation(), diag::note_previous_definition);
5113       } else {
5114         PushOnScopeChains(VD, S);
5115       }
5116     } else {
5117       CurContext->addDecl(VD);
5118     }
5119     Expr *Begin = D.Range.Begin;
5120     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5121       ExprResult BeginRes =
5122           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5123       Begin = BeginRes.get();
5124     }
5125     Expr *End = D.Range.End;
5126     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5127       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5128       End = EndRes.get();
5129     }
5130     Expr *Step = D.Range.Step;
5131     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5132       if (!Step->getType()->isIntegralType(Context)) {
5133         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5134             << Step << Step->getSourceRange();
5135         IsCorrect = false;
5136         continue;
5137       }
5138       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5139       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5140       // If the step expression of a range-specification equals zero, the
5141       // behavior is unspecified.
5142       if (Result && Result->isNullValue()) {
5143         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5144             << Step << Step->getSourceRange();
5145         IsCorrect = false;
5146         continue;
5147       }
5148     }
5149     if (!Begin || !End || !IsCorrect) {
5150       IsCorrect = false;
5151       continue;
5152     }
5153     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5154     IDElem.IteratorDecl = VD;
5155     IDElem.AssignmentLoc = D.AssignLoc;
5156     IDElem.Range.Begin = Begin;
5157     IDElem.Range.End = End;
5158     IDElem.Range.Step = Step;
5159     IDElem.ColonLoc = D.ColonLoc;
5160     IDElem.SecondColonLoc = D.SecColonLoc;
5161   }
5162   if (!IsCorrect) {
5163     // Invalidate all created iterator declarations if error is found.
5164     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5165       if (Decl *ID = D.IteratorDecl)
5166         ID->setInvalidDecl();
5167     }
5168     return ExprError();
5169   }
5170   SmallVector<OMPIteratorHelperData, 4> Helpers;
5171   if (!CurContext->isDependentContext()) {
5172     // Build number of ityeration for each iteration range.
5173     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5174     // ((Begini-Stepi-1-Endi) / -Stepi);
5175     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5176       // (Endi - Begini)
5177       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5178                                           D.Range.Begin);
5179       if(!Res.isUsable()) {
5180         IsCorrect = false;
5181         continue;
5182       }
5183       ExprResult St, St1;
5184       if (D.Range.Step) {
5185         St = D.Range.Step;
5186         // (Endi - Begini) + Stepi
5187         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5188         if (!Res.isUsable()) {
5189           IsCorrect = false;
5190           continue;
5191         }
5192         // (Endi - Begini) + Stepi - 1
5193         Res =
5194             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5195                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5196         if (!Res.isUsable()) {
5197           IsCorrect = false;
5198           continue;
5199         }
5200         // ((Endi - Begini) + Stepi - 1) / Stepi
5201         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5202         if (!Res.isUsable()) {
5203           IsCorrect = false;
5204           continue;
5205         }
5206         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5207         // (Begini - Endi)
5208         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5209                                              D.Range.Begin, D.Range.End);
5210         if (!Res1.isUsable()) {
5211           IsCorrect = false;
5212           continue;
5213         }
5214         // (Begini - Endi) - Stepi
5215         Res1 =
5216             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5217         if (!Res1.isUsable()) {
5218           IsCorrect = false;
5219           continue;
5220         }
5221         // (Begini - Endi) - Stepi - 1
5222         Res1 =
5223             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5224                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5225         if (!Res1.isUsable()) {
5226           IsCorrect = false;
5227           continue;
5228         }
5229         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5230         Res1 =
5231             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5232         if (!Res1.isUsable()) {
5233           IsCorrect = false;
5234           continue;
5235         }
5236         // Stepi > 0.
5237         ExprResult CmpRes =
5238             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5239                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5240         if (!CmpRes.isUsable()) {
5241           IsCorrect = false;
5242           continue;
5243         }
5244         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5245                                  Res.get(), Res1.get());
5246         if (!Res.isUsable()) {
5247           IsCorrect = false;
5248           continue;
5249         }
5250       }
5251       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5252       if (!Res.isUsable()) {
5253         IsCorrect = false;
5254         continue;
5255       }
5256 
5257       // Build counter update.
5258       // Build counter.
5259       auto *CounterVD =
5260           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5261                           D.IteratorDecl->getBeginLoc(), nullptr,
5262                           Res.get()->getType(), nullptr, SC_None);
5263       CounterVD->setImplicit();
5264       ExprResult RefRes =
5265           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5266                            D.IteratorDecl->getBeginLoc());
5267       // Build counter update.
5268       // I = Begini + counter * Stepi;
5269       ExprResult UpdateRes;
5270       if (D.Range.Step) {
5271         UpdateRes = CreateBuiltinBinOp(
5272             D.AssignmentLoc, BO_Mul,
5273             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5274       } else {
5275         UpdateRes = DefaultLvalueConversion(RefRes.get());
5276       }
5277       if (!UpdateRes.isUsable()) {
5278         IsCorrect = false;
5279         continue;
5280       }
5281       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5282                                      UpdateRes.get());
5283       if (!UpdateRes.isUsable()) {
5284         IsCorrect = false;
5285         continue;
5286       }
5287       ExprResult VDRes =
5288           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5289                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5290                            D.IteratorDecl->getBeginLoc());
5291       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5292                                      UpdateRes.get());
5293       if (!UpdateRes.isUsable()) {
5294         IsCorrect = false;
5295         continue;
5296       }
5297       UpdateRes =
5298           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5299       if (!UpdateRes.isUsable()) {
5300         IsCorrect = false;
5301         continue;
5302       }
5303       ExprResult CounterUpdateRes =
5304           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5305       if (!CounterUpdateRes.isUsable()) {
5306         IsCorrect = false;
5307         continue;
5308       }
5309       CounterUpdateRes =
5310           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5311       if (!CounterUpdateRes.isUsable()) {
5312         IsCorrect = false;
5313         continue;
5314       }
5315       OMPIteratorHelperData &HD = Helpers.emplace_back();
5316       HD.CounterVD = CounterVD;
5317       HD.Upper = Res.get();
5318       HD.Update = UpdateRes.get();
5319       HD.CounterUpdate = CounterUpdateRes.get();
5320     }
5321   } else {
5322     Helpers.assign(ID.size(), {});
5323   }
5324   if (!IsCorrect) {
5325     // Invalidate all created iterator declarations if error is found.
5326     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5327       if (Decl *ID = D.IteratorDecl)
5328         ID->setInvalidDecl();
5329     }
5330     return ExprError();
5331   }
5332   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5333                                  LLoc, RLoc, ID, Helpers);
5334 }
5335 
5336 ExprResult
5337 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5338                                       Expr *Idx, SourceLocation RLoc) {
5339   Expr *LHSExp = Base;
5340   Expr *RHSExp = Idx;
5341 
5342   ExprValueKind VK = VK_LValue;
5343   ExprObjectKind OK = OK_Ordinary;
5344 
5345   // Per C++ core issue 1213, the result is an xvalue if either operand is
5346   // a non-lvalue array, and an lvalue otherwise.
5347   if (getLangOpts().CPlusPlus11) {
5348     for (auto *Op : {LHSExp, RHSExp}) {
5349       Op = Op->IgnoreImplicit();
5350       if (Op->getType()->isArrayType() && !Op->isLValue())
5351         VK = VK_XValue;
5352     }
5353   }
5354 
5355   // Perform default conversions.
5356   if (!LHSExp->getType()->getAs<VectorType>()) {
5357     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5358     if (Result.isInvalid())
5359       return ExprError();
5360     LHSExp = Result.get();
5361   }
5362   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5363   if (Result.isInvalid())
5364     return ExprError();
5365   RHSExp = Result.get();
5366 
5367   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5368 
5369   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5370   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5371   // in the subscript position. As a result, we need to derive the array base
5372   // and index from the expression types.
5373   Expr *BaseExpr, *IndexExpr;
5374   QualType ResultType;
5375   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5376     BaseExpr = LHSExp;
5377     IndexExpr = RHSExp;
5378     ResultType = Context.DependentTy;
5379   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5380     BaseExpr = LHSExp;
5381     IndexExpr = RHSExp;
5382     ResultType = PTy->getPointeeType();
5383   } else if (const ObjCObjectPointerType *PTy =
5384                LHSTy->getAs<ObjCObjectPointerType>()) {
5385     BaseExpr = LHSExp;
5386     IndexExpr = RHSExp;
5387 
5388     // Use custom logic if this should be the pseudo-object subscript
5389     // expression.
5390     if (!LangOpts.isSubscriptPointerArithmetic())
5391       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5392                                           nullptr);
5393 
5394     ResultType = PTy->getPointeeType();
5395   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5396      // Handle the uncommon case of "123[Ptr]".
5397     BaseExpr = RHSExp;
5398     IndexExpr = LHSExp;
5399     ResultType = PTy->getPointeeType();
5400   } else if (const ObjCObjectPointerType *PTy =
5401                RHSTy->getAs<ObjCObjectPointerType>()) {
5402      // Handle the uncommon case of "123[Ptr]".
5403     BaseExpr = RHSExp;
5404     IndexExpr = LHSExp;
5405     ResultType = PTy->getPointeeType();
5406     if (!LangOpts.isSubscriptPointerArithmetic()) {
5407       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5408         << ResultType << BaseExpr->getSourceRange();
5409       return ExprError();
5410     }
5411   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5412     BaseExpr = LHSExp;    // vectors: V[123]
5413     IndexExpr = RHSExp;
5414     // We apply C++ DR1213 to vector subscripting too.
5415     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5416       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5417       if (Materialized.isInvalid())
5418         return ExprError();
5419       LHSExp = Materialized.get();
5420     }
5421     VK = LHSExp->getValueKind();
5422     if (VK != VK_RValue)
5423       OK = OK_VectorComponent;
5424 
5425     ResultType = VTy->getElementType();
5426     QualType BaseType = BaseExpr->getType();
5427     Qualifiers BaseQuals = BaseType.getQualifiers();
5428     Qualifiers MemberQuals = ResultType.getQualifiers();
5429     Qualifiers Combined = BaseQuals + MemberQuals;
5430     if (Combined != MemberQuals)
5431       ResultType = Context.getQualifiedType(ResultType, Combined);
5432   } else if (LHSTy->isArrayType()) {
5433     // If we see an array that wasn't promoted by
5434     // DefaultFunctionArrayLvalueConversion, it must be an array that
5435     // wasn't promoted because of the C90 rule that doesn't
5436     // allow promoting non-lvalue arrays.  Warn, then
5437     // force the promotion here.
5438     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5439         << LHSExp->getSourceRange();
5440     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5441                                CK_ArrayToPointerDecay).get();
5442     LHSTy = LHSExp->getType();
5443 
5444     BaseExpr = LHSExp;
5445     IndexExpr = RHSExp;
5446     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5447   } else if (RHSTy->isArrayType()) {
5448     // Same as previous, except for 123[f().a] case
5449     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5450         << RHSExp->getSourceRange();
5451     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5452                                CK_ArrayToPointerDecay).get();
5453     RHSTy = RHSExp->getType();
5454 
5455     BaseExpr = RHSExp;
5456     IndexExpr = LHSExp;
5457     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5458   } else {
5459     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5460        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5461   }
5462   // C99 6.5.2.1p1
5463   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5464     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5465                      << IndexExpr->getSourceRange());
5466 
5467   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5468        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5469          && !IndexExpr->isTypeDependent())
5470     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5471 
5472   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5473   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5474   // type. Note that Functions are not objects, and that (in C99 parlance)
5475   // incomplete types are not object types.
5476   if (ResultType->isFunctionType()) {
5477     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5478         << ResultType << BaseExpr->getSourceRange();
5479     return ExprError();
5480   }
5481 
5482   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5483     // GNU extension: subscripting on pointer to void
5484     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5485       << BaseExpr->getSourceRange();
5486 
5487     // C forbids expressions of unqualified void type from being l-values.
5488     // See IsCForbiddenLValueType.
5489     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5490   } else if (!ResultType->isDependentType() &&
5491              RequireCompleteSizedType(
5492                  LLoc, ResultType,
5493                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5494     return ExprError();
5495 
5496   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5497          !ResultType.isCForbiddenLValueType());
5498 
5499   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5500       FunctionScopes.size() > 1) {
5501     if (auto *TT =
5502             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5503       for (auto I = FunctionScopes.rbegin(),
5504                 E = std::prev(FunctionScopes.rend());
5505            I != E; ++I) {
5506         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5507         if (CSI == nullptr)
5508           break;
5509         DeclContext *DC = nullptr;
5510         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5511           DC = LSI->CallOperator;
5512         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5513           DC = CRSI->TheCapturedDecl;
5514         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5515           DC = BSI->TheDecl;
5516         if (DC) {
5517           if (DC->containsDecl(TT->getDecl()))
5518             break;
5519           captureVariablyModifiedType(
5520               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5521         }
5522       }
5523     }
5524   }
5525 
5526   return new (Context)
5527       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5528 }
5529 
5530 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5531                                   ParmVarDecl *Param) {
5532   if (Param->hasUnparsedDefaultArg()) {
5533     // If we've already cleared out the location for the default argument,
5534     // that means we're parsing it right now.
5535     if (!UnparsedDefaultArgLocs.count(Param)) {
5536       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5537       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5538       Param->setInvalidDecl();
5539       return true;
5540     }
5541 
5542     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5543         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5544     Diag(UnparsedDefaultArgLocs[Param],
5545          diag::note_default_argument_declared_here);
5546     return true;
5547   }
5548 
5549   if (Param->hasUninstantiatedDefaultArg() &&
5550       InstantiateDefaultArgument(CallLoc, FD, Param))
5551     return true;
5552 
5553   assert(Param->hasInit() && "default argument but no initializer?");
5554 
5555   // If the default expression creates temporaries, we need to
5556   // push them to the current stack of expression temporaries so they'll
5557   // be properly destroyed.
5558   // FIXME: We should really be rebuilding the default argument with new
5559   // bound temporaries; see the comment in PR5810.
5560   // We don't need to do that with block decls, though, because
5561   // blocks in default argument expression can never capture anything.
5562   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5563     // Set the "needs cleanups" bit regardless of whether there are
5564     // any explicit objects.
5565     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5566 
5567     // Append all the objects to the cleanup list.  Right now, this
5568     // should always be a no-op, because blocks in default argument
5569     // expressions should never be able to capture anything.
5570     assert(!Init->getNumObjects() &&
5571            "default argument expression has capturing blocks?");
5572   }
5573 
5574   // We already type-checked the argument, so we know it works.
5575   // Just mark all of the declarations in this potentially-evaluated expression
5576   // as being "referenced".
5577   EnterExpressionEvaluationContext EvalContext(
5578       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5579   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5580                                    /*SkipLocalVariables=*/true);
5581   return false;
5582 }
5583 
5584 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5585                                         FunctionDecl *FD, ParmVarDecl *Param) {
5586   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5587   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5588     return ExprError();
5589   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5590 }
5591 
5592 Sema::VariadicCallType
5593 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5594                           Expr *Fn) {
5595   if (Proto && Proto->isVariadic()) {
5596     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5597       return VariadicConstructor;
5598     else if (Fn && Fn->getType()->isBlockPointerType())
5599       return VariadicBlock;
5600     else if (FDecl) {
5601       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5602         if (Method->isInstance())
5603           return VariadicMethod;
5604     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5605       return VariadicMethod;
5606     return VariadicFunction;
5607   }
5608   return VariadicDoesNotApply;
5609 }
5610 
5611 namespace {
5612 class FunctionCallCCC final : public FunctionCallFilterCCC {
5613 public:
5614   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5615                   unsigned NumArgs, MemberExpr *ME)
5616       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5617         FunctionName(FuncName) {}
5618 
5619   bool ValidateCandidate(const TypoCorrection &candidate) override {
5620     if (!candidate.getCorrectionSpecifier() ||
5621         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5622       return false;
5623     }
5624 
5625     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5626   }
5627 
5628   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5629     return std::make_unique<FunctionCallCCC>(*this);
5630   }
5631 
5632 private:
5633   const IdentifierInfo *const FunctionName;
5634 };
5635 }
5636 
5637 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5638                                                FunctionDecl *FDecl,
5639                                                ArrayRef<Expr *> Args) {
5640   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5641   DeclarationName FuncName = FDecl->getDeclName();
5642   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5643 
5644   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5645   if (TypoCorrection Corrected = S.CorrectTypo(
5646           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5647           S.getScopeForContext(S.CurContext), nullptr, CCC,
5648           Sema::CTK_ErrorRecovery)) {
5649     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5650       if (Corrected.isOverloaded()) {
5651         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5652         OverloadCandidateSet::iterator Best;
5653         for (NamedDecl *CD : Corrected) {
5654           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5655             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5656                                    OCS);
5657         }
5658         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5659         case OR_Success:
5660           ND = Best->FoundDecl;
5661           Corrected.setCorrectionDecl(ND);
5662           break;
5663         default:
5664           break;
5665         }
5666       }
5667       ND = ND->getUnderlyingDecl();
5668       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5669         return Corrected;
5670     }
5671   }
5672   return TypoCorrection();
5673 }
5674 
5675 /// ConvertArgumentsForCall - Converts the arguments specified in
5676 /// Args/NumArgs to the parameter types of the function FDecl with
5677 /// function prototype Proto. Call is the call expression itself, and
5678 /// Fn is the function expression. For a C++ member function, this
5679 /// routine does not attempt to convert the object argument. Returns
5680 /// true if the call is ill-formed.
5681 bool
5682 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5683                               FunctionDecl *FDecl,
5684                               const FunctionProtoType *Proto,
5685                               ArrayRef<Expr *> Args,
5686                               SourceLocation RParenLoc,
5687                               bool IsExecConfig) {
5688   // Bail out early if calling a builtin with custom typechecking.
5689   if (FDecl)
5690     if (unsigned ID = FDecl->getBuiltinID())
5691       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5692         return false;
5693 
5694   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5695   // assignment, to the types of the corresponding parameter, ...
5696   unsigned NumParams = Proto->getNumParams();
5697   bool Invalid = false;
5698   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5699   unsigned FnKind = Fn->getType()->isBlockPointerType()
5700                        ? 1 /* block */
5701                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5702                                        : 0 /* function */);
5703 
5704   // If too few arguments are available (and we don't have default
5705   // arguments for the remaining parameters), don't make the call.
5706   if (Args.size() < NumParams) {
5707     if (Args.size() < MinArgs) {
5708       TypoCorrection TC;
5709       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5710         unsigned diag_id =
5711             MinArgs == NumParams && !Proto->isVariadic()
5712                 ? diag::err_typecheck_call_too_few_args_suggest
5713                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5714         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5715                                         << static_cast<unsigned>(Args.size())
5716                                         << TC.getCorrectionRange());
5717       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5718         Diag(RParenLoc,
5719              MinArgs == NumParams && !Proto->isVariadic()
5720                  ? diag::err_typecheck_call_too_few_args_one
5721                  : diag::err_typecheck_call_too_few_args_at_least_one)
5722             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5723       else
5724         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5725                             ? diag::err_typecheck_call_too_few_args
5726                             : diag::err_typecheck_call_too_few_args_at_least)
5727             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5728             << Fn->getSourceRange();
5729 
5730       // Emit the location of the prototype.
5731       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5732         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5733 
5734       return true;
5735     }
5736     // We reserve space for the default arguments when we create
5737     // the call expression, before calling ConvertArgumentsForCall.
5738     assert((Call->getNumArgs() == NumParams) &&
5739            "We should have reserved space for the default arguments before!");
5740   }
5741 
5742   // If too many are passed and not variadic, error on the extras and drop
5743   // them.
5744   if (Args.size() > NumParams) {
5745     if (!Proto->isVariadic()) {
5746       TypoCorrection TC;
5747       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5748         unsigned diag_id =
5749             MinArgs == NumParams && !Proto->isVariadic()
5750                 ? diag::err_typecheck_call_too_many_args_suggest
5751                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5752         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5753                                         << static_cast<unsigned>(Args.size())
5754                                         << TC.getCorrectionRange());
5755       } else if (NumParams == 1 && FDecl &&
5756                  FDecl->getParamDecl(0)->getDeclName())
5757         Diag(Args[NumParams]->getBeginLoc(),
5758              MinArgs == NumParams
5759                  ? diag::err_typecheck_call_too_many_args_one
5760                  : diag::err_typecheck_call_too_many_args_at_most_one)
5761             << FnKind << FDecl->getParamDecl(0)
5762             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5763             << SourceRange(Args[NumParams]->getBeginLoc(),
5764                            Args.back()->getEndLoc());
5765       else
5766         Diag(Args[NumParams]->getBeginLoc(),
5767              MinArgs == NumParams
5768                  ? diag::err_typecheck_call_too_many_args
5769                  : diag::err_typecheck_call_too_many_args_at_most)
5770             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5771             << Fn->getSourceRange()
5772             << SourceRange(Args[NumParams]->getBeginLoc(),
5773                            Args.back()->getEndLoc());
5774 
5775       // Emit the location of the prototype.
5776       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5777         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5778 
5779       // This deletes the extra arguments.
5780       Call->shrinkNumArgs(NumParams);
5781       return true;
5782     }
5783   }
5784   SmallVector<Expr *, 8> AllArgs;
5785   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5786 
5787   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5788                                    AllArgs, CallType);
5789   if (Invalid)
5790     return true;
5791   unsigned TotalNumArgs = AllArgs.size();
5792   for (unsigned i = 0; i < TotalNumArgs; ++i)
5793     Call->setArg(i, AllArgs[i]);
5794 
5795   return false;
5796 }
5797 
5798 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5799                                   const FunctionProtoType *Proto,
5800                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5801                                   SmallVectorImpl<Expr *> &AllArgs,
5802                                   VariadicCallType CallType, bool AllowExplicit,
5803                                   bool IsListInitialization) {
5804   unsigned NumParams = Proto->getNumParams();
5805   bool Invalid = false;
5806   size_t ArgIx = 0;
5807   // Continue to check argument types (even if we have too few/many args).
5808   for (unsigned i = FirstParam; i < NumParams; i++) {
5809     QualType ProtoArgType = Proto->getParamType(i);
5810 
5811     Expr *Arg;
5812     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5813     if (ArgIx < Args.size()) {
5814       Arg = Args[ArgIx++];
5815 
5816       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5817                               diag::err_call_incomplete_argument, Arg))
5818         return true;
5819 
5820       // Strip the unbridged-cast placeholder expression off, if applicable.
5821       bool CFAudited = false;
5822       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5823           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5824           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5825         Arg = stripARCUnbridgedCast(Arg);
5826       else if (getLangOpts().ObjCAutoRefCount &&
5827                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5828                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5829         CFAudited = true;
5830 
5831       if (Proto->getExtParameterInfo(i).isNoEscape())
5832         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5833           BE->getBlockDecl()->setDoesNotEscape();
5834 
5835       InitializedEntity Entity =
5836           Param ? InitializedEntity::InitializeParameter(Context, Param,
5837                                                          ProtoArgType)
5838                 : InitializedEntity::InitializeParameter(
5839                       Context, ProtoArgType, Proto->isParamConsumed(i));
5840 
5841       // Remember that parameter belongs to a CF audited API.
5842       if (CFAudited)
5843         Entity.setParameterCFAudited();
5844 
5845       ExprResult ArgE = PerformCopyInitialization(
5846           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5847       if (ArgE.isInvalid())
5848         return true;
5849 
5850       Arg = ArgE.getAs<Expr>();
5851     } else {
5852       assert(Param && "can't use default arguments without a known callee");
5853 
5854       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5855       if (ArgExpr.isInvalid())
5856         return true;
5857 
5858       Arg = ArgExpr.getAs<Expr>();
5859     }
5860 
5861     // Check for array bounds violations for each argument to the call. This
5862     // check only triggers warnings when the argument isn't a more complex Expr
5863     // with its own checking, such as a BinaryOperator.
5864     CheckArrayAccess(Arg);
5865 
5866     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5867     CheckStaticArrayArgument(CallLoc, Param, Arg);
5868 
5869     AllArgs.push_back(Arg);
5870   }
5871 
5872   // If this is a variadic call, handle args passed through "...".
5873   if (CallType != VariadicDoesNotApply) {
5874     // Assume that extern "C" functions with variadic arguments that
5875     // return __unknown_anytype aren't *really* variadic.
5876     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5877         FDecl->isExternC()) {
5878       for (Expr *A : Args.slice(ArgIx)) {
5879         QualType paramType; // ignored
5880         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5881         Invalid |= arg.isInvalid();
5882         AllArgs.push_back(arg.get());
5883       }
5884 
5885     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5886     } else {
5887       for (Expr *A : Args.slice(ArgIx)) {
5888         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5889         Invalid |= Arg.isInvalid();
5890         AllArgs.push_back(Arg.get());
5891       }
5892     }
5893 
5894     // Check for array bounds violations.
5895     for (Expr *A : Args.slice(ArgIx))
5896       CheckArrayAccess(A);
5897   }
5898   return Invalid;
5899 }
5900 
5901 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5902   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5903   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5904     TL = DTL.getOriginalLoc();
5905   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5906     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5907       << ATL.getLocalSourceRange();
5908 }
5909 
5910 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5911 /// array parameter, check that it is non-null, and that if it is formed by
5912 /// array-to-pointer decay, the underlying array is sufficiently large.
5913 ///
5914 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5915 /// array type derivation, then for each call to the function, the value of the
5916 /// corresponding actual argument shall provide access to the first element of
5917 /// an array with at least as many elements as specified by the size expression.
5918 void
5919 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5920                                ParmVarDecl *Param,
5921                                const Expr *ArgExpr) {
5922   // Static array parameters are not supported in C++.
5923   if (!Param || getLangOpts().CPlusPlus)
5924     return;
5925 
5926   QualType OrigTy = Param->getOriginalType();
5927 
5928   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5929   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5930     return;
5931 
5932   if (ArgExpr->isNullPointerConstant(Context,
5933                                      Expr::NPC_NeverValueDependent)) {
5934     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5935     DiagnoseCalleeStaticArrayParam(*this, Param);
5936     return;
5937   }
5938 
5939   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5940   if (!CAT)
5941     return;
5942 
5943   const ConstantArrayType *ArgCAT =
5944     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5945   if (!ArgCAT)
5946     return;
5947 
5948   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5949                                              ArgCAT->getElementType())) {
5950     if (ArgCAT->getSize().ult(CAT->getSize())) {
5951       Diag(CallLoc, diag::warn_static_array_too_small)
5952           << ArgExpr->getSourceRange()
5953           << (unsigned)ArgCAT->getSize().getZExtValue()
5954           << (unsigned)CAT->getSize().getZExtValue() << 0;
5955       DiagnoseCalleeStaticArrayParam(*this, Param);
5956     }
5957     return;
5958   }
5959 
5960   Optional<CharUnits> ArgSize =
5961       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5962   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5963   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5964     Diag(CallLoc, diag::warn_static_array_too_small)
5965         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5966         << (unsigned)ParmSize->getQuantity() << 1;
5967     DiagnoseCalleeStaticArrayParam(*this, Param);
5968   }
5969 }
5970 
5971 /// Given a function expression of unknown-any type, try to rebuild it
5972 /// to have a function type.
5973 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5974 
5975 /// Is the given type a placeholder that we need to lower out
5976 /// immediately during argument processing?
5977 static bool isPlaceholderToRemoveAsArg(QualType type) {
5978   // Placeholders are never sugared.
5979   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5980   if (!placeholder) return false;
5981 
5982   switch (placeholder->getKind()) {
5983   // Ignore all the non-placeholder types.
5984 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5985   case BuiltinType::Id:
5986 #include "clang/Basic/OpenCLImageTypes.def"
5987 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5988   case BuiltinType::Id:
5989 #include "clang/Basic/OpenCLExtensionTypes.def"
5990   // In practice we'll never use this, since all SVE types are sugared
5991   // via TypedefTypes rather than exposed directly as BuiltinTypes.
5992 #define SVE_TYPE(Name, Id, SingletonId) \
5993   case BuiltinType::Id:
5994 #include "clang/Basic/AArch64SVEACLETypes.def"
5995 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \
5996   case BuiltinType::Id:
5997 #include "clang/Basic/PPCTypes.def"
5998 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5999 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6000 #include "clang/AST/BuiltinTypes.def"
6001     return false;
6002 
6003   // We cannot lower out overload sets; they might validly be resolved
6004   // by the call machinery.
6005   case BuiltinType::Overload:
6006     return false;
6007 
6008   // Unbridged casts in ARC can be handled in some call positions and
6009   // should be left in place.
6010   case BuiltinType::ARCUnbridgedCast:
6011     return false;
6012 
6013   // Pseudo-objects should be converted as soon as possible.
6014   case BuiltinType::PseudoObject:
6015     return true;
6016 
6017   // The debugger mode could theoretically but currently does not try
6018   // to resolve unknown-typed arguments based on known parameter types.
6019   case BuiltinType::UnknownAny:
6020     return true;
6021 
6022   // These are always invalid as call arguments and should be reported.
6023   case BuiltinType::BoundMember:
6024   case BuiltinType::BuiltinFn:
6025   case BuiltinType::IncompleteMatrixIdx:
6026   case BuiltinType::OMPArraySection:
6027   case BuiltinType::OMPArrayShaping:
6028   case BuiltinType::OMPIterator:
6029     return true;
6030 
6031   }
6032   llvm_unreachable("bad builtin type kind");
6033 }
6034 
6035 /// Check an argument list for placeholders that we won't try to
6036 /// handle later.
6037 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6038   // Apply this processing to all the arguments at once instead of
6039   // dying at the first failure.
6040   bool hasInvalid = false;
6041   for (size_t i = 0, e = args.size(); i != e; i++) {
6042     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6043       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6044       if (result.isInvalid()) hasInvalid = true;
6045       else args[i] = result.get();
6046     }
6047   }
6048   return hasInvalid;
6049 }
6050 
6051 /// If a builtin function has a pointer argument with no explicit address
6052 /// space, then it should be able to accept a pointer to any address
6053 /// space as input.  In order to do this, we need to replace the
6054 /// standard builtin declaration with one that uses the same address space
6055 /// as the call.
6056 ///
6057 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6058 ///                  it does not contain any pointer arguments without
6059 ///                  an address space qualifer.  Otherwise the rewritten
6060 ///                  FunctionDecl is returned.
6061 /// TODO: Handle pointer return types.
6062 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6063                                                 FunctionDecl *FDecl,
6064                                                 MultiExprArg ArgExprs) {
6065 
6066   QualType DeclType = FDecl->getType();
6067   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6068 
6069   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6070       ArgExprs.size() < FT->getNumParams())
6071     return nullptr;
6072 
6073   bool NeedsNewDecl = false;
6074   unsigned i = 0;
6075   SmallVector<QualType, 8> OverloadParams;
6076 
6077   for (QualType ParamType : FT->param_types()) {
6078 
6079     // Convert array arguments to pointer to simplify type lookup.
6080     ExprResult ArgRes =
6081         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6082     if (ArgRes.isInvalid())
6083       return nullptr;
6084     Expr *Arg = ArgRes.get();
6085     QualType ArgType = Arg->getType();
6086     if (!ParamType->isPointerType() ||
6087         ParamType.hasAddressSpace() ||
6088         !ArgType->isPointerType() ||
6089         !ArgType->getPointeeType().hasAddressSpace()) {
6090       OverloadParams.push_back(ParamType);
6091       continue;
6092     }
6093 
6094     QualType PointeeType = ParamType->getPointeeType();
6095     if (PointeeType.hasAddressSpace())
6096       continue;
6097 
6098     NeedsNewDecl = true;
6099     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6100 
6101     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6102     OverloadParams.push_back(Context.getPointerType(PointeeType));
6103   }
6104 
6105   if (!NeedsNewDecl)
6106     return nullptr;
6107 
6108   FunctionProtoType::ExtProtoInfo EPI;
6109   EPI.Variadic = FT->isVariadic();
6110   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6111                                                 OverloadParams, EPI);
6112   DeclContext *Parent = FDecl->getParent();
6113   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6114                                                     FDecl->getLocation(),
6115                                                     FDecl->getLocation(),
6116                                                     FDecl->getIdentifier(),
6117                                                     OverloadTy,
6118                                                     /*TInfo=*/nullptr,
6119                                                     SC_Extern, false,
6120                                                     /*hasPrototype=*/true);
6121   SmallVector<ParmVarDecl*, 16> Params;
6122   FT = cast<FunctionProtoType>(OverloadTy);
6123   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6124     QualType ParamType = FT->getParamType(i);
6125     ParmVarDecl *Parm =
6126         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6127                                 SourceLocation(), nullptr, ParamType,
6128                                 /*TInfo=*/nullptr, SC_None, nullptr);
6129     Parm->setScopeInfo(0, i);
6130     Params.push_back(Parm);
6131   }
6132   OverloadDecl->setParams(Params);
6133   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6134   return OverloadDecl;
6135 }
6136 
6137 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6138                                     FunctionDecl *Callee,
6139                                     MultiExprArg ArgExprs) {
6140   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6141   // similar attributes) really don't like it when functions are called with an
6142   // invalid number of args.
6143   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6144                          /*PartialOverloading=*/false) &&
6145       !Callee->isVariadic())
6146     return;
6147   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6148     return;
6149 
6150   if (const EnableIfAttr *Attr =
6151           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6152     S.Diag(Fn->getBeginLoc(),
6153            isa<CXXMethodDecl>(Callee)
6154                ? diag::err_ovl_no_viable_member_function_in_call
6155                : diag::err_ovl_no_viable_function_in_call)
6156         << Callee << Callee->getSourceRange();
6157     S.Diag(Callee->getLocation(),
6158            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6159         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6160     return;
6161   }
6162 }
6163 
6164 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6165     const UnresolvedMemberExpr *const UME, Sema &S) {
6166 
6167   const auto GetFunctionLevelDCIfCXXClass =
6168       [](Sema &S) -> const CXXRecordDecl * {
6169     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6170     if (!DC || !DC->getParent())
6171       return nullptr;
6172 
6173     // If the call to some member function was made from within a member
6174     // function body 'M' return return 'M's parent.
6175     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6176       return MD->getParent()->getCanonicalDecl();
6177     // else the call was made from within a default member initializer of a
6178     // class, so return the class.
6179     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6180       return RD->getCanonicalDecl();
6181     return nullptr;
6182   };
6183   // If our DeclContext is neither a member function nor a class (in the
6184   // case of a lambda in a default member initializer), we can't have an
6185   // enclosing 'this'.
6186 
6187   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6188   if (!CurParentClass)
6189     return false;
6190 
6191   // The naming class for implicit member functions call is the class in which
6192   // name lookup starts.
6193   const CXXRecordDecl *const NamingClass =
6194       UME->getNamingClass()->getCanonicalDecl();
6195   assert(NamingClass && "Must have naming class even for implicit access");
6196 
6197   // If the unresolved member functions were found in a 'naming class' that is
6198   // related (either the same or derived from) to the class that contains the
6199   // member function that itself contained the implicit member access.
6200 
6201   return CurParentClass == NamingClass ||
6202          CurParentClass->isDerivedFrom(NamingClass);
6203 }
6204 
6205 static void
6206 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6207     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6208 
6209   if (!UME)
6210     return;
6211 
6212   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6213   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6214   // already been captured, or if this is an implicit member function call (if
6215   // it isn't, an attempt to capture 'this' should already have been made).
6216   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6217       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6218     return;
6219 
6220   // Check if the naming class in which the unresolved members were found is
6221   // related (same as or is a base of) to the enclosing class.
6222 
6223   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6224     return;
6225 
6226 
6227   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6228   // If the enclosing function is not dependent, then this lambda is
6229   // capture ready, so if we can capture this, do so.
6230   if (!EnclosingFunctionCtx->isDependentContext()) {
6231     // If the current lambda and all enclosing lambdas can capture 'this' -
6232     // then go ahead and capture 'this' (since our unresolved overload set
6233     // contains at least one non-static member function).
6234     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6235       S.CheckCXXThisCapture(CallLoc);
6236   } else if (S.CurContext->isDependentContext()) {
6237     // ... since this is an implicit member reference, that might potentially
6238     // involve a 'this' capture, mark 'this' for potential capture in
6239     // enclosing lambdas.
6240     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6241       CurLSI->addPotentialThisCapture(CallLoc);
6242   }
6243 }
6244 
6245 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6246                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6247                                Expr *ExecConfig) {
6248   ExprResult Call =
6249       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6250   if (Call.isInvalid())
6251     return Call;
6252 
6253   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6254   // language modes.
6255   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6256     if (ULE->hasExplicitTemplateArgs() &&
6257         ULE->decls_begin() == ULE->decls_end()) {
6258       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6259                                  ? diag::warn_cxx17_compat_adl_only_template_id
6260                                  : diag::ext_adl_only_template_id)
6261           << ULE->getName();
6262     }
6263   }
6264 
6265   if (LangOpts.OpenMP)
6266     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6267                            ExecConfig);
6268 
6269   return Call;
6270 }
6271 
6272 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6273 /// This provides the location of the left/right parens and a list of comma
6274 /// locations.
6275 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6276                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6277                                Expr *ExecConfig, bool IsExecConfig) {
6278   // Since this might be a postfix expression, get rid of ParenListExprs.
6279   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6280   if (Result.isInvalid()) return ExprError();
6281   Fn = Result.get();
6282 
6283   if (checkArgsForPlaceholders(*this, ArgExprs))
6284     return ExprError();
6285 
6286   if (getLangOpts().CPlusPlus) {
6287     // If this is a pseudo-destructor expression, build the call immediately.
6288     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6289       if (!ArgExprs.empty()) {
6290         // Pseudo-destructor calls should not have any arguments.
6291         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6292             << FixItHint::CreateRemoval(
6293                    SourceRange(ArgExprs.front()->getBeginLoc(),
6294                                ArgExprs.back()->getEndLoc()));
6295       }
6296 
6297       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6298                               VK_RValue, RParenLoc, CurFPFeatureOverrides());
6299     }
6300     if (Fn->getType() == Context.PseudoObjectTy) {
6301       ExprResult result = CheckPlaceholderExpr(Fn);
6302       if (result.isInvalid()) return ExprError();
6303       Fn = result.get();
6304     }
6305 
6306     // Determine whether this is a dependent call inside a C++ template,
6307     // in which case we won't do any semantic analysis now.
6308     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6309       if (ExecConfig) {
6310         return CUDAKernelCallExpr::Create(
6311             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6312             Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides());
6313       } else {
6314 
6315         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6316             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6317             Fn->getBeginLoc());
6318 
6319         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6320                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6321       }
6322     }
6323 
6324     // Determine whether this is a call to an object (C++ [over.call.object]).
6325     if (Fn->getType()->isRecordType())
6326       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6327                                           RParenLoc);
6328 
6329     if (Fn->getType() == Context.UnknownAnyTy) {
6330       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6331       if (result.isInvalid()) return ExprError();
6332       Fn = result.get();
6333     }
6334 
6335     if (Fn->getType() == Context.BoundMemberTy) {
6336       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6337                                        RParenLoc);
6338     }
6339   }
6340 
6341   // Check for overloaded calls.  This can happen even in C due to extensions.
6342   if (Fn->getType() == Context.OverloadTy) {
6343     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6344 
6345     // We aren't supposed to apply this logic if there's an '&' involved.
6346     if (!find.HasFormOfMemberPointer) {
6347       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6348         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6349                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6350       OverloadExpr *ovl = find.Expression;
6351       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6352         return BuildOverloadedCallExpr(
6353             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6354             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6355       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6356                                        RParenLoc);
6357     }
6358   }
6359 
6360   // If we're directly calling a function, get the appropriate declaration.
6361   if (Fn->getType() == Context.UnknownAnyTy) {
6362     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6363     if (result.isInvalid()) return ExprError();
6364     Fn = result.get();
6365   }
6366 
6367   Expr *NakedFn = Fn->IgnoreParens();
6368 
6369   bool CallingNDeclIndirectly = false;
6370   NamedDecl *NDecl = nullptr;
6371   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6372     if (UnOp->getOpcode() == UO_AddrOf) {
6373       CallingNDeclIndirectly = true;
6374       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6375     }
6376   }
6377 
6378   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6379     NDecl = DRE->getDecl();
6380 
6381     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6382     if (FDecl && FDecl->getBuiltinID()) {
6383       // Rewrite the function decl for this builtin by replacing parameters
6384       // with no explicit address space with the address space of the arguments
6385       // in ArgExprs.
6386       if ((FDecl =
6387                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6388         NDecl = FDecl;
6389         Fn = DeclRefExpr::Create(
6390             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6391             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6392             nullptr, DRE->isNonOdrUse());
6393       }
6394     }
6395   } else if (isa<MemberExpr>(NakedFn))
6396     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6397 
6398   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6399     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6400                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6401       return ExprError();
6402 
6403     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6404       return ExprError();
6405 
6406     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6407   }
6408 
6409   if (Context.isDependenceAllowed() &&
6410       (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6411     assert(!getLangOpts().CPlusPlus);
6412     assert((Fn->containsErrors() ||
6413             llvm::any_of(ArgExprs,
6414                          [](clang::Expr *E) { return E->containsErrors(); })) &&
6415            "should only occur in error-recovery path.");
6416     QualType ReturnType =
6417         llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6418             ? dyn_cast<FunctionDecl>(NDecl)->getCallResultType()
6419             : Context.DependentTy;
6420     return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6421                             Expr::getValueKindForType(ReturnType), RParenLoc,
6422                             CurFPFeatureOverrides());
6423   }
6424   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6425                                ExecConfig, IsExecConfig);
6426 }
6427 
6428 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6429 ///
6430 /// __builtin_astype( value, dst type )
6431 ///
6432 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6433                                  SourceLocation BuiltinLoc,
6434                                  SourceLocation RParenLoc) {
6435   ExprValueKind VK = VK_RValue;
6436   ExprObjectKind OK = OK_Ordinary;
6437   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6438   QualType SrcTy = E->getType();
6439   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6440     return ExprError(Diag(BuiltinLoc,
6441                           diag::err_invalid_astype_of_different_size)
6442                      << DstTy
6443                      << SrcTy
6444                      << E->getSourceRange());
6445   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6446 }
6447 
6448 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6449 /// provided arguments.
6450 ///
6451 /// __builtin_convertvector( value, dst type )
6452 ///
6453 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6454                                         SourceLocation BuiltinLoc,
6455                                         SourceLocation RParenLoc) {
6456   TypeSourceInfo *TInfo;
6457   GetTypeFromParser(ParsedDestTy, &TInfo);
6458   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6459 }
6460 
6461 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6462 /// i.e. an expression not of \p OverloadTy.  The expression should
6463 /// unary-convert to an expression of function-pointer or
6464 /// block-pointer type.
6465 ///
6466 /// \param NDecl the declaration being called, if available
6467 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6468                                        SourceLocation LParenLoc,
6469                                        ArrayRef<Expr *> Args,
6470                                        SourceLocation RParenLoc, Expr *Config,
6471                                        bool IsExecConfig, ADLCallKind UsesADL) {
6472   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6473   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6474 
6475   // Functions with 'interrupt' attribute cannot be called directly.
6476   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6477     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6478     return ExprError();
6479   }
6480 
6481   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6482   // so there's some risk when calling out to non-interrupt handler functions
6483   // that the callee might not preserve them. This is easy to diagnose here,
6484   // but can be very challenging to debug.
6485   if (auto *Caller = getCurFunctionDecl())
6486     if (Caller->hasAttr<ARMInterruptAttr>()) {
6487       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6488       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6489         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6490     }
6491 
6492   // Promote the function operand.
6493   // We special-case function promotion here because we only allow promoting
6494   // builtin functions to function pointers in the callee of a call.
6495   ExprResult Result;
6496   QualType ResultTy;
6497   if (BuiltinID &&
6498       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6499     // Extract the return type from the (builtin) function pointer type.
6500     // FIXME Several builtins still have setType in
6501     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6502     // Builtins.def to ensure they are correct before removing setType calls.
6503     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6504     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6505     ResultTy = FDecl->getCallResultType();
6506   } else {
6507     Result = CallExprUnaryConversions(Fn);
6508     ResultTy = Context.BoolTy;
6509   }
6510   if (Result.isInvalid())
6511     return ExprError();
6512   Fn = Result.get();
6513 
6514   // Check for a valid function type, but only if it is not a builtin which
6515   // requires custom type checking. These will be handled by
6516   // CheckBuiltinFunctionCall below just after creation of the call expression.
6517   const FunctionType *FuncT = nullptr;
6518   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6519   retry:
6520     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6521       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6522       // have type pointer to function".
6523       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6524       if (!FuncT)
6525         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6526                          << Fn->getType() << Fn->getSourceRange());
6527     } else if (const BlockPointerType *BPT =
6528                    Fn->getType()->getAs<BlockPointerType>()) {
6529       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6530     } else {
6531       // Handle calls to expressions of unknown-any type.
6532       if (Fn->getType() == Context.UnknownAnyTy) {
6533         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6534         if (rewrite.isInvalid())
6535           return ExprError();
6536         Fn = rewrite.get();
6537         goto retry;
6538       }
6539 
6540       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6541                        << Fn->getType() << Fn->getSourceRange());
6542     }
6543   }
6544 
6545   // Get the number of parameters in the function prototype, if any.
6546   // We will allocate space for max(Args.size(), NumParams) arguments
6547   // in the call expression.
6548   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6549   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6550 
6551   CallExpr *TheCall;
6552   if (Config) {
6553     assert(UsesADL == ADLCallKind::NotADL &&
6554            "CUDAKernelCallExpr should not use ADL");
6555     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6556                                          Args, ResultTy, VK_RValue, RParenLoc,
6557                                          CurFPFeatureOverrides(), NumParams);
6558   } else {
6559     TheCall =
6560         CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6561                          CurFPFeatureOverrides(), NumParams, UsesADL);
6562   }
6563 
6564   if (!Context.isDependenceAllowed()) {
6565     // Forget about the nulled arguments since typo correction
6566     // do not handle them well.
6567     TheCall->shrinkNumArgs(Args.size());
6568     // C cannot always handle TypoExpr nodes in builtin calls and direct
6569     // function calls as their argument checking don't necessarily handle
6570     // dependent types properly, so make sure any TypoExprs have been
6571     // dealt with.
6572     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6573     if (!Result.isUsable()) return ExprError();
6574     CallExpr *TheOldCall = TheCall;
6575     TheCall = dyn_cast<CallExpr>(Result.get());
6576     bool CorrectedTypos = TheCall != TheOldCall;
6577     if (!TheCall) return Result;
6578     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6579 
6580     // A new call expression node was created if some typos were corrected.
6581     // However it may not have been constructed with enough storage. In this
6582     // case, rebuild the node with enough storage. The waste of space is
6583     // immaterial since this only happens when some typos were corrected.
6584     if (CorrectedTypos && Args.size() < NumParams) {
6585       if (Config)
6586         TheCall = CUDAKernelCallExpr::Create(
6587             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6588             RParenLoc, CurFPFeatureOverrides(), NumParams);
6589       else
6590         TheCall =
6591             CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6592                              CurFPFeatureOverrides(), NumParams, UsesADL);
6593     }
6594     // We can now handle the nulled arguments for the default arguments.
6595     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6596   }
6597 
6598   // Bail out early if calling a builtin with custom type checking.
6599   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6600     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6601 
6602   if (getLangOpts().CUDA) {
6603     if (Config) {
6604       // CUDA: Kernel calls must be to global functions
6605       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6606         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6607             << FDecl << Fn->getSourceRange());
6608 
6609       // CUDA: Kernel function must have 'void' return type
6610       if (!FuncT->getReturnType()->isVoidType() &&
6611           !FuncT->getReturnType()->getAs<AutoType>() &&
6612           !FuncT->getReturnType()->isInstantiationDependentType())
6613         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6614             << Fn->getType() << Fn->getSourceRange());
6615     } else {
6616       // CUDA: Calls to global functions must be configured
6617       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6618         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6619             << FDecl << Fn->getSourceRange());
6620     }
6621   }
6622 
6623   // Check for a valid return type
6624   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6625                           FDecl))
6626     return ExprError();
6627 
6628   // We know the result type of the call, set it.
6629   TheCall->setType(FuncT->getCallResultType(Context));
6630   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6631 
6632   if (Proto) {
6633     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6634                                 IsExecConfig))
6635       return ExprError();
6636   } else {
6637     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6638 
6639     if (FDecl) {
6640       // Check if we have too few/too many template arguments, based
6641       // on our knowledge of the function definition.
6642       const FunctionDecl *Def = nullptr;
6643       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6644         Proto = Def->getType()->getAs<FunctionProtoType>();
6645        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6646           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6647           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6648       }
6649 
6650       // If the function we're calling isn't a function prototype, but we have
6651       // a function prototype from a prior declaratiom, use that prototype.
6652       if (!FDecl->hasPrototype())
6653         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6654     }
6655 
6656     // Promote the arguments (C99 6.5.2.2p6).
6657     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6658       Expr *Arg = Args[i];
6659 
6660       if (Proto && i < Proto->getNumParams()) {
6661         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6662             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6663         ExprResult ArgE =
6664             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6665         if (ArgE.isInvalid())
6666           return true;
6667 
6668         Arg = ArgE.getAs<Expr>();
6669 
6670       } else {
6671         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6672 
6673         if (ArgE.isInvalid())
6674           return true;
6675 
6676         Arg = ArgE.getAs<Expr>();
6677       }
6678 
6679       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6680                               diag::err_call_incomplete_argument, Arg))
6681         return ExprError();
6682 
6683       TheCall->setArg(i, Arg);
6684     }
6685   }
6686 
6687   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6688     if (!Method->isStatic())
6689       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6690         << Fn->getSourceRange());
6691 
6692   // Check for sentinels
6693   if (NDecl)
6694     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6695 
6696   // Warn for unions passing across security boundary (CMSE).
6697   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6698     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6699       if (const auto *RT =
6700               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6701         if (RT->getDecl()->isOrContainsUnion())
6702           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6703               << 0 << i;
6704       }
6705     }
6706   }
6707 
6708   // Do special checking on direct calls to functions.
6709   if (FDecl) {
6710     if (CheckFunctionCall(FDecl, TheCall, Proto))
6711       return ExprError();
6712 
6713     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6714 
6715     if (BuiltinID)
6716       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6717   } else if (NDecl) {
6718     if (CheckPointerCall(NDecl, TheCall, Proto))
6719       return ExprError();
6720   } else {
6721     if (CheckOtherCall(TheCall, Proto))
6722       return ExprError();
6723   }
6724 
6725   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6726 }
6727 
6728 ExprResult
6729 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6730                            SourceLocation RParenLoc, Expr *InitExpr) {
6731   assert(Ty && "ActOnCompoundLiteral(): missing type");
6732   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6733 
6734   TypeSourceInfo *TInfo;
6735   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6736   if (!TInfo)
6737     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6738 
6739   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6740 }
6741 
6742 ExprResult
6743 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6744                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6745   QualType literalType = TInfo->getType();
6746 
6747   if (literalType->isArrayType()) {
6748     if (RequireCompleteSizedType(
6749             LParenLoc, Context.getBaseElementType(literalType),
6750             diag::err_array_incomplete_or_sizeless_type,
6751             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6752       return ExprError();
6753     if (literalType->isVariableArrayType())
6754       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6755         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6756   } else if (!literalType->isDependentType() &&
6757              RequireCompleteType(LParenLoc, literalType,
6758                diag::err_typecheck_decl_incomplete_type,
6759                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6760     return ExprError();
6761 
6762   InitializedEntity Entity
6763     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6764   InitializationKind Kind
6765     = InitializationKind::CreateCStyleCast(LParenLoc,
6766                                            SourceRange(LParenLoc, RParenLoc),
6767                                            /*InitList=*/true);
6768   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6769   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6770                                       &literalType);
6771   if (Result.isInvalid())
6772     return ExprError();
6773   LiteralExpr = Result.get();
6774 
6775   bool isFileScope = !CurContext->isFunctionOrMethod();
6776 
6777   // In C, compound literals are l-values for some reason.
6778   // For GCC compatibility, in C++, file-scope array compound literals with
6779   // constant initializers are also l-values, and compound literals are
6780   // otherwise prvalues.
6781   //
6782   // (GCC also treats C++ list-initialized file-scope array prvalues with
6783   // constant initializers as l-values, but that's non-conforming, so we don't
6784   // follow it there.)
6785   //
6786   // FIXME: It would be better to handle the lvalue cases as materializing and
6787   // lifetime-extending a temporary object, but our materialized temporaries
6788   // representation only supports lifetime extension from a variable, not "out
6789   // of thin air".
6790   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6791   // is bound to the result of applying array-to-pointer decay to the compound
6792   // literal.
6793   // FIXME: GCC supports compound literals of reference type, which should
6794   // obviously have a value kind derived from the kind of reference involved.
6795   ExprValueKind VK =
6796       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6797           ? VK_RValue
6798           : VK_LValue;
6799 
6800   if (isFileScope)
6801     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6802       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6803         Expr *Init = ILE->getInit(i);
6804         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6805       }
6806 
6807   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6808                                               VK, LiteralExpr, isFileScope);
6809   if (isFileScope) {
6810     if (!LiteralExpr->isTypeDependent() &&
6811         !LiteralExpr->isValueDependent() &&
6812         !literalType->isDependentType()) // C99 6.5.2.5p3
6813       if (CheckForConstantInitializer(LiteralExpr, literalType))
6814         return ExprError();
6815   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6816              literalType.getAddressSpace() != LangAS::Default) {
6817     // Embedded-C extensions to C99 6.5.2.5:
6818     //   "If the compound literal occurs inside the body of a function, the
6819     //   type name shall not be qualified by an address-space qualifier."
6820     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6821       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6822     return ExprError();
6823   }
6824 
6825   if (!isFileScope && !getLangOpts().CPlusPlus) {
6826     // Compound literals that have automatic storage duration are destroyed at
6827     // the end of the scope in C; in C++, they're just temporaries.
6828 
6829     // Emit diagnostics if it is or contains a C union type that is non-trivial
6830     // to destruct.
6831     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6832       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6833                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6834 
6835     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6836     if (literalType.isDestructedType()) {
6837       Cleanup.setExprNeedsCleanups(true);
6838       ExprCleanupObjects.push_back(E);
6839       getCurFunction()->setHasBranchProtectedScope();
6840     }
6841   }
6842 
6843   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6844       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6845     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6846                                        E->getInitializer()->getExprLoc());
6847 
6848   return MaybeBindToTemporary(E);
6849 }
6850 
6851 ExprResult
6852 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6853                     SourceLocation RBraceLoc) {
6854   // Only produce each kind of designated initialization diagnostic once.
6855   SourceLocation FirstDesignator;
6856   bool DiagnosedArrayDesignator = false;
6857   bool DiagnosedNestedDesignator = false;
6858   bool DiagnosedMixedDesignator = false;
6859 
6860   // Check that any designated initializers are syntactically valid in the
6861   // current language mode.
6862   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6863     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6864       if (FirstDesignator.isInvalid())
6865         FirstDesignator = DIE->getBeginLoc();
6866 
6867       if (!getLangOpts().CPlusPlus)
6868         break;
6869 
6870       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6871         DiagnosedNestedDesignator = true;
6872         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6873           << DIE->getDesignatorsSourceRange();
6874       }
6875 
6876       for (auto &Desig : DIE->designators()) {
6877         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6878           DiagnosedArrayDesignator = true;
6879           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6880             << Desig.getSourceRange();
6881         }
6882       }
6883 
6884       if (!DiagnosedMixedDesignator &&
6885           !isa<DesignatedInitExpr>(InitArgList[0])) {
6886         DiagnosedMixedDesignator = true;
6887         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6888           << DIE->getSourceRange();
6889         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6890           << InitArgList[0]->getSourceRange();
6891       }
6892     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6893                isa<DesignatedInitExpr>(InitArgList[0])) {
6894       DiagnosedMixedDesignator = true;
6895       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6896       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6897         << DIE->getSourceRange();
6898       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6899         << InitArgList[I]->getSourceRange();
6900     }
6901   }
6902 
6903   if (FirstDesignator.isValid()) {
6904     // Only diagnose designated initiaization as a C++20 extension if we didn't
6905     // already diagnose use of (non-C++20) C99 designator syntax.
6906     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6907         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6908       Diag(FirstDesignator, getLangOpts().CPlusPlus20
6909                                 ? diag::warn_cxx17_compat_designated_init
6910                                 : diag::ext_cxx_designated_init);
6911     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6912       Diag(FirstDesignator, diag::ext_designated_init);
6913     }
6914   }
6915 
6916   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6917 }
6918 
6919 ExprResult
6920 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6921                     SourceLocation RBraceLoc) {
6922   // Semantic analysis for initializers is done by ActOnDeclarator() and
6923   // CheckInitializer() - it requires knowledge of the object being initialized.
6924 
6925   // Immediately handle non-overload placeholders.  Overloads can be
6926   // resolved contextually, but everything else here can't.
6927   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6928     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6929       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6930 
6931       // Ignore failures; dropping the entire initializer list because
6932       // of one failure would be terrible for indexing/etc.
6933       if (result.isInvalid()) continue;
6934 
6935       InitArgList[I] = result.get();
6936     }
6937   }
6938 
6939   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6940                                                RBraceLoc);
6941   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6942   return E;
6943 }
6944 
6945 /// Do an explicit extend of the given block pointer if we're in ARC.
6946 void Sema::maybeExtendBlockObject(ExprResult &E) {
6947   assert(E.get()->getType()->isBlockPointerType());
6948   assert(E.get()->isRValue());
6949 
6950   // Only do this in an r-value context.
6951   if (!getLangOpts().ObjCAutoRefCount) return;
6952 
6953   E = ImplicitCastExpr::Create(
6954       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
6955       /*base path*/ nullptr, VK_RValue, FPOptionsOverride());
6956   Cleanup.setExprNeedsCleanups(true);
6957 }
6958 
6959 /// Prepare a conversion of the given expression to an ObjC object
6960 /// pointer type.
6961 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6962   QualType type = E.get()->getType();
6963   if (type->isObjCObjectPointerType()) {
6964     return CK_BitCast;
6965   } else if (type->isBlockPointerType()) {
6966     maybeExtendBlockObject(E);
6967     return CK_BlockPointerToObjCPointerCast;
6968   } else {
6969     assert(type->isPointerType());
6970     return CK_CPointerToObjCPointerCast;
6971   }
6972 }
6973 
6974 /// Prepares for a scalar cast, performing all the necessary stages
6975 /// except the final cast and returning the kind required.
6976 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6977   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6978   // Also, callers should have filtered out the invalid cases with
6979   // pointers.  Everything else should be possible.
6980 
6981   QualType SrcTy = Src.get()->getType();
6982   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6983     return CK_NoOp;
6984 
6985   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6986   case Type::STK_MemberPointer:
6987     llvm_unreachable("member pointer type in C");
6988 
6989   case Type::STK_CPointer:
6990   case Type::STK_BlockPointer:
6991   case Type::STK_ObjCObjectPointer:
6992     switch (DestTy->getScalarTypeKind()) {
6993     case Type::STK_CPointer: {
6994       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6995       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6996       if (SrcAS != DestAS)
6997         return CK_AddressSpaceConversion;
6998       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6999         return CK_NoOp;
7000       return CK_BitCast;
7001     }
7002     case Type::STK_BlockPointer:
7003       return (SrcKind == Type::STK_BlockPointer
7004                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7005     case Type::STK_ObjCObjectPointer:
7006       if (SrcKind == Type::STK_ObjCObjectPointer)
7007         return CK_BitCast;
7008       if (SrcKind == Type::STK_CPointer)
7009         return CK_CPointerToObjCPointerCast;
7010       maybeExtendBlockObject(Src);
7011       return CK_BlockPointerToObjCPointerCast;
7012     case Type::STK_Bool:
7013       return CK_PointerToBoolean;
7014     case Type::STK_Integral:
7015       return CK_PointerToIntegral;
7016     case Type::STK_Floating:
7017     case Type::STK_FloatingComplex:
7018     case Type::STK_IntegralComplex:
7019     case Type::STK_MemberPointer:
7020     case Type::STK_FixedPoint:
7021       llvm_unreachable("illegal cast from pointer");
7022     }
7023     llvm_unreachable("Should have returned before this");
7024 
7025   case Type::STK_FixedPoint:
7026     switch (DestTy->getScalarTypeKind()) {
7027     case Type::STK_FixedPoint:
7028       return CK_FixedPointCast;
7029     case Type::STK_Bool:
7030       return CK_FixedPointToBoolean;
7031     case Type::STK_Integral:
7032       return CK_FixedPointToIntegral;
7033     case Type::STK_Floating:
7034       return CK_FixedPointToFloating;
7035     case Type::STK_IntegralComplex:
7036     case Type::STK_FloatingComplex:
7037       Diag(Src.get()->getExprLoc(),
7038            diag::err_unimplemented_conversion_with_fixed_point_type)
7039           << DestTy;
7040       return CK_IntegralCast;
7041     case Type::STK_CPointer:
7042     case Type::STK_ObjCObjectPointer:
7043     case Type::STK_BlockPointer:
7044     case Type::STK_MemberPointer:
7045       llvm_unreachable("illegal cast to pointer type");
7046     }
7047     llvm_unreachable("Should have returned before this");
7048 
7049   case Type::STK_Bool: // casting from bool is like casting from an integer
7050   case Type::STK_Integral:
7051     switch (DestTy->getScalarTypeKind()) {
7052     case Type::STK_CPointer:
7053     case Type::STK_ObjCObjectPointer:
7054     case Type::STK_BlockPointer:
7055       if (Src.get()->isNullPointerConstant(Context,
7056                                            Expr::NPC_ValueDependentIsNull))
7057         return CK_NullToPointer;
7058       return CK_IntegralToPointer;
7059     case Type::STK_Bool:
7060       return CK_IntegralToBoolean;
7061     case Type::STK_Integral:
7062       return CK_IntegralCast;
7063     case Type::STK_Floating:
7064       return CK_IntegralToFloating;
7065     case Type::STK_IntegralComplex:
7066       Src = ImpCastExprToType(Src.get(),
7067                       DestTy->castAs<ComplexType>()->getElementType(),
7068                       CK_IntegralCast);
7069       return CK_IntegralRealToComplex;
7070     case Type::STK_FloatingComplex:
7071       Src = ImpCastExprToType(Src.get(),
7072                       DestTy->castAs<ComplexType>()->getElementType(),
7073                       CK_IntegralToFloating);
7074       return CK_FloatingRealToComplex;
7075     case Type::STK_MemberPointer:
7076       llvm_unreachable("member pointer type in C");
7077     case Type::STK_FixedPoint:
7078       return CK_IntegralToFixedPoint;
7079     }
7080     llvm_unreachable("Should have returned before this");
7081 
7082   case Type::STK_Floating:
7083     switch (DestTy->getScalarTypeKind()) {
7084     case Type::STK_Floating:
7085       return CK_FloatingCast;
7086     case Type::STK_Bool:
7087       return CK_FloatingToBoolean;
7088     case Type::STK_Integral:
7089       return CK_FloatingToIntegral;
7090     case Type::STK_FloatingComplex:
7091       Src = ImpCastExprToType(Src.get(),
7092                               DestTy->castAs<ComplexType>()->getElementType(),
7093                               CK_FloatingCast);
7094       return CK_FloatingRealToComplex;
7095     case Type::STK_IntegralComplex:
7096       Src = ImpCastExprToType(Src.get(),
7097                               DestTy->castAs<ComplexType>()->getElementType(),
7098                               CK_FloatingToIntegral);
7099       return CK_IntegralRealToComplex;
7100     case Type::STK_CPointer:
7101     case Type::STK_ObjCObjectPointer:
7102     case Type::STK_BlockPointer:
7103       llvm_unreachable("valid float->pointer cast?");
7104     case Type::STK_MemberPointer:
7105       llvm_unreachable("member pointer type in C");
7106     case Type::STK_FixedPoint:
7107       return CK_FloatingToFixedPoint;
7108     }
7109     llvm_unreachable("Should have returned before this");
7110 
7111   case Type::STK_FloatingComplex:
7112     switch (DestTy->getScalarTypeKind()) {
7113     case Type::STK_FloatingComplex:
7114       return CK_FloatingComplexCast;
7115     case Type::STK_IntegralComplex:
7116       return CK_FloatingComplexToIntegralComplex;
7117     case Type::STK_Floating: {
7118       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7119       if (Context.hasSameType(ET, DestTy))
7120         return CK_FloatingComplexToReal;
7121       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7122       return CK_FloatingCast;
7123     }
7124     case Type::STK_Bool:
7125       return CK_FloatingComplexToBoolean;
7126     case Type::STK_Integral:
7127       Src = ImpCastExprToType(Src.get(),
7128                               SrcTy->castAs<ComplexType>()->getElementType(),
7129                               CK_FloatingComplexToReal);
7130       return CK_FloatingToIntegral;
7131     case Type::STK_CPointer:
7132     case Type::STK_ObjCObjectPointer:
7133     case Type::STK_BlockPointer:
7134       llvm_unreachable("valid complex float->pointer cast?");
7135     case Type::STK_MemberPointer:
7136       llvm_unreachable("member pointer type in C");
7137     case Type::STK_FixedPoint:
7138       Diag(Src.get()->getExprLoc(),
7139            diag::err_unimplemented_conversion_with_fixed_point_type)
7140           << SrcTy;
7141       return CK_IntegralCast;
7142     }
7143     llvm_unreachable("Should have returned before this");
7144 
7145   case Type::STK_IntegralComplex:
7146     switch (DestTy->getScalarTypeKind()) {
7147     case Type::STK_FloatingComplex:
7148       return CK_IntegralComplexToFloatingComplex;
7149     case Type::STK_IntegralComplex:
7150       return CK_IntegralComplexCast;
7151     case Type::STK_Integral: {
7152       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7153       if (Context.hasSameType(ET, DestTy))
7154         return CK_IntegralComplexToReal;
7155       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7156       return CK_IntegralCast;
7157     }
7158     case Type::STK_Bool:
7159       return CK_IntegralComplexToBoolean;
7160     case Type::STK_Floating:
7161       Src = ImpCastExprToType(Src.get(),
7162                               SrcTy->castAs<ComplexType>()->getElementType(),
7163                               CK_IntegralComplexToReal);
7164       return CK_IntegralToFloating;
7165     case Type::STK_CPointer:
7166     case Type::STK_ObjCObjectPointer:
7167     case Type::STK_BlockPointer:
7168       llvm_unreachable("valid complex int->pointer cast?");
7169     case Type::STK_MemberPointer:
7170       llvm_unreachable("member pointer type in C");
7171     case Type::STK_FixedPoint:
7172       Diag(Src.get()->getExprLoc(),
7173            diag::err_unimplemented_conversion_with_fixed_point_type)
7174           << SrcTy;
7175       return CK_IntegralCast;
7176     }
7177     llvm_unreachable("Should have returned before this");
7178   }
7179 
7180   llvm_unreachable("Unhandled scalar cast");
7181 }
7182 
7183 static bool breakDownVectorType(QualType type, uint64_t &len,
7184                                 QualType &eltType) {
7185   // Vectors are simple.
7186   if (const VectorType *vecType = type->getAs<VectorType>()) {
7187     len = vecType->getNumElements();
7188     eltType = vecType->getElementType();
7189     assert(eltType->isScalarType());
7190     return true;
7191   }
7192 
7193   // We allow lax conversion to and from non-vector types, but only if
7194   // they're real types (i.e. non-complex, non-pointer scalar types).
7195   if (!type->isRealType()) return false;
7196 
7197   len = 1;
7198   eltType = type;
7199   return true;
7200 }
7201 
7202 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7203 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7204 /// allowed?
7205 ///
7206 /// This will also return false if the two given types do not make sense from
7207 /// the perspective of SVE bitcasts.
7208 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7209   assert(srcTy->isVectorType() || destTy->isVectorType());
7210 
7211   auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7212     if (!FirstType->isSizelessBuiltinType())
7213       return false;
7214 
7215     const auto *VecTy = SecondType->getAs<VectorType>();
7216     return VecTy &&
7217            VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7218   };
7219 
7220   return ValidScalableConversion(srcTy, destTy) ||
7221          ValidScalableConversion(destTy, srcTy);
7222 }
7223 
7224 /// Are the two types lax-compatible vector types?  That is, given
7225 /// that one of them is a vector, do they have equal storage sizes,
7226 /// where the storage size is the number of elements times the element
7227 /// size?
7228 ///
7229 /// This will also return false if either of the types is neither a
7230 /// vector nor a real type.
7231 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7232   assert(destTy->isVectorType() || srcTy->isVectorType());
7233 
7234   // Disallow lax conversions between scalars and ExtVectors (these
7235   // conversions are allowed for other vector types because common headers
7236   // depend on them).  Most scalar OP ExtVector cases are handled by the
7237   // splat path anyway, which does what we want (convert, not bitcast).
7238   // What this rules out for ExtVectors is crazy things like char4*float.
7239   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7240   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7241 
7242   uint64_t srcLen, destLen;
7243   QualType srcEltTy, destEltTy;
7244   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7245   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7246 
7247   // ASTContext::getTypeSize will return the size rounded up to a
7248   // power of 2, so instead of using that, we need to use the raw
7249   // element size multiplied by the element count.
7250   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7251   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7252 
7253   return (srcLen * srcEltSize == destLen * destEltSize);
7254 }
7255 
7256 /// Is this a legal conversion between two types, one of which is
7257 /// known to be a vector type?
7258 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7259   assert(destTy->isVectorType() || srcTy->isVectorType());
7260 
7261   switch (Context.getLangOpts().getLaxVectorConversions()) {
7262   case LangOptions::LaxVectorConversionKind::None:
7263     return false;
7264 
7265   case LangOptions::LaxVectorConversionKind::Integer:
7266     if (!srcTy->isIntegralOrEnumerationType()) {
7267       auto *Vec = srcTy->getAs<VectorType>();
7268       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7269         return false;
7270     }
7271     if (!destTy->isIntegralOrEnumerationType()) {
7272       auto *Vec = destTy->getAs<VectorType>();
7273       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7274         return false;
7275     }
7276     // OK, integer (vector) -> integer (vector) bitcast.
7277     break;
7278 
7279     case LangOptions::LaxVectorConversionKind::All:
7280     break;
7281   }
7282 
7283   return areLaxCompatibleVectorTypes(srcTy, destTy);
7284 }
7285 
7286 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7287                            CastKind &Kind) {
7288   assert(VectorTy->isVectorType() && "Not a vector type!");
7289 
7290   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7291     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7292       return Diag(R.getBegin(),
7293                   Ty->isVectorType() ?
7294                   diag::err_invalid_conversion_between_vectors :
7295                   diag::err_invalid_conversion_between_vector_and_integer)
7296         << VectorTy << Ty << R;
7297   } else
7298     return Diag(R.getBegin(),
7299                 diag::err_invalid_conversion_between_vector_and_scalar)
7300       << VectorTy << Ty << R;
7301 
7302   Kind = CK_BitCast;
7303   return false;
7304 }
7305 
7306 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7307   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7308 
7309   if (DestElemTy == SplattedExpr->getType())
7310     return SplattedExpr;
7311 
7312   assert(DestElemTy->isFloatingType() ||
7313          DestElemTy->isIntegralOrEnumerationType());
7314 
7315   CastKind CK;
7316   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7317     // OpenCL requires that we convert `true` boolean expressions to -1, but
7318     // only when splatting vectors.
7319     if (DestElemTy->isFloatingType()) {
7320       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7321       // in two steps: boolean to signed integral, then to floating.
7322       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7323                                                  CK_BooleanToSignedIntegral);
7324       SplattedExpr = CastExprRes.get();
7325       CK = CK_IntegralToFloating;
7326     } else {
7327       CK = CK_BooleanToSignedIntegral;
7328     }
7329   } else {
7330     ExprResult CastExprRes = SplattedExpr;
7331     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7332     if (CastExprRes.isInvalid())
7333       return ExprError();
7334     SplattedExpr = CastExprRes.get();
7335   }
7336   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7337 }
7338 
7339 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7340                                     Expr *CastExpr, CastKind &Kind) {
7341   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7342 
7343   QualType SrcTy = CastExpr->getType();
7344 
7345   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7346   // an ExtVectorType.
7347   // In OpenCL, casts between vectors of different types are not allowed.
7348   // (See OpenCL 6.2).
7349   if (SrcTy->isVectorType()) {
7350     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7351         (getLangOpts().OpenCL &&
7352          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7353       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7354         << DestTy << SrcTy << R;
7355       return ExprError();
7356     }
7357     Kind = CK_BitCast;
7358     return CastExpr;
7359   }
7360 
7361   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7362   // conversion will take place first from scalar to elt type, and then
7363   // splat from elt type to vector.
7364   if (SrcTy->isPointerType())
7365     return Diag(R.getBegin(),
7366                 diag::err_invalid_conversion_between_vector_and_scalar)
7367       << DestTy << SrcTy << R;
7368 
7369   Kind = CK_VectorSplat;
7370   return prepareVectorSplat(DestTy, CastExpr);
7371 }
7372 
7373 ExprResult
7374 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7375                     Declarator &D, ParsedType &Ty,
7376                     SourceLocation RParenLoc, Expr *CastExpr) {
7377   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7378          "ActOnCastExpr(): missing type or expr");
7379 
7380   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7381   if (D.isInvalidType())
7382     return ExprError();
7383 
7384   if (getLangOpts().CPlusPlus) {
7385     // Check that there are no default arguments (C++ only).
7386     CheckExtraCXXDefaultArguments(D);
7387   } else {
7388     // Make sure any TypoExprs have been dealt with.
7389     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7390     if (!Res.isUsable())
7391       return ExprError();
7392     CastExpr = Res.get();
7393   }
7394 
7395   checkUnusedDeclAttributes(D);
7396 
7397   QualType castType = castTInfo->getType();
7398   Ty = CreateParsedType(castType, castTInfo);
7399 
7400   bool isVectorLiteral = false;
7401 
7402   // Check for an altivec or OpenCL literal,
7403   // i.e. all the elements are integer constants.
7404   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7405   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7406   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7407        && castType->isVectorType() && (PE || PLE)) {
7408     if (PLE && PLE->getNumExprs() == 0) {
7409       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7410       return ExprError();
7411     }
7412     if (PE || PLE->getNumExprs() == 1) {
7413       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7414       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7415         isVectorLiteral = true;
7416     }
7417     else
7418       isVectorLiteral = true;
7419   }
7420 
7421   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7422   // then handle it as such.
7423   if (isVectorLiteral)
7424     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7425 
7426   // If the Expr being casted is a ParenListExpr, handle it specially.
7427   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7428   // sequence of BinOp comma operators.
7429   if (isa<ParenListExpr>(CastExpr)) {
7430     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7431     if (Result.isInvalid()) return ExprError();
7432     CastExpr = Result.get();
7433   }
7434 
7435   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7436       !getSourceManager().isInSystemMacro(LParenLoc))
7437     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7438 
7439   CheckTollFreeBridgeCast(castType, CastExpr);
7440 
7441   CheckObjCBridgeRelatedCast(castType, CastExpr);
7442 
7443   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7444 
7445   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7446 }
7447 
7448 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7449                                     SourceLocation RParenLoc, Expr *E,
7450                                     TypeSourceInfo *TInfo) {
7451   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7452          "Expected paren or paren list expression");
7453 
7454   Expr **exprs;
7455   unsigned numExprs;
7456   Expr *subExpr;
7457   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7458   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7459     LiteralLParenLoc = PE->getLParenLoc();
7460     LiteralRParenLoc = PE->getRParenLoc();
7461     exprs = PE->getExprs();
7462     numExprs = PE->getNumExprs();
7463   } else { // isa<ParenExpr> by assertion at function entrance
7464     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7465     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7466     subExpr = cast<ParenExpr>(E)->getSubExpr();
7467     exprs = &subExpr;
7468     numExprs = 1;
7469   }
7470 
7471   QualType Ty = TInfo->getType();
7472   assert(Ty->isVectorType() && "Expected vector type");
7473 
7474   SmallVector<Expr *, 8> initExprs;
7475   const VectorType *VTy = Ty->castAs<VectorType>();
7476   unsigned numElems = VTy->getNumElements();
7477 
7478   // '(...)' form of vector initialization in AltiVec: the number of
7479   // initializers must be one or must match the size of the vector.
7480   // If a single value is specified in the initializer then it will be
7481   // replicated to all the components of the vector
7482   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7483     // The number of initializers must be one or must match the size of the
7484     // vector. If a single value is specified in the initializer then it will
7485     // be replicated to all the components of the vector
7486     if (numExprs == 1) {
7487       QualType ElemTy = VTy->getElementType();
7488       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7489       if (Literal.isInvalid())
7490         return ExprError();
7491       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7492                                   PrepareScalarCast(Literal, ElemTy));
7493       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7494     }
7495     else if (numExprs < numElems) {
7496       Diag(E->getExprLoc(),
7497            diag::err_incorrect_number_of_vector_initializers);
7498       return ExprError();
7499     }
7500     else
7501       initExprs.append(exprs, exprs + numExprs);
7502   }
7503   else {
7504     // For OpenCL, when the number of initializers is a single value,
7505     // it will be replicated to all components of the vector.
7506     if (getLangOpts().OpenCL &&
7507         VTy->getVectorKind() == VectorType::GenericVector &&
7508         numExprs == 1) {
7509         QualType ElemTy = VTy->getElementType();
7510         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7511         if (Literal.isInvalid())
7512           return ExprError();
7513         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7514                                     PrepareScalarCast(Literal, ElemTy));
7515         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7516     }
7517 
7518     initExprs.append(exprs, exprs + numExprs);
7519   }
7520   // FIXME: This means that pretty-printing the final AST will produce curly
7521   // braces instead of the original commas.
7522   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7523                                                    initExprs, LiteralRParenLoc);
7524   initE->setType(Ty);
7525   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7526 }
7527 
7528 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7529 /// the ParenListExpr into a sequence of comma binary operators.
7530 ExprResult
7531 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7532   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7533   if (!E)
7534     return OrigExpr;
7535 
7536   ExprResult Result(E->getExpr(0));
7537 
7538   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7539     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7540                         E->getExpr(i));
7541 
7542   if (Result.isInvalid()) return ExprError();
7543 
7544   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7545 }
7546 
7547 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7548                                     SourceLocation R,
7549                                     MultiExprArg Val) {
7550   return ParenListExpr::Create(Context, L, Val, R);
7551 }
7552 
7553 /// Emit a specialized diagnostic when one expression is a null pointer
7554 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7555 /// emitted.
7556 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7557                                       SourceLocation QuestionLoc) {
7558   Expr *NullExpr = LHSExpr;
7559   Expr *NonPointerExpr = RHSExpr;
7560   Expr::NullPointerConstantKind NullKind =
7561       NullExpr->isNullPointerConstant(Context,
7562                                       Expr::NPC_ValueDependentIsNotNull);
7563 
7564   if (NullKind == Expr::NPCK_NotNull) {
7565     NullExpr = RHSExpr;
7566     NonPointerExpr = LHSExpr;
7567     NullKind =
7568         NullExpr->isNullPointerConstant(Context,
7569                                         Expr::NPC_ValueDependentIsNotNull);
7570   }
7571 
7572   if (NullKind == Expr::NPCK_NotNull)
7573     return false;
7574 
7575   if (NullKind == Expr::NPCK_ZeroExpression)
7576     return false;
7577 
7578   if (NullKind == Expr::NPCK_ZeroLiteral) {
7579     // In this case, check to make sure that we got here from a "NULL"
7580     // string in the source code.
7581     NullExpr = NullExpr->IgnoreParenImpCasts();
7582     SourceLocation loc = NullExpr->getExprLoc();
7583     if (!findMacroSpelling(loc, "NULL"))
7584       return false;
7585   }
7586 
7587   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7588   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7589       << NonPointerExpr->getType() << DiagType
7590       << NonPointerExpr->getSourceRange();
7591   return true;
7592 }
7593 
7594 /// Return false if the condition expression is valid, true otherwise.
7595 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7596   QualType CondTy = Cond->getType();
7597 
7598   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7599   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7600     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7601       << CondTy << Cond->getSourceRange();
7602     return true;
7603   }
7604 
7605   // C99 6.5.15p2
7606   if (CondTy->isScalarType()) return false;
7607 
7608   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7609     << CondTy << Cond->getSourceRange();
7610   return true;
7611 }
7612 
7613 /// Handle when one or both operands are void type.
7614 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7615                                          ExprResult &RHS) {
7616     Expr *LHSExpr = LHS.get();
7617     Expr *RHSExpr = RHS.get();
7618 
7619     if (!LHSExpr->getType()->isVoidType())
7620       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7621           << RHSExpr->getSourceRange();
7622     if (!RHSExpr->getType()->isVoidType())
7623       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7624           << LHSExpr->getSourceRange();
7625     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7626     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7627     return S.Context.VoidTy;
7628 }
7629 
7630 /// Return false if the NullExpr can be promoted to PointerTy,
7631 /// true otherwise.
7632 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7633                                         QualType PointerTy) {
7634   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7635       !NullExpr.get()->isNullPointerConstant(S.Context,
7636                                             Expr::NPC_ValueDependentIsNull))
7637     return true;
7638 
7639   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7640   return false;
7641 }
7642 
7643 /// Checks compatibility between two pointers and return the resulting
7644 /// type.
7645 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7646                                                      ExprResult &RHS,
7647                                                      SourceLocation Loc) {
7648   QualType LHSTy = LHS.get()->getType();
7649   QualType RHSTy = RHS.get()->getType();
7650 
7651   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7652     // Two identical pointers types are always compatible.
7653     return LHSTy;
7654   }
7655 
7656   QualType lhptee, rhptee;
7657 
7658   // Get the pointee types.
7659   bool IsBlockPointer = false;
7660   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7661     lhptee = LHSBTy->getPointeeType();
7662     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7663     IsBlockPointer = true;
7664   } else {
7665     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7666     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7667   }
7668 
7669   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7670   // differently qualified versions of compatible types, the result type is
7671   // a pointer to an appropriately qualified version of the composite
7672   // type.
7673 
7674   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7675   // clause doesn't make sense for our extensions. E.g. address space 2 should
7676   // be incompatible with address space 3: they may live on different devices or
7677   // anything.
7678   Qualifiers lhQual = lhptee.getQualifiers();
7679   Qualifiers rhQual = rhptee.getQualifiers();
7680 
7681   LangAS ResultAddrSpace = LangAS::Default;
7682   LangAS LAddrSpace = lhQual.getAddressSpace();
7683   LangAS RAddrSpace = rhQual.getAddressSpace();
7684 
7685   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7686   // spaces is disallowed.
7687   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7688     ResultAddrSpace = LAddrSpace;
7689   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7690     ResultAddrSpace = RAddrSpace;
7691   else {
7692     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7693         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7694         << RHS.get()->getSourceRange();
7695     return QualType();
7696   }
7697 
7698   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7699   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7700   lhQual.removeCVRQualifiers();
7701   rhQual.removeCVRQualifiers();
7702 
7703   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7704   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7705   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7706   // qual types are compatible iff
7707   //  * corresponded types are compatible
7708   //  * CVR qualifiers are equal
7709   //  * address spaces are equal
7710   // Thus for conditional operator we merge CVR and address space unqualified
7711   // pointees and if there is a composite type we return a pointer to it with
7712   // merged qualifiers.
7713   LHSCastKind =
7714       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7715   RHSCastKind =
7716       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7717   lhQual.removeAddressSpace();
7718   rhQual.removeAddressSpace();
7719 
7720   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7721   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7722 
7723   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7724 
7725   if (CompositeTy.isNull()) {
7726     // In this situation, we assume void* type. No especially good
7727     // reason, but this is what gcc does, and we do have to pick
7728     // to get a consistent AST.
7729     QualType incompatTy;
7730     incompatTy = S.Context.getPointerType(
7731         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7732     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7733     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7734 
7735     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7736     // for casts between types with incompatible address space qualifiers.
7737     // For the following code the compiler produces casts between global and
7738     // local address spaces of the corresponded innermost pointees:
7739     // local int *global *a;
7740     // global int *global *b;
7741     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7742     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7743         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7744         << RHS.get()->getSourceRange();
7745 
7746     return incompatTy;
7747   }
7748 
7749   // The pointer types are compatible.
7750   // In case of OpenCL ResultTy should have the address space qualifier
7751   // which is a superset of address spaces of both the 2nd and the 3rd
7752   // operands of the conditional operator.
7753   QualType ResultTy = [&, ResultAddrSpace]() {
7754     if (S.getLangOpts().OpenCL) {
7755       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7756       CompositeQuals.setAddressSpace(ResultAddrSpace);
7757       return S.Context
7758           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7759           .withCVRQualifiers(MergedCVRQual);
7760     }
7761     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7762   }();
7763   if (IsBlockPointer)
7764     ResultTy = S.Context.getBlockPointerType(ResultTy);
7765   else
7766     ResultTy = S.Context.getPointerType(ResultTy);
7767 
7768   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7769   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7770   return ResultTy;
7771 }
7772 
7773 /// Return the resulting type when the operands are both block pointers.
7774 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7775                                                           ExprResult &LHS,
7776                                                           ExprResult &RHS,
7777                                                           SourceLocation Loc) {
7778   QualType LHSTy = LHS.get()->getType();
7779   QualType RHSTy = RHS.get()->getType();
7780 
7781   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7782     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7783       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7784       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7785       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7786       return destType;
7787     }
7788     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7789       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7790       << RHS.get()->getSourceRange();
7791     return QualType();
7792   }
7793 
7794   // We have 2 block pointer types.
7795   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7796 }
7797 
7798 /// Return the resulting type when the operands are both pointers.
7799 static QualType
7800 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7801                                             ExprResult &RHS,
7802                                             SourceLocation Loc) {
7803   // get the pointer types
7804   QualType LHSTy = LHS.get()->getType();
7805   QualType RHSTy = RHS.get()->getType();
7806 
7807   // get the "pointed to" types
7808   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7809   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7810 
7811   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7812   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7813     // Figure out necessary qualifiers (C99 6.5.15p6)
7814     QualType destPointee
7815       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7816     QualType destType = S.Context.getPointerType(destPointee);
7817     // Add qualifiers if necessary.
7818     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7819     // Promote to void*.
7820     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7821     return destType;
7822   }
7823   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7824     QualType destPointee
7825       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7826     QualType destType = S.Context.getPointerType(destPointee);
7827     // Add qualifiers if necessary.
7828     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7829     // Promote to void*.
7830     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7831     return destType;
7832   }
7833 
7834   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7835 }
7836 
7837 /// Return false if the first expression is not an integer and the second
7838 /// expression is not a pointer, true otherwise.
7839 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7840                                         Expr* PointerExpr, SourceLocation Loc,
7841                                         bool IsIntFirstExpr) {
7842   if (!PointerExpr->getType()->isPointerType() ||
7843       !Int.get()->getType()->isIntegerType())
7844     return false;
7845 
7846   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7847   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7848 
7849   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7850     << Expr1->getType() << Expr2->getType()
7851     << Expr1->getSourceRange() << Expr2->getSourceRange();
7852   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7853                             CK_IntegralToPointer);
7854   return true;
7855 }
7856 
7857 /// Simple conversion between integer and floating point types.
7858 ///
7859 /// Used when handling the OpenCL conditional operator where the
7860 /// condition is a vector while the other operands are scalar.
7861 ///
7862 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7863 /// types are either integer or floating type. Between the two
7864 /// operands, the type with the higher rank is defined as the "result
7865 /// type". The other operand needs to be promoted to the same type. No
7866 /// other type promotion is allowed. We cannot use
7867 /// UsualArithmeticConversions() for this purpose, since it always
7868 /// promotes promotable types.
7869 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7870                                             ExprResult &RHS,
7871                                             SourceLocation QuestionLoc) {
7872   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7873   if (LHS.isInvalid())
7874     return QualType();
7875   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7876   if (RHS.isInvalid())
7877     return QualType();
7878 
7879   // For conversion purposes, we ignore any qualifiers.
7880   // For example, "const float" and "float" are equivalent.
7881   QualType LHSType =
7882     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7883   QualType RHSType =
7884     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7885 
7886   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7887     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7888       << LHSType << LHS.get()->getSourceRange();
7889     return QualType();
7890   }
7891 
7892   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7893     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7894       << RHSType << RHS.get()->getSourceRange();
7895     return QualType();
7896   }
7897 
7898   // If both types are identical, no conversion is needed.
7899   if (LHSType == RHSType)
7900     return LHSType;
7901 
7902   // Now handle "real" floating types (i.e. float, double, long double).
7903   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7904     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7905                                  /*IsCompAssign = */ false);
7906 
7907   // Finally, we have two differing integer types.
7908   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7909   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7910 }
7911 
7912 /// Convert scalar operands to a vector that matches the
7913 ///        condition in length.
7914 ///
7915 /// Used when handling the OpenCL conditional operator where the
7916 /// condition is a vector while the other operands are scalar.
7917 ///
7918 /// We first compute the "result type" for the scalar operands
7919 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7920 /// into a vector of that type where the length matches the condition
7921 /// vector type. s6.11.6 requires that the element types of the result
7922 /// and the condition must have the same number of bits.
7923 static QualType
7924 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7925                               QualType CondTy, SourceLocation QuestionLoc) {
7926   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7927   if (ResTy.isNull()) return QualType();
7928 
7929   const VectorType *CV = CondTy->getAs<VectorType>();
7930   assert(CV);
7931 
7932   // Determine the vector result type
7933   unsigned NumElements = CV->getNumElements();
7934   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7935 
7936   // Ensure that all types have the same number of bits
7937   if (S.Context.getTypeSize(CV->getElementType())
7938       != S.Context.getTypeSize(ResTy)) {
7939     // Since VectorTy is created internally, it does not pretty print
7940     // with an OpenCL name. Instead, we just print a description.
7941     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7942     SmallString<64> Str;
7943     llvm::raw_svector_ostream OS(Str);
7944     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7945     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7946       << CondTy << OS.str();
7947     return QualType();
7948   }
7949 
7950   // Convert operands to the vector result type
7951   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7952   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7953 
7954   return VectorTy;
7955 }
7956 
7957 /// Return false if this is a valid OpenCL condition vector
7958 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7959                                        SourceLocation QuestionLoc) {
7960   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7961   // integral type.
7962   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7963   assert(CondTy);
7964   QualType EleTy = CondTy->getElementType();
7965   if (EleTy->isIntegerType()) return false;
7966 
7967   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7968     << Cond->getType() << Cond->getSourceRange();
7969   return true;
7970 }
7971 
7972 /// Return false if the vector condition type and the vector
7973 ///        result type are compatible.
7974 ///
7975 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7976 /// number of elements, and their element types have the same number
7977 /// of bits.
7978 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7979                               SourceLocation QuestionLoc) {
7980   const VectorType *CV = CondTy->getAs<VectorType>();
7981   const VectorType *RV = VecResTy->getAs<VectorType>();
7982   assert(CV && RV);
7983 
7984   if (CV->getNumElements() != RV->getNumElements()) {
7985     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7986       << CondTy << VecResTy;
7987     return true;
7988   }
7989 
7990   QualType CVE = CV->getElementType();
7991   QualType RVE = RV->getElementType();
7992 
7993   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7994     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7995       << CondTy << VecResTy;
7996     return true;
7997   }
7998 
7999   return false;
8000 }
8001 
8002 /// Return the resulting type for the conditional operator in
8003 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8004 ///        s6.3.i) when the condition is a vector type.
8005 static QualType
8006 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8007                              ExprResult &LHS, ExprResult &RHS,
8008                              SourceLocation QuestionLoc) {
8009   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8010   if (Cond.isInvalid())
8011     return QualType();
8012   QualType CondTy = Cond.get()->getType();
8013 
8014   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8015     return QualType();
8016 
8017   // If either operand is a vector then find the vector type of the
8018   // result as specified in OpenCL v1.1 s6.3.i.
8019   if (LHS.get()->getType()->isVectorType() ||
8020       RHS.get()->getType()->isVectorType()) {
8021     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8022                                               /*isCompAssign*/false,
8023                                               /*AllowBothBool*/true,
8024                                               /*AllowBoolConversions*/false);
8025     if (VecResTy.isNull()) return QualType();
8026     // The result type must match the condition type as specified in
8027     // OpenCL v1.1 s6.11.6.
8028     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8029       return QualType();
8030     return VecResTy;
8031   }
8032 
8033   // Both operands are scalar.
8034   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8035 }
8036 
8037 /// Return true if the Expr is block type
8038 static bool checkBlockType(Sema &S, const Expr *E) {
8039   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8040     QualType Ty = CE->getCallee()->getType();
8041     if (Ty->isBlockPointerType()) {
8042       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8043       return true;
8044     }
8045   }
8046   return false;
8047 }
8048 
8049 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8050 /// In that case, LHS = cond.
8051 /// C99 6.5.15
8052 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8053                                         ExprResult &RHS, ExprValueKind &VK,
8054                                         ExprObjectKind &OK,
8055                                         SourceLocation QuestionLoc) {
8056 
8057   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8058   if (!LHSResult.isUsable()) return QualType();
8059   LHS = LHSResult;
8060 
8061   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8062   if (!RHSResult.isUsable()) return QualType();
8063   RHS = RHSResult;
8064 
8065   // C++ is sufficiently different to merit its own checker.
8066   if (getLangOpts().CPlusPlus)
8067     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8068 
8069   VK = VK_RValue;
8070   OK = OK_Ordinary;
8071 
8072   if (Context.isDependenceAllowed() &&
8073       (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8074        RHS.get()->isTypeDependent())) {
8075     assert(!getLangOpts().CPlusPlus);
8076     assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8077             RHS.get()->containsErrors()) &&
8078            "should only occur in error-recovery path.");
8079     return Context.DependentTy;
8080   }
8081 
8082   // The OpenCL operator with a vector condition is sufficiently
8083   // different to merit its own checker.
8084   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8085       Cond.get()->getType()->isExtVectorType())
8086     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8087 
8088   // First, check the condition.
8089   Cond = UsualUnaryConversions(Cond.get());
8090   if (Cond.isInvalid())
8091     return QualType();
8092   if (checkCondition(*this, Cond.get(), QuestionLoc))
8093     return QualType();
8094 
8095   // Now check the two expressions.
8096   if (LHS.get()->getType()->isVectorType() ||
8097       RHS.get()->getType()->isVectorType())
8098     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8099                                /*AllowBothBool*/true,
8100                                /*AllowBoolConversions*/false);
8101 
8102   QualType ResTy =
8103       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8104   if (LHS.isInvalid() || RHS.isInvalid())
8105     return QualType();
8106 
8107   QualType LHSTy = LHS.get()->getType();
8108   QualType RHSTy = RHS.get()->getType();
8109 
8110   // Diagnose attempts to convert between __float128 and long double where
8111   // such conversions currently can't be handled.
8112   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8113     Diag(QuestionLoc,
8114          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8115       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8116     return QualType();
8117   }
8118 
8119   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8120   // selection operator (?:).
8121   if (getLangOpts().OpenCL &&
8122       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8123     return QualType();
8124   }
8125 
8126   // If both operands have arithmetic type, do the usual arithmetic conversions
8127   // to find a common type: C99 6.5.15p3,5.
8128   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8129     // Disallow invalid arithmetic conversions, such as those between ExtInts of
8130     // different sizes, or between ExtInts and other types.
8131     if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8132       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8133           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8134           << RHS.get()->getSourceRange();
8135       return QualType();
8136     }
8137 
8138     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8139     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8140 
8141     return ResTy;
8142   }
8143 
8144   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8145   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8146     return LHSTy;
8147   }
8148 
8149   // If both operands are the same structure or union type, the result is that
8150   // type.
8151   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8152     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8153       if (LHSRT->getDecl() == RHSRT->getDecl())
8154         // "If both the operands have structure or union type, the result has
8155         // that type."  This implies that CV qualifiers are dropped.
8156         return LHSTy.getUnqualifiedType();
8157     // FIXME: Type of conditional expression must be complete in C mode.
8158   }
8159 
8160   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8161   // The following || allows only one side to be void (a GCC-ism).
8162   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8163     return checkConditionalVoidType(*this, LHS, RHS);
8164   }
8165 
8166   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8167   // the type of the other operand."
8168   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8169   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8170 
8171   // All objective-c pointer type analysis is done here.
8172   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8173                                                         QuestionLoc);
8174   if (LHS.isInvalid() || RHS.isInvalid())
8175     return QualType();
8176   if (!compositeType.isNull())
8177     return compositeType;
8178 
8179 
8180   // Handle block pointer types.
8181   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8182     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8183                                                      QuestionLoc);
8184 
8185   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8186   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8187     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8188                                                        QuestionLoc);
8189 
8190   // GCC compatibility: soften pointer/integer mismatch.  Note that
8191   // null pointers have been filtered out by this point.
8192   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8193       /*IsIntFirstExpr=*/true))
8194     return RHSTy;
8195   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8196       /*IsIntFirstExpr=*/false))
8197     return LHSTy;
8198 
8199   // Allow ?: operations in which both operands have the same
8200   // built-in sizeless type.
8201   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8202     return LHSTy;
8203 
8204   // Emit a better diagnostic if one of the expressions is a null pointer
8205   // constant and the other is not a pointer type. In this case, the user most
8206   // likely forgot to take the address of the other expression.
8207   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8208     return QualType();
8209 
8210   // Otherwise, the operands are not compatible.
8211   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8212     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8213     << RHS.get()->getSourceRange();
8214   return QualType();
8215 }
8216 
8217 /// FindCompositeObjCPointerType - Helper method to find composite type of
8218 /// two objective-c pointer types of the two input expressions.
8219 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8220                                             SourceLocation QuestionLoc) {
8221   QualType LHSTy = LHS.get()->getType();
8222   QualType RHSTy = RHS.get()->getType();
8223 
8224   // Handle things like Class and struct objc_class*.  Here we case the result
8225   // to the pseudo-builtin, because that will be implicitly cast back to the
8226   // redefinition type if an attempt is made to access its fields.
8227   if (LHSTy->isObjCClassType() &&
8228       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8229     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8230     return LHSTy;
8231   }
8232   if (RHSTy->isObjCClassType() &&
8233       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8234     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8235     return RHSTy;
8236   }
8237   // And the same for struct objc_object* / id
8238   if (LHSTy->isObjCIdType() &&
8239       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8240     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8241     return LHSTy;
8242   }
8243   if (RHSTy->isObjCIdType() &&
8244       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8245     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8246     return RHSTy;
8247   }
8248   // And the same for struct objc_selector* / SEL
8249   if (Context.isObjCSelType(LHSTy) &&
8250       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8251     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8252     return LHSTy;
8253   }
8254   if (Context.isObjCSelType(RHSTy) &&
8255       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8256     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8257     return RHSTy;
8258   }
8259   // Check constraints for Objective-C object pointers types.
8260   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8261 
8262     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8263       // Two identical object pointer types are always compatible.
8264       return LHSTy;
8265     }
8266     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8267     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8268     QualType compositeType = LHSTy;
8269 
8270     // If both operands are interfaces and either operand can be
8271     // assigned to the other, use that type as the composite
8272     // type. This allows
8273     //   xxx ? (A*) a : (B*) b
8274     // where B is a subclass of A.
8275     //
8276     // Additionally, as for assignment, if either type is 'id'
8277     // allow silent coercion. Finally, if the types are
8278     // incompatible then make sure to use 'id' as the composite
8279     // type so the result is acceptable for sending messages to.
8280 
8281     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8282     // It could return the composite type.
8283     if (!(compositeType =
8284           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8285       // Nothing more to do.
8286     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8287       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8288     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8289       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8290     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8291                 RHSOPT->isObjCQualifiedIdType()) &&
8292                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8293                                                          true)) {
8294       // Need to handle "id<xx>" explicitly.
8295       // GCC allows qualified id and any Objective-C type to devolve to
8296       // id. Currently localizing to here until clear this should be
8297       // part of ObjCQualifiedIdTypesAreCompatible.
8298       compositeType = Context.getObjCIdType();
8299     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8300       compositeType = Context.getObjCIdType();
8301     } else {
8302       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8303       << LHSTy << RHSTy
8304       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8305       QualType incompatTy = Context.getObjCIdType();
8306       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8307       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8308       return incompatTy;
8309     }
8310     // The object pointer types are compatible.
8311     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8312     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8313     return compositeType;
8314   }
8315   // Check Objective-C object pointer types and 'void *'
8316   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8317     if (getLangOpts().ObjCAutoRefCount) {
8318       // ARC forbids the implicit conversion of object pointers to 'void *',
8319       // so these types are not compatible.
8320       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8321           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8322       LHS = RHS = true;
8323       return QualType();
8324     }
8325     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8326     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8327     QualType destPointee
8328     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8329     QualType destType = Context.getPointerType(destPointee);
8330     // Add qualifiers if necessary.
8331     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8332     // Promote to void*.
8333     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8334     return destType;
8335   }
8336   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8337     if (getLangOpts().ObjCAutoRefCount) {
8338       // ARC forbids the implicit conversion of object pointers to 'void *',
8339       // so these types are not compatible.
8340       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8341           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8342       LHS = RHS = true;
8343       return QualType();
8344     }
8345     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8346     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8347     QualType destPointee
8348     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8349     QualType destType = Context.getPointerType(destPointee);
8350     // Add qualifiers if necessary.
8351     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8352     // Promote to void*.
8353     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8354     return destType;
8355   }
8356   return QualType();
8357 }
8358 
8359 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8360 /// ParenRange in parentheses.
8361 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8362                                const PartialDiagnostic &Note,
8363                                SourceRange ParenRange) {
8364   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8365   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8366       EndLoc.isValid()) {
8367     Self.Diag(Loc, Note)
8368       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8369       << FixItHint::CreateInsertion(EndLoc, ")");
8370   } else {
8371     // We can't display the parentheses, so just show the bare note.
8372     Self.Diag(Loc, Note) << ParenRange;
8373   }
8374 }
8375 
8376 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8377   return BinaryOperator::isAdditiveOp(Opc) ||
8378          BinaryOperator::isMultiplicativeOp(Opc) ||
8379          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8380   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8381   // not any of the logical operators.  Bitwise-xor is commonly used as a
8382   // logical-xor because there is no logical-xor operator.  The logical
8383   // operators, including uses of xor, have a high false positive rate for
8384   // precedence warnings.
8385 }
8386 
8387 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8388 /// expression, either using a built-in or overloaded operator,
8389 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8390 /// expression.
8391 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8392                                    Expr **RHSExprs) {
8393   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8394   E = E->IgnoreImpCasts();
8395   E = E->IgnoreConversionOperatorSingleStep();
8396   E = E->IgnoreImpCasts();
8397   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8398     E = MTE->getSubExpr();
8399     E = E->IgnoreImpCasts();
8400   }
8401 
8402   // Built-in binary operator.
8403   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8404     if (IsArithmeticOp(OP->getOpcode())) {
8405       *Opcode = OP->getOpcode();
8406       *RHSExprs = OP->getRHS();
8407       return true;
8408     }
8409   }
8410 
8411   // Overloaded operator.
8412   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8413     if (Call->getNumArgs() != 2)
8414       return false;
8415 
8416     // Make sure this is really a binary operator that is safe to pass into
8417     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8418     OverloadedOperatorKind OO = Call->getOperator();
8419     if (OO < OO_Plus || OO > OO_Arrow ||
8420         OO == OO_PlusPlus || OO == OO_MinusMinus)
8421       return false;
8422 
8423     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8424     if (IsArithmeticOp(OpKind)) {
8425       *Opcode = OpKind;
8426       *RHSExprs = Call->getArg(1);
8427       return true;
8428     }
8429   }
8430 
8431   return false;
8432 }
8433 
8434 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8435 /// or is a logical expression such as (x==y) which has int type, but is
8436 /// commonly interpreted as boolean.
8437 static bool ExprLooksBoolean(Expr *E) {
8438   E = E->IgnoreParenImpCasts();
8439 
8440   if (E->getType()->isBooleanType())
8441     return true;
8442   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8443     return OP->isComparisonOp() || OP->isLogicalOp();
8444   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8445     return OP->getOpcode() == UO_LNot;
8446   if (E->getType()->isPointerType())
8447     return true;
8448   // FIXME: What about overloaded operator calls returning "unspecified boolean
8449   // type"s (commonly pointer-to-members)?
8450 
8451   return false;
8452 }
8453 
8454 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8455 /// and binary operator are mixed in a way that suggests the programmer assumed
8456 /// the conditional operator has higher precedence, for example:
8457 /// "int x = a + someBinaryCondition ? 1 : 2".
8458 static void DiagnoseConditionalPrecedence(Sema &Self,
8459                                           SourceLocation OpLoc,
8460                                           Expr *Condition,
8461                                           Expr *LHSExpr,
8462                                           Expr *RHSExpr) {
8463   BinaryOperatorKind CondOpcode;
8464   Expr *CondRHS;
8465 
8466   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8467     return;
8468   if (!ExprLooksBoolean(CondRHS))
8469     return;
8470 
8471   // The condition is an arithmetic binary expression, with a right-
8472   // hand side that looks boolean, so warn.
8473 
8474   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8475                         ? diag::warn_precedence_bitwise_conditional
8476                         : diag::warn_precedence_conditional;
8477 
8478   Self.Diag(OpLoc, DiagID)
8479       << Condition->getSourceRange()
8480       << BinaryOperator::getOpcodeStr(CondOpcode);
8481 
8482   SuggestParentheses(
8483       Self, OpLoc,
8484       Self.PDiag(diag::note_precedence_silence)
8485           << BinaryOperator::getOpcodeStr(CondOpcode),
8486       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8487 
8488   SuggestParentheses(Self, OpLoc,
8489                      Self.PDiag(diag::note_precedence_conditional_first),
8490                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8491 }
8492 
8493 /// Compute the nullability of a conditional expression.
8494 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8495                                               QualType LHSTy, QualType RHSTy,
8496                                               ASTContext &Ctx) {
8497   if (!ResTy->isAnyPointerType())
8498     return ResTy;
8499 
8500   auto GetNullability = [&Ctx](QualType Ty) {
8501     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8502     if (Kind)
8503       return *Kind;
8504     return NullabilityKind::Unspecified;
8505   };
8506 
8507   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8508   NullabilityKind MergedKind;
8509 
8510   // Compute nullability of a binary conditional expression.
8511   if (IsBin) {
8512     if (LHSKind == NullabilityKind::NonNull)
8513       MergedKind = NullabilityKind::NonNull;
8514     else
8515       MergedKind = RHSKind;
8516   // Compute nullability of a normal conditional expression.
8517   } else {
8518     if (LHSKind == NullabilityKind::Nullable ||
8519         RHSKind == NullabilityKind::Nullable)
8520       MergedKind = NullabilityKind::Nullable;
8521     else if (LHSKind == NullabilityKind::NonNull)
8522       MergedKind = RHSKind;
8523     else if (RHSKind == NullabilityKind::NonNull)
8524       MergedKind = LHSKind;
8525     else
8526       MergedKind = NullabilityKind::Unspecified;
8527   }
8528 
8529   // Return if ResTy already has the correct nullability.
8530   if (GetNullability(ResTy) == MergedKind)
8531     return ResTy;
8532 
8533   // Strip all nullability from ResTy.
8534   while (ResTy->getNullability(Ctx))
8535     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8536 
8537   // Create a new AttributedType with the new nullability kind.
8538   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8539   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8540 }
8541 
8542 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8543 /// in the case of a the GNU conditional expr extension.
8544 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8545                                     SourceLocation ColonLoc,
8546                                     Expr *CondExpr, Expr *LHSExpr,
8547                                     Expr *RHSExpr) {
8548   if (!Context.isDependenceAllowed()) {
8549     // C cannot handle TypoExpr nodes in the condition because it
8550     // doesn't handle dependent types properly, so make sure any TypoExprs have
8551     // been dealt with before checking the operands.
8552     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8553     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8554     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8555 
8556     if (!CondResult.isUsable())
8557       return ExprError();
8558 
8559     if (LHSExpr) {
8560       if (!LHSResult.isUsable())
8561         return ExprError();
8562     }
8563 
8564     if (!RHSResult.isUsable())
8565       return ExprError();
8566 
8567     CondExpr = CondResult.get();
8568     LHSExpr = LHSResult.get();
8569     RHSExpr = RHSResult.get();
8570   }
8571 
8572   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8573   // was the condition.
8574   OpaqueValueExpr *opaqueValue = nullptr;
8575   Expr *commonExpr = nullptr;
8576   if (!LHSExpr) {
8577     commonExpr = CondExpr;
8578     // Lower out placeholder types first.  This is important so that we don't
8579     // try to capture a placeholder. This happens in few cases in C++; such
8580     // as Objective-C++'s dictionary subscripting syntax.
8581     if (commonExpr->hasPlaceholderType()) {
8582       ExprResult result = CheckPlaceholderExpr(commonExpr);
8583       if (!result.isUsable()) return ExprError();
8584       commonExpr = result.get();
8585     }
8586     // We usually want to apply unary conversions *before* saving, except
8587     // in the special case of a C++ l-value conditional.
8588     if (!(getLangOpts().CPlusPlus
8589           && !commonExpr->isTypeDependent()
8590           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8591           && commonExpr->isGLValue()
8592           && commonExpr->isOrdinaryOrBitFieldObject()
8593           && RHSExpr->isOrdinaryOrBitFieldObject()
8594           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8595       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8596       if (commonRes.isInvalid())
8597         return ExprError();
8598       commonExpr = commonRes.get();
8599     }
8600 
8601     // If the common expression is a class or array prvalue, materialize it
8602     // so that we can safely refer to it multiple times.
8603     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8604                                    commonExpr->getType()->isArrayType())) {
8605       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8606       if (MatExpr.isInvalid())
8607         return ExprError();
8608       commonExpr = MatExpr.get();
8609     }
8610 
8611     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8612                                                 commonExpr->getType(),
8613                                                 commonExpr->getValueKind(),
8614                                                 commonExpr->getObjectKind(),
8615                                                 commonExpr);
8616     LHSExpr = CondExpr = opaqueValue;
8617   }
8618 
8619   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8620   ExprValueKind VK = VK_RValue;
8621   ExprObjectKind OK = OK_Ordinary;
8622   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8623   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8624                                              VK, OK, QuestionLoc);
8625   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8626       RHS.isInvalid())
8627     return ExprError();
8628 
8629   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8630                                 RHS.get());
8631 
8632   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8633 
8634   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8635                                          Context);
8636 
8637   if (!commonExpr)
8638     return new (Context)
8639         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8640                             RHS.get(), result, VK, OK);
8641 
8642   return new (Context) BinaryConditionalOperator(
8643       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8644       ColonLoc, result, VK, OK);
8645 }
8646 
8647 // Check if we have a conversion between incompatible cmse function pointer
8648 // types, that is, a conversion between a function pointer with the
8649 // cmse_nonsecure_call attribute and one without.
8650 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8651                                           QualType ToType) {
8652   if (const auto *ToFn =
8653           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8654     if (const auto *FromFn =
8655             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8656       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8657       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8658 
8659       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8660     }
8661   }
8662   return false;
8663 }
8664 
8665 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8666 // being closely modeled after the C99 spec:-). The odd characteristic of this
8667 // routine is it effectively iqnores the qualifiers on the top level pointee.
8668 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8669 // FIXME: add a couple examples in this comment.
8670 static Sema::AssignConvertType
8671 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8672   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8673   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8674 
8675   // get the "pointed to" type (ignoring qualifiers at the top level)
8676   const Type *lhptee, *rhptee;
8677   Qualifiers lhq, rhq;
8678   std::tie(lhptee, lhq) =
8679       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8680   std::tie(rhptee, rhq) =
8681       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8682 
8683   Sema::AssignConvertType ConvTy = Sema::Compatible;
8684 
8685   // C99 6.5.16.1p1: This following citation is common to constraints
8686   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8687   // qualifiers of the type *pointed to* by the right;
8688 
8689   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8690   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8691       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8692     // Ignore lifetime for further calculation.
8693     lhq.removeObjCLifetime();
8694     rhq.removeObjCLifetime();
8695   }
8696 
8697   if (!lhq.compatiblyIncludes(rhq)) {
8698     // Treat address-space mismatches as fatal.
8699     if (!lhq.isAddressSpaceSupersetOf(rhq))
8700       return Sema::IncompatiblePointerDiscardsQualifiers;
8701 
8702     // It's okay to add or remove GC or lifetime qualifiers when converting to
8703     // and from void*.
8704     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8705                         .compatiblyIncludes(
8706                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8707              && (lhptee->isVoidType() || rhptee->isVoidType()))
8708       ; // keep old
8709 
8710     // Treat lifetime mismatches as fatal.
8711     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8712       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8713 
8714     // For GCC/MS compatibility, other qualifier mismatches are treated
8715     // as still compatible in C.
8716     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8717   }
8718 
8719   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8720   // incomplete type and the other is a pointer to a qualified or unqualified
8721   // version of void...
8722   if (lhptee->isVoidType()) {
8723     if (rhptee->isIncompleteOrObjectType())
8724       return ConvTy;
8725 
8726     // As an extension, we allow cast to/from void* to function pointer.
8727     assert(rhptee->isFunctionType());
8728     return Sema::FunctionVoidPointer;
8729   }
8730 
8731   if (rhptee->isVoidType()) {
8732     if (lhptee->isIncompleteOrObjectType())
8733       return ConvTy;
8734 
8735     // As an extension, we allow cast to/from void* to function pointer.
8736     assert(lhptee->isFunctionType());
8737     return Sema::FunctionVoidPointer;
8738   }
8739 
8740   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8741   // unqualified versions of compatible types, ...
8742   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8743   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8744     // Check if the pointee types are compatible ignoring the sign.
8745     // We explicitly check for char so that we catch "char" vs
8746     // "unsigned char" on systems where "char" is unsigned.
8747     if (lhptee->isCharType())
8748       ltrans = S.Context.UnsignedCharTy;
8749     else if (lhptee->hasSignedIntegerRepresentation())
8750       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8751 
8752     if (rhptee->isCharType())
8753       rtrans = S.Context.UnsignedCharTy;
8754     else if (rhptee->hasSignedIntegerRepresentation())
8755       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8756 
8757     if (ltrans == rtrans) {
8758       // Types are compatible ignoring the sign. Qualifier incompatibility
8759       // takes priority over sign incompatibility because the sign
8760       // warning can be disabled.
8761       if (ConvTy != Sema::Compatible)
8762         return ConvTy;
8763 
8764       return Sema::IncompatiblePointerSign;
8765     }
8766 
8767     // If we are a multi-level pointer, it's possible that our issue is simply
8768     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8769     // the eventual target type is the same and the pointers have the same
8770     // level of indirection, this must be the issue.
8771     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8772       do {
8773         std::tie(lhptee, lhq) =
8774           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8775         std::tie(rhptee, rhq) =
8776           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8777 
8778         // Inconsistent address spaces at this point is invalid, even if the
8779         // address spaces would be compatible.
8780         // FIXME: This doesn't catch address space mismatches for pointers of
8781         // different nesting levels, like:
8782         //   __local int *** a;
8783         //   int ** b = a;
8784         // It's not clear how to actually determine when such pointers are
8785         // invalidly incompatible.
8786         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8787           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8788 
8789       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8790 
8791       if (lhptee == rhptee)
8792         return Sema::IncompatibleNestedPointerQualifiers;
8793     }
8794 
8795     // General pointer incompatibility takes priority over qualifiers.
8796     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8797       return Sema::IncompatibleFunctionPointer;
8798     return Sema::IncompatiblePointer;
8799   }
8800   if (!S.getLangOpts().CPlusPlus &&
8801       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8802     return Sema::IncompatibleFunctionPointer;
8803   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8804     return Sema::IncompatibleFunctionPointer;
8805   return ConvTy;
8806 }
8807 
8808 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8809 /// block pointer types are compatible or whether a block and normal pointer
8810 /// are compatible. It is more restrict than comparing two function pointer
8811 // types.
8812 static Sema::AssignConvertType
8813 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8814                                     QualType RHSType) {
8815   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8816   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8817 
8818   QualType lhptee, rhptee;
8819 
8820   // get the "pointed to" type (ignoring qualifiers at the top level)
8821   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8822   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8823 
8824   // In C++, the types have to match exactly.
8825   if (S.getLangOpts().CPlusPlus)
8826     return Sema::IncompatibleBlockPointer;
8827 
8828   Sema::AssignConvertType ConvTy = Sema::Compatible;
8829 
8830   // For blocks we enforce that qualifiers are identical.
8831   Qualifiers LQuals = lhptee.getLocalQualifiers();
8832   Qualifiers RQuals = rhptee.getLocalQualifiers();
8833   if (S.getLangOpts().OpenCL) {
8834     LQuals.removeAddressSpace();
8835     RQuals.removeAddressSpace();
8836   }
8837   if (LQuals != RQuals)
8838     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8839 
8840   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8841   // assignment.
8842   // The current behavior is similar to C++ lambdas. A block might be
8843   // assigned to a variable iff its return type and parameters are compatible
8844   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8845   // an assignment. Presumably it should behave in way that a function pointer
8846   // assignment does in C, so for each parameter and return type:
8847   //  * CVR and address space of LHS should be a superset of CVR and address
8848   //  space of RHS.
8849   //  * unqualified types should be compatible.
8850   if (S.getLangOpts().OpenCL) {
8851     if (!S.Context.typesAreBlockPointerCompatible(
8852             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8853             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8854       return Sema::IncompatibleBlockPointer;
8855   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8856     return Sema::IncompatibleBlockPointer;
8857 
8858   return ConvTy;
8859 }
8860 
8861 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8862 /// for assignment compatibility.
8863 static Sema::AssignConvertType
8864 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8865                                    QualType RHSType) {
8866   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8867   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8868 
8869   if (LHSType->isObjCBuiltinType()) {
8870     // Class is not compatible with ObjC object pointers.
8871     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8872         !RHSType->isObjCQualifiedClassType())
8873       return Sema::IncompatiblePointer;
8874     return Sema::Compatible;
8875   }
8876   if (RHSType->isObjCBuiltinType()) {
8877     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8878         !LHSType->isObjCQualifiedClassType())
8879       return Sema::IncompatiblePointer;
8880     return Sema::Compatible;
8881   }
8882   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8883   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8884 
8885   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8886       // make an exception for id<P>
8887       !LHSType->isObjCQualifiedIdType())
8888     return Sema::CompatiblePointerDiscardsQualifiers;
8889 
8890   if (S.Context.typesAreCompatible(LHSType, RHSType))
8891     return Sema::Compatible;
8892   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8893     return Sema::IncompatibleObjCQualifiedId;
8894   return Sema::IncompatiblePointer;
8895 }
8896 
8897 Sema::AssignConvertType
8898 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8899                                  QualType LHSType, QualType RHSType) {
8900   // Fake up an opaque expression.  We don't actually care about what
8901   // cast operations are required, so if CheckAssignmentConstraints
8902   // adds casts to this they'll be wasted, but fortunately that doesn't
8903   // usually happen on valid code.
8904   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8905   ExprResult RHSPtr = &RHSExpr;
8906   CastKind K;
8907 
8908   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8909 }
8910 
8911 /// This helper function returns true if QT is a vector type that has element
8912 /// type ElementType.
8913 static bool isVector(QualType QT, QualType ElementType) {
8914   if (const VectorType *VT = QT->getAs<VectorType>())
8915     return VT->getElementType().getCanonicalType() == ElementType;
8916   return false;
8917 }
8918 
8919 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8920 /// has code to accommodate several GCC extensions when type checking
8921 /// pointers. Here are some objectionable examples that GCC considers warnings:
8922 ///
8923 ///  int a, *pint;
8924 ///  short *pshort;
8925 ///  struct foo *pfoo;
8926 ///
8927 ///  pint = pshort; // warning: assignment from incompatible pointer type
8928 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8929 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8930 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8931 ///
8932 /// As a result, the code for dealing with pointers is more complex than the
8933 /// C99 spec dictates.
8934 ///
8935 /// Sets 'Kind' for any result kind except Incompatible.
8936 Sema::AssignConvertType
8937 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8938                                  CastKind &Kind, bool ConvertRHS) {
8939   QualType RHSType = RHS.get()->getType();
8940   QualType OrigLHSType = LHSType;
8941 
8942   // Get canonical types.  We're not formatting these types, just comparing
8943   // them.
8944   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8945   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8946 
8947   // Common case: no conversion required.
8948   if (LHSType == RHSType) {
8949     Kind = CK_NoOp;
8950     return Compatible;
8951   }
8952 
8953   // If we have an atomic type, try a non-atomic assignment, then just add an
8954   // atomic qualification step.
8955   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8956     Sema::AssignConvertType result =
8957       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8958     if (result != Compatible)
8959       return result;
8960     if (Kind != CK_NoOp && ConvertRHS)
8961       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8962     Kind = CK_NonAtomicToAtomic;
8963     return Compatible;
8964   }
8965 
8966   // If the left-hand side is a reference type, then we are in a
8967   // (rare!) case where we've allowed the use of references in C,
8968   // e.g., as a parameter type in a built-in function. In this case,
8969   // just make sure that the type referenced is compatible with the
8970   // right-hand side type. The caller is responsible for adjusting
8971   // LHSType so that the resulting expression does not have reference
8972   // type.
8973   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8974     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8975       Kind = CK_LValueBitCast;
8976       return Compatible;
8977     }
8978     return Incompatible;
8979   }
8980 
8981   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8982   // to the same ExtVector type.
8983   if (LHSType->isExtVectorType()) {
8984     if (RHSType->isExtVectorType())
8985       return Incompatible;
8986     if (RHSType->isArithmeticType()) {
8987       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8988       if (ConvertRHS)
8989         RHS = prepareVectorSplat(LHSType, RHS.get());
8990       Kind = CK_VectorSplat;
8991       return Compatible;
8992     }
8993   }
8994 
8995   // Conversions to or from vector type.
8996   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8997     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8998       // Allow assignments of an AltiVec vector type to an equivalent GCC
8999       // vector type and vice versa
9000       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9001         Kind = CK_BitCast;
9002         return Compatible;
9003       }
9004 
9005       // If we are allowing lax vector conversions, and LHS and RHS are both
9006       // vectors, the total size only needs to be the same. This is a bitcast;
9007       // no bits are changed but the result type is different.
9008       if (isLaxVectorConversion(RHSType, LHSType)) {
9009         Kind = CK_BitCast;
9010         return IncompatibleVectors;
9011       }
9012     }
9013 
9014     // When the RHS comes from another lax conversion (e.g. binops between
9015     // scalars and vectors) the result is canonicalized as a vector. When the
9016     // LHS is also a vector, the lax is allowed by the condition above. Handle
9017     // the case where LHS is a scalar.
9018     if (LHSType->isScalarType()) {
9019       const VectorType *VecType = RHSType->getAs<VectorType>();
9020       if (VecType && VecType->getNumElements() == 1 &&
9021           isLaxVectorConversion(RHSType, LHSType)) {
9022         ExprResult *VecExpr = &RHS;
9023         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9024         Kind = CK_BitCast;
9025         return Compatible;
9026       }
9027     }
9028 
9029     // Allow assignments between fixed-length and sizeless SVE vectors.
9030     if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9031         (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9032       if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9033           Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9034         Kind = CK_BitCast;
9035         return Compatible;
9036       }
9037 
9038     return Incompatible;
9039   }
9040 
9041   // Diagnose attempts to convert between __float128 and long double where
9042   // such conversions currently can't be handled.
9043   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9044     return Incompatible;
9045 
9046   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9047   // discards the imaginary part.
9048   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9049       !LHSType->getAs<ComplexType>())
9050     return Incompatible;
9051 
9052   // Arithmetic conversions.
9053   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9054       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9055     if (ConvertRHS)
9056       Kind = PrepareScalarCast(RHS, LHSType);
9057     return Compatible;
9058   }
9059 
9060   // Conversions to normal pointers.
9061   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9062     // U* -> T*
9063     if (isa<PointerType>(RHSType)) {
9064       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9065       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9066       if (AddrSpaceL != AddrSpaceR)
9067         Kind = CK_AddressSpaceConversion;
9068       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9069         Kind = CK_NoOp;
9070       else
9071         Kind = CK_BitCast;
9072       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9073     }
9074 
9075     // int -> T*
9076     if (RHSType->isIntegerType()) {
9077       Kind = CK_IntegralToPointer; // FIXME: null?
9078       return IntToPointer;
9079     }
9080 
9081     // C pointers are not compatible with ObjC object pointers,
9082     // with two exceptions:
9083     if (isa<ObjCObjectPointerType>(RHSType)) {
9084       //  - conversions to void*
9085       if (LHSPointer->getPointeeType()->isVoidType()) {
9086         Kind = CK_BitCast;
9087         return Compatible;
9088       }
9089 
9090       //  - conversions from 'Class' to the redefinition type
9091       if (RHSType->isObjCClassType() &&
9092           Context.hasSameType(LHSType,
9093                               Context.getObjCClassRedefinitionType())) {
9094         Kind = CK_BitCast;
9095         return Compatible;
9096       }
9097 
9098       Kind = CK_BitCast;
9099       return IncompatiblePointer;
9100     }
9101 
9102     // U^ -> void*
9103     if (RHSType->getAs<BlockPointerType>()) {
9104       if (LHSPointer->getPointeeType()->isVoidType()) {
9105         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9106         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9107                                 ->getPointeeType()
9108                                 .getAddressSpace();
9109         Kind =
9110             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9111         return Compatible;
9112       }
9113     }
9114 
9115     return Incompatible;
9116   }
9117 
9118   // Conversions to block pointers.
9119   if (isa<BlockPointerType>(LHSType)) {
9120     // U^ -> T^
9121     if (RHSType->isBlockPointerType()) {
9122       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9123                               ->getPointeeType()
9124                               .getAddressSpace();
9125       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9126                               ->getPointeeType()
9127                               .getAddressSpace();
9128       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9129       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9130     }
9131 
9132     // int or null -> T^
9133     if (RHSType->isIntegerType()) {
9134       Kind = CK_IntegralToPointer; // FIXME: null
9135       return IntToBlockPointer;
9136     }
9137 
9138     // id -> T^
9139     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9140       Kind = CK_AnyPointerToBlockPointerCast;
9141       return Compatible;
9142     }
9143 
9144     // void* -> T^
9145     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9146       if (RHSPT->getPointeeType()->isVoidType()) {
9147         Kind = CK_AnyPointerToBlockPointerCast;
9148         return Compatible;
9149       }
9150 
9151     return Incompatible;
9152   }
9153 
9154   // Conversions to Objective-C pointers.
9155   if (isa<ObjCObjectPointerType>(LHSType)) {
9156     // A* -> B*
9157     if (RHSType->isObjCObjectPointerType()) {
9158       Kind = CK_BitCast;
9159       Sema::AssignConvertType result =
9160         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9161       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9162           result == Compatible &&
9163           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9164         result = IncompatibleObjCWeakRef;
9165       return result;
9166     }
9167 
9168     // int or null -> A*
9169     if (RHSType->isIntegerType()) {
9170       Kind = CK_IntegralToPointer; // FIXME: null
9171       return IntToPointer;
9172     }
9173 
9174     // In general, C pointers are not compatible with ObjC object pointers,
9175     // with two exceptions:
9176     if (isa<PointerType>(RHSType)) {
9177       Kind = CK_CPointerToObjCPointerCast;
9178 
9179       //  - conversions from 'void*'
9180       if (RHSType->isVoidPointerType()) {
9181         return Compatible;
9182       }
9183 
9184       //  - conversions to 'Class' from its redefinition type
9185       if (LHSType->isObjCClassType() &&
9186           Context.hasSameType(RHSType,
9187                               Context.getObjCClassRedefinitionType())) {
9188         return Compatible;
9189       }
9190 
9191       return IncompatiblePointer;
9192     }
9193 
9194     // Only under strict condition T^ is compatible with an Objective-C pointer.
9195     if (RHSType->isBlockPointerType() &&
9196         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9197       if (ConvertRHS)
9198         maybeExtendBlockObject(RHS);
9199       Kind = CK_BlockPointerToObjCPointerCast;
9200       return Compatible;
9201     }
9202 
9203     return Incompatible;
9204   }
9205 
9206   // Conversions from pointers that are not covered by the above.
9207   if (isa<PointerType>(RHSType)) {
9208     // T* -> _Bool
9209     if (LHSType == Context.BoolTy) {
9210       Kind = CK_PointerToBoolean;
9211       return Compatible;
9212     }
9213 
9214     // T* -> int
9215     if (LHSType->isIntegerType()) {
9216       Kind = CK_PointerToIntegral;
9217       return PointerToInt;
9218     }
9219 
9220     return Incompatible;
9221   }
9222 
9223   // Conversions from Objective-C pointers that are not covered by the above.
9224   if (isa<ObjCObjectPointerType>(RHSType)) {
9225     // T* -> _Bool
9226     if (LHSType == Context.BoolTy) {
9227       Kind = CK_PointerToBoolean;
9228       return Compatible;
9229     }
9230 
9231     // T* -> int
9232     if (LHSType->isIntegerType()) {
9233       Kind = CK_PointerToIntegral;
9234       return PointerToInt;
9235     }
9236 
9237     return Incompatible;
9238   }
9239 
9240   // struct A -> struct B
9241   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9242     if (Context.typesAreCompatible(LHSType, RHSType)) {
9243       Kind = CK_NoOp;
9244       return Compatible;
9245     }
9246   }
9247 
9248   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9249     Kind = CK_IntToOCLSampler;
9250     return Compatible;
9251   }
9252 
9253   return Incompatible;
9254 }
9255 
9256 /// Constructs a transparent union from an expression that is
9257 /// used to initialize the transparent union.
9258 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9259                                       ExprResult &EResult, QualType UnionType,
9260                                       FieldDecl *Field) {
9261   // Build an initializer list that designates the appropriate member
9262   // of the transparent union.
9263   Expr *E = EResult.get();
9264   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9265                                                    E, SourceLocation());
9266   Initializer->setType(UnionType);
9267   Initializer->setInitializedFieldInUnion(Field);
9268 
9269   // Build a compound literal constructing a value of the transparent
9270   // union type from this initializer list.
9271   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9272   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9273                                         VK_RValue, Initializer, false);
9274 }
9275 
9276 Sema::AssignConvertType
9277 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9278                                                ExprResult &RHS) {
9279   QualType RHSType = RHS.get()->getType();
9280 
9281   // If the ArgType is a Union type, we want to handle a potential
9282   // transparent_union GCC extension.
9283   const RecordType *UT = ArgType->getAsUnionType();
9284   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9285     return Incompatible;
9286 
9287   // The field to initialize within the transparent union.
9288   RecordDecl *UD = UT->getDecl();
9289   FieldDecl *InitField = nullptr;
9290   // It's compatible if the expression matches any of the fields.
9291   for (auto *it : UD->fields()) {
9292     if (it->getType()->isPointerType()) {
9293       // If the transparent union contains a pointer type, we allow:
9294       // 1) void pointer
9295       // 2) null pointer constant
9296       if (RHSType->isPointerType())
9297         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9298           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9299           InitField = it;
9300           break;
9301         }
9302 
9303       if (RHS.get()->isNullPointerConstant(Context,
9304                                            Expr::NPC_ValueDependentIsNull)) {
9305         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9306                                 CK_NullToPointer);
9307         InitField = it;
9308         break;
9309       }
9310     }
9311 
9312     CastKind Kind;
9313     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9314           == Compatible) {
9315       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9316       InitField = it;
9317       break;
9318     }
9319   }
9320 
9321   if (!InitField)
9322     return Incompatible;
9323 
9324   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9325   return Compatible;
9326 }
9327 
9328 Sema::AssignConvertType
9329 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9330                                        bool Diagnose,
9331                                        bool DiagnoseCFAudited,
9332                                        bool ConvertRHS) {
9333   // We need to be able to tell the caller whether we diagnosed a problem, if
9334   // they ask us to issue diagnostics.
9335   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9336 
9337   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9338   // we can't avoid *all* modifications at the moment, so we need some somewhere
9339   // to put the updated value.
9340   ExprResult LocalRHS = CallerRHS;
9341   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9342 
9343   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9344     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9345       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9346           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9347         Diag(RHS.get()->getExprLoc(),
9348              diag::warn_noderef_to_dereferenceable_pointer)
9349             << RHS.get()->getSourceRange();
9350       }
9351     }
9352   }
9353 
9354   if (getLangOpts().CPlusPlus) {
9355     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9356       // C++ 5.17p3: If the left operand is not of class type, the
9357       // expression is implicitly converted (C++ 4) to the
9358       // cv-unqualified type of the left operand.
9359       QualType RHSType = RHS.get()->getType();
9360       if (Diagnose) {
9361         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9362                                         AA_Assigning);
9363       } else {
9364         ImplicitConversionSequence ICS =
9365             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9366                                   /*SuppressUserConversions=*/false,
9367                                   AllowedExplicit::None,
9368                                   /*InOverloadResolution=*/false,
9369                                   /*CStyle=*/false,
9370                                   /*AllowObjCWritebackConversion=*/false);
9371         if (ICS.isFailure())
9372           return Incompatible;
9373         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9374                                         ICS, AA_Assigning);
9375       }
9376       if (RHS.isInvalid())
9377         return Incompatible;
9378       Sema::AssignConvertType result = Compatible;
9379       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9380           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9381         result = IncompatibleObjCWeakRef;
9382       return result;
9383     }
9384 
9385     // FIXME: Currently, we fall through and treat C++ classes like C
9386     // structures.
9387     // FIXME: We also fall through for atomics; not sure what should
9388     // happen there, though.
9389   } else if (RHS.get()->getType() == Context.OverloadTy) {
9390     // As a set of extensions to C, we support overloading on functions. These
9391     // functions need to be resolved here.
9392     DeclAccessPair DAP;
9393     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9394             RHS.get(), LHSType, /*Complain=*/false, DAP))
9395       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9396     else
9397       return Incompatible;
9398   }
9399 
9400   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9401   // a null pointer constant.
9402   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9403        LHSType->isBlockPointerType()) &&
9404       RHS.get()->isNullPointerConstant(Context,
9405                                        Expr::NPC_ValueDependentIsNull)) {
9406     if (Diagnose || ConvertRHS) {
9407       CastKind Kind;
9408       CXXCastPath Path;
9409       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9410                              /*IgnoreBaseAccess=*/false, Diagnose);
9411       if (ConvertRHS)
9412         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9413     }
9414     return Compatible;
9415   }
9416 
9417   // OpenCL queue_t type assignment.
9418   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9419                                  Context, Expr::NPC_ValueDependentIsNull)) {
9420     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9421     return Compatible;
9422   }
9423 
9424   // This check seems unnatural, however it is necessary to ensure the proper
9425   // conversion of functions/arrays. If the conversion were done for all
9426   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9427   // expressions that suppress this implicit conversion (&, sizeof).
9428   //
9429   // Suppress this for references: C++ 8.5.3p5.
9430   if (!LHSType->isReferenceType()) {
9431     // FIXME: We potentially allocate here even if ConvertRHS is false.
9432     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9433     if (RHS.isInvalid())
9434       return Incompatible;
9435   }
9436   CastKind Kind;
9437   Sema::AssignConvertType result =
9438     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9439 
9440   // C99 6.5.16.1p2: The value of the right operand is converted to the
9441   // type of the assignment expression.
9442   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9443   // so that we can use references in built-in functions even in C.
9444   // The getNonReferenceType() call makes sure that the resulting expression
9445   // does not have reference type.
9446   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9447     QualType Ty = LHSType.getNonLValueExprType(Context);
9448     Expr *E = RHS.get();
9449 
9450     // Check for various Objective-C errors. If we are not reporting
9451     // diagnostics and just checking for errors, e.g., during overload
9452     // resolution, return Incompatible to indicate the failure.
9453     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9454         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9455                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9456       if (!Diagnose)
9457         return Incompatible;
9458     }
9459     if (getLangOpts().ObjC &&
9460         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9461                                            E->getType(), E, Diagnose) ||
9462          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9463       if (!Diagnose)
9464         return Incompatible;
9465       // Replace the expression with a corrected version and continue so we
9466       // can find further errors.
9467       RHS = E;
9468       return Compatible;
9469     }
9470 
9471     if (ConvertRHS)
9472       RHS = ImpCastExprToType(E, Ty, Kind);
9473   }
9474 
9475   return result;
9476 }
9477 
9478 namespace {
9479 /// The original operand to an operator, prior to the application of the usual
9480 /// arithmetic conversions and converting the arguments of a builtin operator
9481 /// candidate.
9482 struct OriginalOperand {
9483   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9484     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9485       Op = MTE->getSubExpr();
9486     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9487       Op = BTE->getSubExpr();
9488     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9489       Orig = ICE->getSubExprAsWritten();
9490       Conversion = ICE->getConversionFunction();
9491     }
9492   }
9493 
9494   QualType getType() const { return Orig->getType(); }
9495 
9496   Expr *Orig;
9497   NamedDecl *Conversion;
9498 };
9499 }
9500 
9501 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9502                                ExprResult &RHS) {
9503   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9504 
9505   Diag(Loc, diag::err_typecheck_invalid_operands)
9506     << OrigLHS.getType() << OrigRHS.getType()
9507     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9508 
9509   // If a user-defined conversion was applied to either of the operands prior
9510   // to applying the built-in operator rules, tell the user about it.
9511   if (OrigLHS.Conversion) {
9512     Diag(OrigLHS.Conversion->getLocation(),
9513          diag::note_typecheck_invalid_operands_converted)
9514       << 0 << LHS.get()->getType();
9515   }
9516   if (OrigRHS.Conversion) {
9517     Diag(OrigRHS.Conversion->getLocation(),
9518          diag::note_typecheck_invalid_operands_converted)
9519       << 1 << RHS.get()->getType();
9520   }
9521 
9522   return QualType();
9523 }
9524 
9525 // Diagnose cases where a scalar was implicitly converted to a vector and
9526 // diagnose the underlying types. Otherwise, diagnose the error
9527 // as invalid vector logical operands for non-C++ cases.
9528 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9529                                             ExprResult &RHS) {
9530   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9531   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9532 
9533   bool LHSNatVec = LHSType->isVectorType();
9534   bool RHSNatVec = RHSType->isVectorType();
9535 
9536   if (!(LHSNatVec && RHSNatVec)) {
9537     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9538     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9539     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9540         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9541         << Vector->getSourceRange();
9542     return QualType();
9543   }
9544 
9545   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9546       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9547       << RHS.get()->getSourceRange();
9548 
9549   return QualType();
9550 }
9551 
9552 /// Try to convert a value of non-vector type to a vector type by converting
9553 /// the type to the element type of the vector and then performing a splat.
9554 /// If the language is OpenCL, we only use conversions that promote scalar
9555 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9556 /// for float->int.
9557 ///
9558 /// OpenCL V2.0 6.2.6.p2:
9559 /// An error shall occur if any scalar operand type has greater rank
9560 /// than the type of the vector element.
9561 ///
9562 /// \param scalar - if non-null, actually perform the conversions
9563 /// \return true if the operation fails (but without diagnosing the failure)
9564 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9565                                      QualType scalarTy,
9566                                      QualType vectorEltTy,
9567                                      QualType vectorTy,
9568                                      unsigned &DiagID) {
9569   // The conversion to apply to the scalar before splatting it,
9570   // if necessary.
9571   CastKind scalarCast = CK_NoOp;
9572 
9573   if (vectorEltTy->isIntegralType(S.Context)) {
9574     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9575         (scalarTy->isIntegerType() &&
9576          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9577       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9578       return true;
9579     }
9580     if (!scalarTy->isIntegralType(S.Context))
9581       return true;
9582     scalarCast = CK_IntegralCast;
9583   } else if (vectorEltTy->isRealFloatingType()) {
9584     if (scalarTy->isRealFloatingType()) {
9585       if (S.getLangOpts().OpenCL &&
9586           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9587         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9588         return true;
9589       }
9590       scalarCast = CK_FloatingCast;
9591     }
9592     else if (scalarTy->isIntegralType(S.Context))
9593       scalarCast = CK_IntegralToFloating;
9594     else
9595       return true;
9596   } else {
9597     return true;
9598   }
9599 
9600   // Adjust scalar if desired.
9601   if (scalar) {
9602     if (scalarCast != CK_NoOp)
9603       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9604     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9605   }
9606   return false;
9607 }
9608 
9609 /// Convert vector E to a vector with the same number of elements but different
9610 /// element type.
9611 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9612   const auto *VecTy = E->getType()->getAs<VectorType>();
9613   assert(VecTy && "Expression E must be a vector");
9614   QualType NewVecTy = S.Context.getVectorType(ElementType,
9615                                               VecTy->getNumElements(),
9616                                               VecTy->getVectorKind());
9617 
9618   // Look through the implicit cast. Return the subexpression if its type is
9619   // NewVecTy.
9620   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9621     if (ICE->getSubExpr()->getType() == NewVecTy)
9622       return ICE->getSubExpr();
9623 
9624   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9625   return S.ImpCastExprToType(E, NewVecTy, Cast);
9626 }
9627 
9628 /// Test if a (constant) integer Int can be casted to another integer type
9629 /// IntTy without losing precision.
9630 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9631                                       QualType OtherIntTy) {
9632   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9633 
9634   // Reject cases where the value of the Int is unknown as that would
9635   // possibly cause truncation, but accept cases where the scalar can be
9636   // demoted without loss of precision.
9637   Expr::EvalResult EVResult;
9638   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9639   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9640   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9641   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9642 
9643   if (CstInt) {
9644     // If the scalar is constant and is of a higher order and has more active
9645     // bits that the vector element type, reject it.
9646     llvm::APSInt Result = EVResult.Val.getInt();
9647     unsigned NumBits = IntSigned
9648                            ? (Result.isNegative() ? Result.getMinSignedBits()
9649                                                   : Result.getActiveBits())
9650                            : Result.getActiveBits();
9651     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9652       return true;
9653 
9654     // If the signedness of the scalar type and the vector element type
9655     // differs and the number of bits is greater than that of the vector
9656     // element reject it.
9657     return (IntSigned != OtherIntSigned &&
9658             NumBits > S.Context.getIntWidth(OtherIntTy));
9659   }
9660 
9661   // Reject cases where the value of the scalar is not constant and it's
9662   // order is greater than that of the vector element type.
9663   return (Order < 0);
9664 }
9665 
9666 /// Test if a (constant) integer Int can be casted to floating point type
9667 /// FloatTy without losing precision.
9668 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9669                                      QualType FloatTy) {
9670   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9671 
9672   // Determine if the integer constant can be expressed as a floating point
9673   // number of the appropriate type.
9674   Expr::EvalResult EVResult;
9675   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9676 
9677   uint64_t Bits = 0;
9678   if (CstInt) {
9679     // Reject constants that would be truncated if they were converted to
9680     // the floating point type. Test by simple to/from conversion.
9681     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9682     //        could be avoided if there was a convertFromAPInt method
9683     //        which could signal back if implicit truncation occurred.
9684     llvm::APSInt Result = EVResult.Val.getInt();
9685     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9686     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9687                            llvm::APFloat::rmTowardZero);
9688     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9689                              !IntTy->hasSignedIntegerRepresentation());
9690     bool Ignored = false;
9691     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9692                            &Ignored);
9693     if (Result != ConvertBack)
9694       return true;
9695   } else {
9696     // Reject types that cannot be fully encoded into the mantissa of
9697     // the float.
9698     Bits = S.Context.getTypeSize(IntTy);
9699     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9700         S.Context.getFloatTypeSemantics(FloatTy));
9701     if (Bits > FloatPrec)
9702       return true;
9703   }
9704 
9705   return false;
9706 }
9707 
9708 /// Attempt to convert and splat Scalar into a vector whose types matches
9709 /// Vector following GCC conversion rules. The rule is that implicit
9710 /// conversion can occur when Scalar can be casted to match Vector's element
9711 /// type without causing truncation of Scalar.
9712 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9713                                         ExprResult *Vector) {
9714   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9715   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9716   const VectorType *VT = VectorTy->getAs<VectorType>();
9717 
9718   assert(!isa<ExtVectorType>(VT) &&
9719          "ExtVectorTypes should not be handled here!");
9720 
9721   QualType VectorEltTy = VT->getElementType();
9722 
9723   // Reject cases where the vector element type or the scalar element type are
9724   // not integral or floating point types.
9725   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9726     return true;
9727 
9728   // The conversion to apply to the scalar before splatting it,
9729   // if necessary.
9730   CastKind ScalarCast = CK_NoOp;
9731 
9732   // Accept cases where the vector elements are integers and the scalar is
9733   // an integer.
9734   // FIXME: Notionally if the scalar was a floating point value with a precise
9735   //        integral representation, we could cast it to an appropriate integer
9736   //        type and then perform the rest of the checks here. GCC will perform
9737   //        this conversion in some cases as determined by the input language.
9738   //        We should accept it on a language independent basis.
9739   if (VectorEltTy->isIntegralType(S.Context) &&
9740       ScalarTy->isIntegralType(S.Context) &&
9741       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9742 
9743     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9744       return true;
9745 
9746     ScalarCast = CK_IntegralCast;
9747   } else if (VectorEltTy->isIntegralType(S.Context) &&
9748              ScalarTy->isRealFloatingType()) {
9749     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9750       ScalarCast = CK_FloatingToIntegral;
9751     else
9752       return true;
9753   } else if (VectorEltTy->isRealFloatingType()) {
9754     if (ScalarTy->isRealFloatingType()) {
9755 
9756       // Reject cases where the scalar type is not a constant and has a higher
9757       // Order than the vector element type.
9758       llvm::APFloat Result(0.0);
9759 
9760       // Determine whether this is a constant scalar. In the event that the
9761       // value is dependent (and thus cannot be evaluated by the constant
9762       // evaluator), skip the evaluation. This will then diagnose once the
9763       // expression is instantiated.
9764       bool CstScalar = Scalar->get()->isValueDependent() ||
9765                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9766       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9767       if (!CstScalar && Order < 0)
9768         return true;
9769 
9770       // If the scalar cannot be safely casted to the vector element type,
9771       // reject it.
9772       if (CstScalar) {
9773         bool Truncated = false;
9774         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9775                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9776         if (Truncated)
9777           return true;
9778       }
9779 
9780       ScalarCast = CK_FloatingCast;
9781     } else if (ScalarTy->isIntegralType(S.Context)) {
9782       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9783         return true;
9784 
9785       ScalarCast = CK_IntegralToFloating;
9786     } else
9787       return true;
9788   } else if (ScalarTy->isEnumeralType())
9789     return true;
9790 
9791   // Adjust scalar if desired.
9792   if (Scalar) {
9793     if (ScalarCast != CK_NoOp)
9794       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9795     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9796   }
9797   return false;
9798 }
9799 
9800 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9801                                    SourceLocation Loc, bool IsCompAssign,
9802                                    bool AllowBothBool,
9803                                    bool AllowBoolConversions) {
9804   if (!IsCompAssign) {
9805     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9806     if (LHS.isInvalid())
9807       return QualType();
9808   }
9809   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9810   if (RHS.isInvalid())
9811     return QualType();
9812 
9813   // For conversion purposes, we ignore any qualifiers.
9814   // For example, "const float" and "float" are equivalent.
9815   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9816   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9817 
9818   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9819   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9820   assert(LHSVecType || RHSVecType);
9821 
9822   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
9823       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
9824     return InvalidOperands(Loc, LHS, RHS);
9825 
9826   // AltiVec-style "vector bool op vector bool" combinations are allowed
9827   // for some operators but not others.
9828   if (!AllowBothBool &&
9829       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9830       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9831     return InvalidOperands(Loc, LHS, RHS);
9832 
9833   // If the vector types are identical, return.
9834   if (Context.hasSameType(LHSType, RHSType))
9835     return LHSType;
9836 
9837   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9838   if (LHSVecType && RHSVecType &&
9839       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9840     if (isa<ExtVectorType>(LHSVecType)) {
9841       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9842       return LHSType;
9843     }
9844 
9845     if (!IsCompAssign)
9846       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9847     return RHSType;
9848   }
9849 
9850   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9851   // can be mixed, with the result being the non-bool type.  The non-bool
9852   // operand must have integer element type.
9853   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9854       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9855       (Context.getTypeSize(LHSVecType->getElementType()) ==
9856        Context.getTypeSize(RHSVecType->getElementType()))) {
9857     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9858         LHSVecType->getElementType()->isIntegerType() &&
9859         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9860       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9861       return LHSType;
9862     }
9863     if (!IsCompAssign &&
9864         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9865         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9866         RHSVecType->getElementType()->isIntegerType()) {
9867       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9868       return RHSType;
9869     }
9870   }
9871 
9872   // Expressions containing fixed-length and sizeless SVE vectors are invalid
9873   // since the ambiguity can affect the ABI.
9874   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
9875     const VectorType *VecType = SecondType->getAs<VectorType>();
9876     return FirstType->isSizelessBuiltinType() && VecType &&
9877            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
9878             VecType->getVectorKind() ==
9879                 VectorType::SveFixedLengthPredicateVector);
9880   };
9881 
9882   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
9883     Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
9884     return QualType();
9885   }
9886 
9887   // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
9888   // since the ambiguity can affect the ABI.
9889   auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
9890     const VectorType *FirstVecType = FirstType->getAs<VectorType>();
9891     const VectorType *SecondVecType = SecondType->getAs<VectorType>();
9892 
9893     if (FirstVecType && SecondVecType)
9894       return FirstVecType->getVectorKind() == VectorType::GenericVector &&
9895              (SecondVecType->getVectorKind() ==
9896                   VectorType::SveFixedLengthDataVector ||
9897               SecondVecType->getVectorKind() ==
9898                   VectorType::SveFixedLengthPredicateVector);
9899 
9900     return FirstType->isSizelessBuiltinType() && SecondVecType &&
9901            SecondVecType->getVectorKind() == VectorType::GenericVector;
9902   };
9903 
9904   if (IsSveGnuConversion(LHSType, RHSType) ||
9905       IsSveGnuConversion(RHSType, LHSType)) {
9906     Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
9907     return QualType();
9908   }
9909 
9910   // If there's a vector type and a scalar, try to convert the scalar to
9911   // the vector element type and splat.
9912   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9913   if (!RHSVecType) {
9914     if (isa<ExtVectorType>(LHSVecType)) {
9915       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9916                                     LHSVecType->getElementType(), LHSType,
9917                                     DiagID))
9918         return LHSType;
9919     } else {
9920       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9921         return LHSType;
9922     }
9923   }
9924   if (!LHSVecType) {
9925     if (isa<ExtVectorType>(RHSVecType)) {
9926       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9927                                     LHSType, RHSVecType->getElementType(),
9928                                     RHSType, DiagID))
9929         return RHSType;
9930     } else {
9931       if (LHS.get()->getValueKind() == VK_LValue ||
9932           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9933         return RHSType;
9934     }
9935   }
9936 
9937   // FIXME: The code below also handles conversion between vectors and
9938   // non-scalars, we should break this down into fine grained specific checks
9939   // and emit proper diagnostics.
9940   QualType VecType = LHSVecType ? LHSType : RHSType;
9941   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9942   QualType OtherType = LHSVecType ? RHSType : LHSType;
9943   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9944   if (isLaxVectorConversion(OtherType, VecType)) {
9945     // If we're allowing lax vector conversions, only the total (data) size
9946     // needs to be the same. For non compound assignment, if one of the types is
9947     // scalar, the result is always the vector type.
9948     if (!IsCompAssign) {
9949       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9950       return VecType;
9951     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9952     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9953     // type. Note that this is already done by non-compound assignments in
9954     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9955     // <1 x T> -> T. The result is also a vector type.
9956     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9957                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9958       ExprResult *RHSExpr = &RHS;
9959       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9960       return VecType;
9961     }
9962   }
9963 
9964   // Okay, the expression is invalid.
9965 
9966   // If there's a non-vector, non-real operand, diagnose that.
9967   if ((!RHSVecType && !RHSType->isRealType()) ||
9968       (!LHSVecType && !LHSType->isRealType())) {
9969     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9970       << LHSType << RHSType
9971       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9972     return QualType();
9973   }
9974 
9975   // OpenCL V1.1 6.2.6.p1:
9976   // If the operands are of more than one vector type, then an error shall
9977   // occur. Implicit conversions between vector types are not permitted, per
9978   // section 6.2.1.
9979   if (getLangOpts().OpenCL &&
9980       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9981       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9982     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9983                                                            << RHSType;
9984     return QualType();
9985   }
9986 
9987 
9988   // If there is a vector type that is not a ExtVector and a scalar, we reach
9989   // this point if scalar could not be converted to the vector's element type
9990   // without truncation.
9991   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9992       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9993     QualType Scalar = LHSVecType ? RHSType : LHSType;
9994     QualType Vector = LHSVecType ? LHSType : RHSType;
9995     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9996     Diag(Loc,
9997          diag::err_typecheck_vector_not_convertable_implict_truncation)
9998         << ScalarOrVector << Scalar << Vector;
9999 
10000     return QualType();
10001   }
10002 
10003   // Otherwise, use the generic diagnostic.
10004   Diag(Loc, DiagID)
10005     << LHSType << RHSType
10006     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10007   return QualType();
10008 }
10009 
10010 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10011 // expression.  These are mainly cases where the null pointer is used as an
10012 // integer instead of a pointer.
10013 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10014                                 SourceLocation Loc, bool IsCompare) {
10015   // The canonical way to check for a GNU null is with isNullPointerConstant,
10016   // but we use a bit of a hack here for speed; this is a relatively
10017   // hot path, and isNullPointerConstant is slow.
10018   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10019   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10020 
10021   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10022 
10023   // Avoid analyzing cases where the result will either be invalid (and
10024   // diagnosed as such) or entirely valid and not something to warn about.
10025   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10026       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10027     return;
10028 
10029   // Comparison operations would not make sense with a null pointer no matter
10030   // what the other expression is.
10031   if (!IsCompare) {
10032     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10033         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10034         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10035     return;
10036   }
10037 
10038   // The rest of the operations only make sense with a null pointer
10039   // if the other expression is a pointer.
10040   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10041       NonNullType->canDecayToPointerType())
10042     return;
10043 
10044   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10045       << LHSNull /* LHS is NULL */ << NonNullType
10046       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10047 }
10048 
10049 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10050                                           SourceLocation Loc) {
10051   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10052   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10053   if (!LUE || !RUE)
10054     return;
10055   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10056       RUE->getKind() != UETT_SizeOf)
10057     return;
10058 
10059   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10060   QualType LHSTy = LHSArg->getType();
10061   QualType RHSTy;
10062 
10063   if (RUE->isArgumentType())
10064     RHSTy = RUE->getArgumentType().getNonReferenceType();
10065   else
10066     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10067 
10068   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10069     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10070       return;
10071 
10072     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10073     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10074       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10075         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10076             << LHSArgDecl;
10077     }
10078   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10079     QualType ArrayElemTy = ArrayTy->getElementType();
10080     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10081         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10082         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10083         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10084       return;
10085     S.Diag(Loc, diag::warn_division_sizeof_array)
10086         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10087     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10088       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10089         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10090             << LHSArgDecl;
10091     }
10092 
10093     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10094   }
10095 }
10096 
10097 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10098                                                ExprResult &RHS,
10099                                                SourceLocation Loc, bool IsDiv) {
10100   // Check for division/remainder by zero.
10101   Expr::EvalResult RHSValue;
10102   if (!RHS.get()->isValueDependent() &&
10103       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10104       RHSValue.Val.getInt() == 0)
10105     S.DiagRuntimeBehavior(Loc, RHS.get(),
10106                           S.PDiag(diag::warn_remainder_division_by_zero)
10107                             << IsDiv << RHS.get()->getSourceRange());
10108 }
10109 
10110 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10111                                            SourceLocation Loc,
10112                                            bool IsCompAssign, bool IsDiv) {
10113   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10114 
10115   if (LHS.get()->getType()->isVectorType() ||
10116       RHS.get()->getType()->isVectorType())
10117     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10118                                /*AllowBothBool*/getLangOpts().AltiVec,
10119                                /*AllowBoolConversions*/false);
10120   if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10121                  RHS.get()->getType()->isConstantMatrixType()))
10122     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10123 
10124   QualType compType = UsualArithmeticConversions(
10125       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10126   if (LHS.isInvalid() || RHS.isInvalid())
10127     return QualType();
10128 
10129 
10130   if (compType.isNull() || !compType->isArithmeticType())
10131     return InvalidOperands(Loc, LHS, RHS);
10132   if (IsDiv) {
10133     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10134     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10135   }
10136   return compType;
10137 }
10138 
10139 QualType Sema::CheckRemainderOperands(
10140   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10141   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10142 
10143   if (LHS.get()->getType()->isVectorType() ||
10144       RHS.get()->getType()->isVectorType()) {
10145     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10146         RHS.get()->getType()->hasIntegerRepresentation())
10147       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10148                                  /*AllowBothBool*/getLangOpts().AltiVec,
10149                                  /*AllowBoolConversions*/false);
10150     return InvalidOperands(Loc, LHS, RHS);
10151   }
10152 
10153   QualType compType = UsualArithmeticConversions(
10154       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10155   if (LHS.isInvalid() || RHS.isInvalid())
10156     return QualType();
10157 
10158   if (compType.isNull() || !compType->isIntegerType())
10159     return InvalidOperands(Loc, LHS, RHS);
10160   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10161   return compType;
10162 }
10163 
10164 /// Diagnose invalid arithmetic on two void pointers.
10165 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10166                                                 Expr *LHSExpr, Expr *RHSExpr) {
10167   S.Diag(Loc, S.getLangOpts().CPlusPlus
10168                 ? diag::err_typecheck_pointer_arith_void_type
10169                 : diag::ext_gnu_void_ptr)
10170     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10171                             << RHSExpr->getSourceRange();
10172 }
10173 
10174 /// Diagnose invalid arithmetic on a void pointer.
10175 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10176                                             Expr *Pointer) {
10177   S.Diag(Loc, S.getLangOpts().CPlusPlus
10178                 ? diag::err_typecheck_pointer_arith_void_type
10179                 : diag::ext_gnu_void_ptr)
10180     << 0 /* one pointer */ << Pointer->getSourceRange();
10181 }
10182 
10183 /// Diagnose invalid arithmetic on a null pointer.
10184 ///
10185 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10186 /// idiom, which we recognize as a GNU extension.
10187 ///
10188 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10189                                             Expr *Pointer, bool IsGNUIdiom) {
10190   if (IsGNUIdiom)
10191     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10192       << Pointer->getSourceRange();
10193   else
10194     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10195       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10196 }
10197 
10198 /// Diagnose invalid arithmetic on two function pointers.
10199 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10200                                                     Expr *LHS, Expr *RHS) {
10201   assert(LHS->getType()->isAnyPointerType());
10202   assert(RHS->getType()->isAnyPointerType());
10203   S.Diag(Loc, S.getLangOpts().CPlusPlus
10204                 ? diag::err_typecheck_pointer_arith_function_type
10205                 : diag::ext_gnu_ptr_func_arith)
10206     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10207     // We only show the second type if it differs from the first.
10208     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10209                                                    RHS->getType())
10210     << RHS->getType()->getPointeeType()
10211     << LHS->getSourceRange() << RHS->getSourceRange();
10212 }
10213 
10214 /// Diagnose invalid arithmetic on a function pointer.
10215 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10216                                                 Expr *Pointer) {
10217   assert(Pointer->getType()->isAnyPointerType());
10218   S.Diag(Loc, S.getLangOpts().CPlusPlus
10219                 ? diag::err_typecheck_pointer_arith_function_type
10220                 : diag::ext_gnu_ptr_func_arith)
10221     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10222     << 0 /* one pointer, so only one type */
10223     << Pointer->getSourceRange();
10224 }
10225 
10226 /// Emit error if Operand is incomplete pointer type
10227 ///
10228 /// \returns True if pointer has incomplete type
10229 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10230                                                  Expr *Operand) {
10231   QualType ResType = Operand->getType();
10232   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10233     ResType = ResAtomicType->getValueType();
10234 
10235   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10236   QualType PointeeTy = ResType->getPointeeType();
10237   return S.RequireCompleteSizedType(
10238       Loc, PointeeTy,
10239       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10240       Operand->getSourceRange());
10241 }
10242 
10243 /// Check the validity of an arithmetic pointer operand.
10244 ///
10245 /// If the operand has pointer type, this code will check for pointer types
10246 /// which are invalid in arithmetic operations. These will be diagnosed
10247 /// appropriately, including whether or not the use is supported as an
10248 /// extension.
10249 ///
10250 /// \returns True when the operand is valid to use (even if as an extension).
10251 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10252                                             Expr *Operand) {
10253   QualType ResType = Operand->getType();
10254   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10255     ResType = ResAtomicType->getValueType();
10256 
10257   if (!ResType->isAnyPointerType()) return true;
10258 
10259   QualType PointeeTy = ResType->getPointeeType();
10260   if (PointeeTy->isVoidType()) {
10261     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10262     return !S.getLangOpts().CPlusPlus;
10263   }
10264   if (PointeeTy->isFunctionType()) {
10265     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10266     return !S.getLangOpts().CPlusPlus;
10267   }
10268 
10269   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10270 
10271   return true;
10272 }
10273 
10274 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10275 /// operands.
10276 ///
10277 /// This routine will diagnose any invalid arithmetic on pointer operands much
10278 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10279 /// for emitting a single diagnostic even for operations where both LHS and RHS
10280 /// are (potentially problematic) pointers.
10281 ///
10282 /// \returns True when the operand is valid to use (even if as an extension).
10283 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10284                                                 Expr *LHSExpr, Expr *RHSExpr) {
10285   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10286   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10287   if (!isLHSPointer && !isRHSPointer) return true;
10288 
10289   QualType LHSPointeeTy, RHSPointeeTy;
10290   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10291   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10292 
10293   // if both are pointers check if operation is valid wrt address spaces
10294   if (isLHSPointer && isRHSPointer) {
10295     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10296       S.Diag(Loc,
10297              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10298           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10299           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10300       return false;
10301     }
10302   }
10303 
10304   // Check for arithmetic on pointers to incomplete types.
10305   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10306   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10307   if (isLHSVoidPtr || isRHSVoidPtr) {
10308     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10309     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10310     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10311 
10312     return !S.getLangOpts().CPlusPlus;
10313   }
10314 
10315   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10316   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10317   if (isLHSFuncPtr || isRHSFuncPtr) {
10318     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10319     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10320                                                                 RHSExpr);
10321     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10322 
10323     return !S.getLangOpts().CPlusPlus;
10324   }
10325 
10326   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10327     return false;
10328   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10329     return false;
10330 
10331   return true;
10332 }
10333 
10334 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10335 /// literal.
10336 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10337                                   Expr *LHSExpr, Expr *RHSExpr) {
10338   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10339   Expr* IndexExpr = RHSExpr;
10340   if (!StrExpr) {
10341     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10342     IndexExpr = LHSExpr;
10343   }
10344 
10345   bool IsStringPlusInt = StrExpr &&
10346       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10347   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10348     return;
10349 
10350   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10351   Self.Diag(OpLoc, diag::warn_string_plus_int)
10352       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10353 
10354   // Only print a fixit for "str" + int, not for int + "str".
10355   if (IndexExpr == RHSExpr) {
10356     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10357     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10358         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10359         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10360         << FixItHint::CreateInsertion(EndLoc, "]");
10361   } else
10362     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10363 }
10364 
10365 /// Emit a warning when adding a char literal to a string.
10366 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10367                                    Expr *LHSExpr, Expr *RHSExpr) {
10368   const Expr *StringRefExpr = LHSExpr;
10369   const CharacterLiteral *CharExpr =
10370       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10371 
10372   if (!CharExpr) {
10373     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10374     StringRefExpr = RHSExpr;
10375   }
10376 
10377   if (!CharExpr || !StringRefExpr)
10378     return;
10379 
10380   const QualType StringType = StringRefExpr->getType();
10381 
10382   // Return if not a PointerType.
10383   if (!StringType->isAnyPointerType())
10384     return;
10385 
10386   // Return if not a CharacterType.
10387   if (!StringType->getPointeeType()->isAnyCharacterType())
10388     return;
10389 
10390   ASTContext &Ctx = Self.getASTContext();
10391   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10392 
10393   const QualType CharType = CharExpr->getType();
10394   if (!CharType->isAnyCharacterType() &&
10395       CharType->isIntegerType() &&
10396       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10397     Self.Diag(OpLoc, diag::warn_string_plus_char)
10398         << DiagRange << Ctx.CharTy;
10399   } else {
10400     Self.Diag(OpLoc, diag::warn_string_plus_char)
10401         << DiagRange << CharExpr->getType();
10402   }
10403 
10404   // Only print a fixit for str + char, not for char + str.
10405   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10406     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10407     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10408         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10409         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10410         << FixItHint::CreateInsertion(EndLoc, "]");
10411   } else {
10412     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10413   }
10414 }
10415 
10416 /// Emit error when two pointers are incompatible.
10417 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10418                                            Expr *LHSExpr, Expr *RHSExpr) {
10419   assert(LHSExpr->getType()->isAnyPointerType());
10420   assert(RHSExpr->getType()->isAnyPointerType());
10421   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10422     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10423     << RHSExpr->getSourceRange();
10424 }
10425 
10426 // C99 6.5.6
10427 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10428                                      SourceLocation Loc, BinaryOperatorKind Opc,
10429                                      QualType* CompLHSTy) {
10430   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10431 
10432   if (LHS.get()->getType()->isVectorType() ||
10433       RHS.get()->getType()->isVectorType()) {
10434     QualType compType = CheckVectorOperands(
10435         LHS, RHS, Loc, CompLHSTy,
10436         /*AllowBothBool*/getLangOpts().AltiVec,
10437         /*AllowBoolConversions*/getLangOpts().ZVector);
10438     if (CompLHSTy) *CompLHSTy = compType;
10439     return compType;
10440   }
10441 
10442   if (LHS.get()->getType()->isConstantMatrixType() ||
10443       RHS.get()->getType()->isConstantMatrixType()) {
10444     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10445   }
10446 
10447   QualType compType = UsualArithmeticConversions(
10448       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10449   if (LHS.isInvalid() || RHS.isInvalid())
10450     return QualType();
10451 
10452   // Diagnose "string literal" '+' int and string '+' "char literal".
10453   if (Opc == BO_Add) {
10454     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10455     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10456   }
10457 
10458   // handle the common case first (both operands are arithmetic).
10459   if (!compType.isNull() && compType->isArithmeticType()) {
10460     if (CompLHSTy) *CompLHSTy = compType;
10461     return compType;
10462   }
10463 
10464   // Type-checking.  Ultimately the pointer's going to be in PExp;
10465   // note that we bias towards the LHS being the pointer.
10466   Expr *PExp = LHS.get(), *IExp = RHS.get();
10467 
10468   bool isObjCPointer;
10469   if (PExp->getType()->isPointerType()) {
10470     isObjCPointer = false;
10471   } else if (PExp->getType()->isObjCObjectPointerType()) {
10472     isObjCPointer = true;
10473   } else {
10474     std::swap(PExp, IExp);
10475     if (PExp->getType()->isPointerType()) {
10476       isObjCPointer = false;
10477     } else if (PExp->getType()->isObjCObjectPointerType()) {
10478       isObjCPointer = true;
10479     } else {
10480       return InvalidOperands(Loc, LHS, RHS);
10481     }
10482   }
10483   assert(PExp->getType()->isAnyPointerType());
10484 
10485   if (!IExp->getType()->isIntegerType())
10486     return InvalidOperands(Loc, LHS, RHS);
10487 
10488   // Adding to a null pointer results in undefined behavior.
10489   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10490           Context, Expr::NPC_ValueDependentIsNotNull)) {
10491     // In C++ adding zero to a null pointer is defined.
10492     Expr::EvalResult KnownVal;
10493     if (!getLangOpts().CPlusPlus ||
10494         (!IExp->isValueDependent() &&
10495          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10496           KnownVal.Val.getInt() != 0))) {
10497       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10498       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10499           Context, BO_Add, PExp, IExp);
10500       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10501     }
10502   }
10503 
10504   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10505     return QualType();
10506 
10507   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10508     return QualType();
10509 
10510   // Check array bounds for pointer arithemtic
10511   CheckArrayAccess(PExp, IExp);
10512 
10513   if (CompLHSTy) {
10514     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10515     if (LHSTy.isNull()) {
10516       LHSTy = LHS.get()->getType();
10517       if (LHSTy->isPromotableIntegerType())
10518         LHSTy = Context.getPromotedIntegerType(LHSTy);
10519     }
10520     *CompLHSTy = LHSTy;
10521   }
10522 
10523   return PExp->getType();
10524 }
10525 
10526 // C99 6.5.6
10527 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10528                                         SourceLocation Loc,
10529                                         QualType* CompLHSTy) {
10530   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10531 
10532   if (LHS.get()->getType()->isVectorType() ||
10533       RHS.get()->getType()->isVectorType()) {
10534     QualType compType = CheckVectorOperands(
10535         LHS, RHS, Loc, CompLHSTy,
10536         /*AllowBothBool*/getLangOpts().AltiVec,
10537         /*AllowBoolConversions*/getLangOpts().ZVector);
10538     if (CompLHSTy) *CompLHSTy = compType;
10539     return compType;
10540   }
10541 
10542   if (LHS.get()->getType()->isConstantMatrixType() ||
10543       RHS.get()->getType()->isConstantMatrixType()) {
10544     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10545   }
10546 
10547   QualType compType = UsualArithmeticConversions(
10548       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10549   if (LHS.isInvalid() || RHS.isInvalid())
10550     return QualType();
10551 
10552   // Enforce type constraints: C99 6.5.6p3.
10553 
10554   // Handle the common case first (both operands are arithmetic).
10555   if (!compType.isNull() && compType->isArithmeticType()) {
10556     if (CompLHSTy) *CompLHSTy = compType;
10557     return compType;
10558   }
10559 
10560   // Either ptr - int   or   ptr - ptr.
10561   if (LHS.get()->getType()->isAnyPointerType()) {
10562     QualType lpointee = LHS.get()->getType()->getPointeeType();
10563 
10564     // Diagnose bad cases where we step over interface counts.
10565     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10566         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10567       return QualType();
10568 
10569     // The result type of a pointer-int computation is the pointer type.
10570     if (RHS.get()->getType()->isIntegerType()) {
10571       // Subtracting from a null pointer should produce a warning.
10572       // The last argument to the diagnose call says this doesn't match the
10573       // GNU int-to-pointer idiom.
10574       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10575                                            Expr::NPC_ValueDependentIsNotNull)) {
10576         // In C++ adding zero to a null pointer is defined.
10577         Expr::EvalResult KnownVal;
10578         if (!getLangOpts().CPlusPlus ||
10579             (!RHS.get()->isValueDependent() &&
10580              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10581               KnownVal.Val.getInt() != 0))) {
10582           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10583         }
10584       }
10585 
10586       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10587         return QualType();
10588 
10589       // Check array bounds for pointer arithemtic
10590       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10591                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10592 
10593       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10594       return LHS.get()->getType();
10595     }
10596 
10597     // Handle pointer-pointer subtractions.
10598     if (const PointerType *RHSPTy
10599           = RHS.get()->getType()->getAs<PointerType>()) {
10600       QualType rpointee = RHSPTy->getPointeeType();
10601 
10602       if (getLangOpts().CPlusPlus) {
10603         // Pointee types must be the same: C++ [expr.add]
10604         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10605           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10606         }
10607       } else {
10608         // Pointee types must be compatible C99 6.5.6p3
10609         if (!Context.typesAreCompatible(
10610                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10611                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10612           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10613           return QualType();
10614         }
10615       }
10616 
10617       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10618                                                LHS.get(), RHS.get()))
10619         return QualType();
10620 
10621       // FIXME: Add warnings for nullptr - ptr.
10622 
10623       // The pointee type may have zero size.  As an extension, a structure or
10624       // union may have zero size or an array may have zero length.  In this
10625       // case subtraction does not make sense.
10626       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10627         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10628         if (ElementSize.isZero()) {
10629           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10630             << rpointee.getUnqualifiedType()
10631             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10632         }
10633       }
10634 
10635       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10636       return Context.getPointerDiffType();
10637     }
10638   }
10639 
10640   return InvalidOperands(Loc, LHS, RHS);
10641 }
10642 
10643 static bool isScopedEnumerationType(QualType T) {
10644   if (const EnumType *ET = T->getAs<EnumType>())
10645     return ET->getDecl()->isScoped();
10646   return false;
10647 }
10648 
10649 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10650                                    SourceLocation Loc, BinaryOperatorKind Opc,
10651                                    QualType LHSType) {
10652   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10653   // so skip remaining warnings as we don't want to modify values within Sema.
10654   if (S.getLangOpts().OpenCL)
10655     return;
10656 
10657   // Check right/shifter operand
10658   Expr::EvalResult RHSResult;
10659   if (RHS.get()->isValueDependent() ||
10660       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10661     return;
10662   llvm::APSInt Right = RHSResult.Val.getInt();
10663 
10664   if (Right.isNegative()) {
10665     S.DiagRuntimeBehavior(Loc, RHS.get(),
10666                           S.PDiag(diag::warn_shift_negative)
10667                             << RHS.get()->getSourceRange());
10668     return;
10669   }
10670 
10671   QualType LHSExprType = LHS.get()->getType();
10672   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
10673   if (LHSExprType->isExtIntType())
10674     LeftSize = S.Context.getIntWidth(LHSExprType);
10675   else if (LHSExprType->isFixedPointType()) {
10676     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
10677     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
10678   }
10679   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10680   if (Right.uge(LeftBits)) {
10681     S.DiagRuntimeBehavior(Loc, RHS.get(),
10682                           S.PDiag(diag::warn_shift_gt_typewidth)
10683                             << RHS.get()->getSourceRange());
10684     return;
10685   }
10686 
10687   // FIXME: We probably need to handle fixed point types specially here.
10688   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
10689     return;
10690 
10691   // When left shifting an ICE which is signed, we can check for overflow which
10692   // according to C++ standards prior to C++2a has undefined behavior
10693   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10694   // more than the maximum value representable in the result type, so never
10695   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10696   // expression is still probably a bug.)
10697   Expr::EvalResult LHSResult;
10698   if (LHS.get()->isValueDependent() ||
10699       LHSType->hasUnsignedIntegerRepresentation() ||
10700       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10701     return;
10702   llvm::APSInt Left = LHSResult.Val.getInt();
10703 
10704   // If LHS does not have a signed type and non-negative value
10705   // then, the behavior is undefined before C++2a. Warn about it.
10706   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10707       !S.getLangOpts().CPlusPlus20) {
10708     S.DiagRuntimeBehavior(Loc, LHS.get(),
10709                           S.PDiag(diag::warn_shift_lhs_negative)
10710                             << LHS.get()->getSourceRange());
10711     return;
10712   }
10713 
10714   llvm::APInt ResultBits =
10715       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10716   if (LeftBits.uge(ResultBits))
10717     return;
10718   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10719   Result = Result.shl(Right);
10720 
10721   // Print the bit representation of the signed integer as an unsigned
10722   // hexadecimal number.
10723   SmallString<40> HexResult;
10724   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10725 
10726   // If we are only missing a sign bit, this is less likely to result in actual
10727   // bugs -- if the result is cast back to an unsigned type, it will have the
10728   // expected value. Thus we place this behind a different warning that can be
10729   // turned off separately if needed.
10730   if (LeftBits == ResultBits - 1) {
10731     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10732         << HexResult << LHSType
10733         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10734     return;
10735   }
10736 
10737   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10738     << HexResult.str() << Result.getMinSignedBits() << LHSType
10739     << Left.getBitWidth() << LHS.get()->getSourceRange()
10740     << RHS.get()->getSourceRange();
10741 }
10742 
10743 /// Return the resulting type when a vector is shifted
10744 ///        by a scalar or vector shift amount.
10745 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10746                                  SourceLocation Loc, bool IsCompAssign) {
10747   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10748   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10749       !LHS.get()->getType()->isVectorType()) {
10750     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10751       << RHS.get()->getType() << LHS.get()->getType()
10752       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10753     return QualType();
10754   }
10755 
10756   if (!IsCompAssign) {
10757     LHS = S.UsualUnaryConversions(LHS.get());
10758     if (LHS.isInvalid()) return QualType();
10759   }
10760 
10761   RHS = S.UsualUnaryConversions(RHS.get());
10762   if (RHS.isInvalid()) return QualType();
10763 
10764   QualType LHSType = LHS.get()->getType();
10765   // Note that LHS might be a scalar because the routine calls not only in
10766   // OpenCL case.
10767   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10768   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10769 
10770   // Note that RHS might not be a vector.
10771   QualType RHSType = RHS.get()->getType();
10772   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10773   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10774 
10775   // The operands need to be integers.
10776   if (!LHSEleType->isIntegerType()) {
10777     S.Diag(Loc, diag::err_typecheck_expect_int)
10778       << LHS.get()->getType() << LHS.get()->getSourceRange();
10779     return QualType();
10780   }
10781 
10782   if (!RHSEleType->isIntegerType()) {
10783     S.Diag(Loc, diag::err_typecheck_expect_int)
10784       << RHS.get()->getType() << RHS.get()->getSourceRange();
10785     return QualType();
10786   }
10787 
10788   if (!LHSVecTy) {
10789     assert(RHSVecTy);
10790     if (IsCompAssign)
10791       return RHSType;
10792     if (LHSEleType != RHSEleType) {
10793       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10794       LHSEleType = RHSEleType;
10795     }
10796     QualType VecTy =
10797         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10798     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10799     LHSType = VecTy;
10800   } else if (RHSVecTy) {
10801     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10802     // are applied component-wise. So if RHS is a vector, then ensure
10803     // that the number of elements is the same as LHS...
10804     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10805       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10806         << LHS.get()->getType() << RHS.get()->getType()
10807         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10808       return QualType();
10809     }
10810     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10811       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10812       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10813       if (LHSBT != RHSBT &&
10814           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10815         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10816             << LHS.get()->getType() << RHS.get()->getType()
10817             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10818       }
10819     }
10820   } else {
10821     // ...else expand RHS to match the number of elements in LHS.
10822     QualType VecTy =
10823       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10824     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10825   }
10826 
10827   return LHSType;
10828 }
10829 
10830 // C99 6.5.7
10831 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10832                                   SourceLocation Loc, BinaryOperatorKind Opc,
10833                                   bool IsCompAssign) {
10834   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10835 
10836   // Vector shifts promote their scalar inputs to vector type.
10837   if (LHS.get()->getType()->isVectorType() ||
10838       RHS.get()->getType()->isVectorType()) {
10839     if (LangOpts.ZVector) {
10840       // The shift operators for the z vector extensions work basically
10841       // like general shifts, except that neither the LHS nor the RHS is
10842       // allowed to be a "vector bool".
10843       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10844         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10845           return InvalidOperands(Loc, LHS, RHS);
10846       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10847         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10848           return InvalidOperands(Loc, LHS, RHS);
10849     }
10850     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10851   }
10852 
10853   // Shifts don't perform usual arithmetic conversions, they just do integer
10854   // promotions on each operand. C99 6.5.7p3
10855 
10856   // For the LHS, do usual unary conversions, but then reset them away
10857   // if this is a compound assignment.
10858   ExprResult OldLHS = LHS;
10859   LHS = UsualUnaryConversions(LHS.get());
10860   if (LHS.isInvalid())
10861     return QualType();
10862   QualType LHSType = LHS.get()->getType();
10863   if (IsCompAssign) LHS = OldLHS;
10864 
10865   // The RHS is simpler.
10866   RHS = UsualUnaryConversions(RHS.get());
10867   if (RHS.isInvalid())
10868     return QualType();
10869   QualType RHSType = RHS.get()->getType();
10870 
10871   // C99 6.5.7p2: Each of the operands shall have integer type.
10872   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
10873   if ((!LHSType->isFixedPointOrIntegerType() &&
10874        !LHSType->hasIntegerRepresentation()) ||
10875       !RHSType->hasIntegerRepresentation())
10876     return InvalidOperands(Loc, LHS, RHS);
10877 
10878   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10879   // hasIntegerRepresentation() above instead of this.
10880   if (isScopedEnumerationType(LHSType) ||
10881       isScopedEnumerationType(RHSType)) {
10882     return InvalidOperands(Loc, LHS, RHS);
10883   }
10884   // Sanity-check shift operands
10885   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10886 
10887   // "The type of the result is that of the promoted left operand."
10888   return LHSType;
10889 }
10890 
10891 /// Diagnose bad pointer comparisons.
10892 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10893                                               ExprResult &LHS, ExprResult &RHS,
10894                                               bool IsError) {
10895   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10896                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10897     << LHS.get()->getType() << RHS.get()->getType()
10898     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10899 }
10900 
10901 /// Returns false if the pointers are converted to a composite type,
10902 /// true otherwise.
10903 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10904                                            ExprResult &LHS, ExprResult &RHS) {
10905   // C++ [expr.rel]p2:
10906   //   [...] Pointer conversions (4.10) and qualification
10907   //   conversions (4.4) are performed on pointer operands (or on
10908   //   a pointer operand and a null pointer constant) to bring
10909   //   them to their composite pointer type. [...]
10910   //
10911   // C++ [expr.eq]p1 uses the same notion for (in)equality
10912   // comparisons of pointers.
10913 
10914   QualType LHSType = LHS.get()->getType();
10915   QualType RHSType = RHS.get()->getType();
10916   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10917          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10918 
10919   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10920   if (T.isNull()) {
10921     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10922         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10923       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10924     else
10925       S.InvalidOperands(Loc, LHS, RHS);
10926     return true;
10927   }
10928 
10929   return false;
10930 }
10931 
10932 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10933                                                     ExprResult &LHS,
10934                                                     ExprResult &RHS,
10935                                                     bool IsError) {
10936   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10937                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10938     << LHS.get()->getType() << RHS.get()->getType()
10939     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10940 }
10941 
10942 static bool isObjCObjectLiteral(ExprResult &E) {
10943   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10944   case Stmt::ObjCArrayLiteralClass:
10945   case Stmt::ObjCDictionaryLiteralClass:
10946   case Stmt::ObjCStringLiteralClass:
10947   case Stmt::ObjCBoxedExprClass:
10948     return true;
10949   default:
10950     // Note that ObjCBoolLiteral is NOT an object literal!
10951     return false;
10952   }
10953 }
10954 
10955 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10956   const ObjCObjectPointerType *Type =
10957     LHS->getType()->getAs<ObjCObjectPointerType>();
10958 
10959   // If this is not actually an Objective-C object, bail out.
10960   if (!Type)
10961     return false;
10962 
10963   // Get the LHS object's interface type.
10964   QualType InterfaceType = Type->getPointeeType();
10965 
10966   // If the RHS isn't an Objective-C object, bail out.
10967   if (!RHS->getType()->isObjCObjectPointerType())
10968     return false;
10969 
10970   // Try to find the -isEqual: method.
10971   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10972   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10973                                                       InterfaceType,
10974                                                       /*IsInstance=*/true);
10975   if (!Method) {
10976     if (Type->isObjCIdType()) {
10977       // For 'id', just check the global pool.
10978       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10979                                                   /*receiverId=*/true);
10980     } else {
10981       // Check protocols.
10982       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10983                                              /*IsInstance=*/true);
10984     }
10985   }
10986 
10987   if (!Method)
10988     return false;
10989 
10990   QualType T = Method->parameters()[0]->getType();
10991   if (!T->isObjCObjectPointerType())
10992     return false;
10993 
10994   QualType R = Method->getReturnType();
10995   if (!R->isScalarType())
10996     return false;
10997 
10998   return true;
10999 }
11000 
11001 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11002   FromE = FromE->IgnoreParenImpCasts();
11003   switch (FromE->getStmtClass()) {
11004     default:
11005       break;
11006     case Stmt::ObjCStringLiteralClass:
11007       // "string literal"
11008       return LK_String;
11009     case Stmt::ObjCArrayLiteralClass:
11010       // "array literal"
11011       return LK_Array;
11012     case Stmt::ObjCDictionaryLiteralClass:
11013       // "dictionary literal"
11014       return LK_Dictionary;
11015     case Stmt::BlockExprClass:
11016       return LK_Block;
11017     case Stmt::ObjCBoxedExprClass: {
11018       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11019       switch (Inner->getStmtClass()) {
11020         case Stmt::IntegerLiteralClass:
11021         case Stmt::FloatingLiteralClass:
11022         case Stmt::CharacterLiteralClass:
11023         case Stmt::ObjCBoolLiteralExprClass:
11024         case Stmt::CXXBoolLiteralExprClass:
11025           // "numeric literal"
11026           return LK_Numeric;
11027         case Stmt::ImplicitCastExprClass: {
11028           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11029           // Boolean literals can be represented by implicit casts.
11030           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11031             return LK_Numeric;
11032           break;
11033         }
11034         default:
11035           break;
11036       }
11037       return LK_Boxed;
11038     }
11039   }
11040   return LK_None;
11041 }
11042 
11043 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11044                                           ExprResult &LHS, ExprResult &RHS,
11045                                           BinaryOperator::Opcode Opc){
11046   Expr *Literal;
11047   Expr *Other;
11048   if (isObjCObjectLiteral(LHS)) {
11049     Literal = LHS.get();
11050     Other = RHS.get();
11051   } else {
11052     Literal = RHS.get();
11053     Other = LHS.get();
11054   }
11055 
11056   // Don't warn on comparisons against nil.
11057   Other = Other->IgnoreParenCasts();
11058   if (Other->isNullPointerConstant(S.getASTContext(),
11059                                    Expr::NPC_ValueDependentIsNotNull))
11060     return;
11061 
11062   // This should be kept in sync with warn_objc_literal_comparison.
11063   // LK_String should always be after the other literals, since it has its own
11064   // warning flag.
11065   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11066   assert(LiteralKind != Sema::LK_Block);
11067   if (LiteralKind == Sema::LK_None) {
11068     llvm_unreachable("Unknown Objective-C object literal kind");
11069   }
11070 
11071   if (LiteralKind == Sema::LK_String)
11072     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11073       << Literal->getSourceRange();
11074   else
11075     S.Diag(Loc, diag::warn_objc_literal_comparison)
11076       << LiteralKind << Literal->getSourceRange();
11077 
11078   if (BinaryOperator::isEqualityOp(Opc) &&
11079       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11080     SourceLocation Start = LHS.get()->getBeginLoc();
11081     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11082     CharSourceRange OpRange =
11083       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11084 
11085     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11086       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11087       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11088       << FixItHint::CreateInsertion(End, "]");
11089   }
11090 }
11091 
11092 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11093 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11094                                            ExprResult &RHS, SourceLocation Loc,
11095                                            BinaryOperatorKind Opc) {
11096   // Check that left hand side is !something.
11097   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11098   if (!UO || UO->getOpcode() != UO_LNot) return;
11099 
11100   // Only check if the right hand side is non-bool arithmetic type.
11101   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11102 
11103   // Make sure that the something in !something is not bool.
11104   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11105   if (SubExpr->isKnownToHaveBooleanValue()) return;
11106 
11107   // Emit warning.
11108   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11109   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11110       << Loc << IsBitwiseOp;
11111 
11112   // First note suggest !(x < y)
11113   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11114   SourceLocation FirstClose = RHS.get()->getEndLoc();
11115   FirstClose = S.getLocForEndOfToken(FirstClose);
11116   if (FirstClose.isInvalid())
11117     FirstOpen = SourceLocation();
11118   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11119       << IsBitwiseOp
11120       << FixItHint::CreateInsertion(FirstOpen, "(")
11121       << FixItHint::CreateInsertion(FirstClose, ")");
11122 
11123   // Second note suggests (!x) < y
11124   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11125   SourceLocation SecondClose = LHS.get()->getEndLoc();
11126   SecondClose = S.getLocForEndOfToken(SecondClose);
11127   if (SecondClose.isInvalid())
11128     SecondOpen = SourceLocation();
11129   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11130       << FixItHint::CreateInsertion(SecondOpen, "(")
11131       << FixItHint::CreateInsertion(SecondClose, ")");
11132 }
11133 
11134 // Returns true if E refers to a non-weak array.
11135 static bool checkForArray(const Expr *E) {
11136   const ValueDecl *D = nullptr;
11137   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11138     D = DR->getDecl();
11139   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11140     if (Mem->isImplicitAccess())
11141       D = Mem->getMemberDecl();
11142   }
11143   if (!D)
11144     return false;
11145   return D->getType()->isArrayType() && !D->isWeak();
11146 }
11147 
11148 /// Diagnose some forms of syntactically-obvious tautological comparison.
11149 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11150                                            Expr *LHS, Expr *RHS,
11151                                            BinaryOperatorKind Opc) {
11152   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11153   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11154 
11155   QualType LHSType = LHS->getType();
11156   QualType RHSType = RHS->getType();
11157   if (LHSType->hasFloatingRepresentation() ||
11158       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11159       S.inTemplateInstantiation())
11160     return;
11161 
11162   // Comparisons between two array types are ill-formed for operator<=>, so
11163   // we shouldn't emit any additional warnings about it.
11164   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11165     return;
11166 
11167   // For non-floating point types, check for self-comparisons of the form
11168   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11169   // often indicate logic errors in the program.
11170   //
11171   // NOTE: Don't warn about comparison expressions resulting from macro
11172   // expansion. Also don't warn about comparisons which are only self
11173   // comparisons within a template instantiation. The warnings should catch
11174   // obvious cases in the definition of the template anyways. The idea is to
11175   // warn when the typed comparison operator will always evaluate to the same
11176   // result.
11177 
11178   // Used for indexing into %select in warn_comparison_always
11179   enum {
11180     AlwaysConstant,
11181     AlwaysTrue,
11182     AlwaysFalse,
11183     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11184   };
11185 
11186   // C++2a [depr.array.comp]:
11187   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11188   //   operands of array type are deprecated.
11189   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11190       RHSStripped->getType()->isArrayType()) {
11191     S.Diag(Loc, diag::warn_depr_array_comparison)
11192         << LHS->getSourceRange() << RHS->getSourceRange()
11193         << LHSStripped->getType() << RHSStripped->getType();
11194     // Carry on to produce the tautological comparison warning, if this
11195     // expression is potentially-evaluated, we can resolve the array to a
11196     // non-weak declaration, and so on.
11197   }
11198 
11199   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11200     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11201       unsigned Result;
11202       switch (Opc) {
11203       case BO_EQ:
11204       case BO_LE:
11205       case BO_GE:
11206         Result = AlwaysTrue;
11207         break;
11208       case BO_NE:
11209       case BO_LT:
11210       case BO_GT:
11211         Result = AlwaysFalse;
11212         break;
11213       case BO_Cmp:
11214         Result = AlwaysEqual;
11215         break;
11216       default:
11217         Result = AlwaysConstant;
11218         break;
11219       }
11220       S.DiagRuntimeBehavior(Loc, nullptr,
11221                             S.PDiag(diag::warn_comparison_always)
11222                                 << 0 /*self-comparison*/
11223                                 << Result);
11224     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11225       // What is it always going to evaluate to?
11226       unsigned Result;
11227       switch (Opc) {
11228       case BO_EQ: // e.g. array1 == array2
11229         Result = AlwaysFalse;
11230         break;
11231       case BO_NE: // e.g. array1 != array2
11232         Result = AlwaysTrue;
11233         break;
11234       default: // e.g. array1 <= array2
11235         // The best we can say is 'a constant'
11236         Result = AlwaysConstant;
11237         break;
11238       }
11239       S.DiagRuntimeBehavior(Loc, nullptr,
11240                             S.PDiag(diag::warn_comparison_always)
11241                                 << 1 /*array comparison*/
11242                                 << Result);
11243     }
11244   }
11245 
11246   if (isa<CastExpr>(LHSStripped))
11247     LHSStripped = LHSStripped->IgnoreParenCasts();
11248   if (isa<CastExpr>(RHSStripped))
11249     RHSStripped = RHSStripped->IgnoreParenCasts();
11250 
11251   // Warn about comparisons against a string constant (unless the other
11252   // operand is null); the user probably wants string comparison function.
11253   Expr *LiteralString = nullptr;
11254   Expr *LiteralStringStripped = nullptr;
11255   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11256       !RHSStripped->isNullPointerConstant(S.Context,
11257                                           Expr::NPC_ValueDependentIsNull)) {
11258     LiteralString = LHS;
11259     LiteralStringStripped = LHSStripped;
11260   } else if ((isa<StringLiteral>(RHSStripped) ||
11261               isa<ObjCEncodeExpr>(RHSStripped)) &&
11262              !LHSStripped->isNullPointerConstant(S.Context,
11263                                           Expr::NPC_ValueDependentIsNull)) {
11264     LiteralString = RHS;
11265     LiteralStringStripped = RHSStripped;
11266   }
11267 
11268   if (LiteralString) {
11269     S.DiagRuntimeBehavior(Loc, nullptr,
11270                           S.PDiag(diag::warn_stringcompare)
11271                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11272                               << LiteralString->getSourceRange());
11273   }
11274 }
11275 
11276 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11277   switch (CK) {
11278   default: {
11279 #ifndef NDEBUG
11280     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11281                  << "\n";
11282 #endif
11283     llvm_unreachable("unhandled cast kind");
11284   }
11285   case CK_UserDefinedConversion:
11286     return ICK_Identity;
11287   case CK_LValueToRValue:
11288     return ICK_Lvalue_To_Rvalue;
11289   case CK_ArrayToPointerDecay:
11290     return ICK_Array_To_Pointer;
11291   case CK_FunctionToPointerDecay:
11292     return ICK_Function_To_Pointer;
11293   case CK_IntegralCast:
11294     return ICK_Integral_Conversion;
11295   case CK_FloatingCast:
11296     return ICK_Floating_Conversion;
11297   case CK_IntegralToFloating:
11298   case CK_FloatingToIntegral:
11299     return ICK_Floating_Integral;
11300   case CK_IntegralComplexCast:
11301   case CK_FloatingComplexCast:
11302   case CK_FloatingComplexToIntegralComplex:
11303   case CK_IntegralComplexToFloatingComplex:
11304     return ICK_Complex_Conversion;
11305   case CK_FloatingComplexToReal:
11306   case CK_FloatingRealToComplex:
11307   case CK_IntegralComplexToReal:
11308   case CK_IntegralRealToComplex:
11309     return ICK_Complex_Real;
11310   }
11311 }
11312 
11313 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11314                                              QualType FromType,
11315                                              SourceLocation Loc) {
11316   // Check for a narrowing implicit conversion.
11317   StandardConversionSequence SCS;
11318   SCS.setAsIdentityConversion();
11319   SCS.setToType(0, FromType);
11320   SCS.setToType(1, ToType);
11321   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11322     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11323 
11324   APValue PreNarrowingValue;
11325   QualType PreNarrowingType;
11326   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11327                                PreNarrowingType,
11328                                /*IgnoreFloatToIntegralConversion*/ true)) {
11329   case NK_Dependent_Narrowing:
11330     // Implicit conversion to a narrower type, but the expression is
11331     // value-dependent so we can't tell whether it's actually narrowing.
11332   case NK_Not_Narrowing:
11333     return false;
11334 
11335   case NK_Constant_Narrowing:
11336     // Implicit conversion to a narrower type, and the value is not a constant
11337     // expression.
11338     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11339         << /*Constant*/ 1
11340         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11341     return true;
11342 
11343   case NK_Variable_Narrowing:
11344     // Implicit conversion to a narrower type, and the value is not a constant
11345     // expression.
11346   case NK_Type_Narrowing:
11347     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11348         << /*Constant*/ 0 << FromType << ToType;
11349     // TODO: It's not a constant expression, but what if the user intended it
11350     // to be? Can we produce notes to help them figure out why it isn't?
11351     return true;
11352   }
11353   llvm_unreachable("unhandled case in switch");
11354 }
11355 
11356 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11357                                                          ExprResult &LHS,
11358                                                          ExprResult &RHS,
11359                                                          SourceLocation Loc) {
11360   QualType LHSType = LHS.get()->getType();
11361   QualType RHSType = RHS.get()->getType();
11362   // Dig out the original argument type and expression before implicit casts
11363   // were applied. These are the types/expressions we need to check the
11364   // [expr.spaceship] requirements against.
11365   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11366   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11367   QualType LHSStrippedType = LHSStripped.get()->getType();
11368   QualType RHSStrippedType = RHSStripped.get()->getType();
11369 
11370   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11371   // other is not, the program is ill-formed.
11372   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11373     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11374     return QualType();
11375   }
11376 
11377   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11378   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11379                     RHSStrippedType->isEnumeralType();
11380   if (NumEnumArgs == 1) {
11381     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11382     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11383     if (OtherTy->hasFloatingRepresentation()) {
11384       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11385       return QualType();
11386     }
11387   }
11388   if (NumEnumArgs == 2) {
11389     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11390     // type E, the operator yields the result of converting the operands
11391     // to the underlying type of E and applying <=> to the converted operands.
11392     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11393       S.InvalidOperands(Loc, LHS, RHS);
11394       return QualType();
11395     }
11396     QualType IntType =
11397         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11398     assert(IntType->isArithmeticType());
11399 
11400     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11401     // promote the boolean type, and all other promotable integer types, to
11402     // avoid this.
11403     if (IntType->isPromotableIntegerType())
11404       IntType = S.Context.getPromotedIntegerType(IntType);
11405 
11406     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11407     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11408     LHSType = RHSType = IntType;
11409   }
11410 
11411   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11412   // usual arithmetic conversions are applied to the operands.
11413   QualType Type =
11414       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11415   if (LHS.isInvalid() || RHS.isInvalid())
11416     return QualType();
11417   if (Type.isNull())
11418     return S.InvalidOperands(Loc, LHS, RHS);
11419 
11420   Optional<ComparisonCategoryType> CCT =
11421       getComparisonCategoryForBuiltinCmp(Type);
11422   if (!CCT)
11423     return S.InvalidOperands(Loc, LHS, RHS);
11424 
11425   bool HasNarrowing = checkThreeWayNarrowingConversion(
11426       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11427   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11428                                                    RHS.get()->getBeginLoc());
11429   if (HasNarrowing)
11430     return QualType();
11431 
11432   assert(!Type.isNull() && "composite type for <=> has not been set");
11433 
11434   return S.CheckComparisonCategoryType(
11435       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11436 }
11437 
11438 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11439                                                  ExprResult &RHS,
11440                                                  SourceLocation Loc,
11441                                                  BinaryOperatorKind Opc) {
11442   if (Opc == BO_Cmp)
11443     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11444 
11445   // C99 6.5.8p3 / C99 6.5.9p4
11446   QualType Type =
11447       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11448   if (LHS.isInvalid() || RHS.isInvalid())
11449     return QualType();
11450   if (Type.isNull())
11451     return S.InvalidOperands(Loc, LHS, RHS);
11452   assert(Type->isArithmeticType() || Type->isEnumeralType());
11453 
11454   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11455     return S.InvalidOperands(Loc, LHS, RHS);
11456 
11457   // Check for comparisons of floating point operands using != and ==.
11458   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11459     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11460 
11461   // The result of comparisons is 'bool' in C++, 'int' in C.
11462   return S.Context.getLogicalOperationType();
11463 }
11464 
11465 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11466   if (!NullE.get()->getType()->isAnyPointerType())
11467     return;
11468   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11469   if (!E.get()->getType()->isAnyPointerType() &&
11470       E.get()->isNullPointerConstant(Context,
11471                                      Expr::NPC_ValueDependentIsNotNull) ==
11472         Expr::NPCK_ZeroExpression) {
11473     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11474       if (CL->getValue() == 0)
11475         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11476             << NullValue
11477             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11478                                             NullValue ? "NULL" : "(void *)0");
11479     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11480         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11481         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11482         if (T == Context.CharTy)
11483           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11484               << NullValue
11485               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11486                                               NullValue ? "NULL" : "(void *)0");
11487       }
11488   }
11489 }
11490 
11491 // C99 6.5.8, C++ [expr.rel]
11492 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11493                                     SourceLocation Loc,
11494                                     BinaryOperatorKind Opc) {
11495   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11496   bool IsThreeWay = Opc == BO_Cmp;
11497   bool IsOrdered = IsRelational || IsThreeWay;
11498   auto IsAnyPointerType = [](ExprResult E) {
11499     QualType Ty = E.get()->getType();
11500     return Ty->isPointerType() || Ty->isMemberPointerType();
11501   };
11502 
11503   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11504   // type, array-to-pointer, ..., conversions are performed on both operands to
11505   // bring them to their composite type.
11506   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11507   // any type-related checks.
11508   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11509     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11510     if (LHS.isInvalid())
11511       return QualType();
11512     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11513     if (RHS.isInvalid())
11514       return QualType();
11515   } else {
11516     LHS = DefaultLvalueConversion(LHS.get());
11517     if (LHS.isInvalid())
11518       return QualType();
11519     RHS = DefaultLvalueConversion(RHS.get());
11520     if (RHS.isInvalid())
11521       return QualType();
11522   }
11523 
11524   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11525   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11526     CheckPtrComparisonWithNullChar(LHS, RHS);
11527     CheckPtrComparisonWithNullChar(RHS, LHS);
11528   }
11529 
11530   // Handle vector comparisons separately.
11531   if (LHS.get()->getType()->isVectorType() ||
11532       RHS.get()->getType()->isVectorType())
11533     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11534 
11535   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11536   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11537 
11538   QualType LHSType = LHS.get()->getType();
11539   QualType RHSType = RHS.get()->getType();
11540   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11541       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11542     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11543 
11544   const Expr::NullPointerConstantKind LHSNullKind =
11545       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11546   const Expr::NullPointerConstantKind RHSNullKind =
11547       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11548   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11549   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11550 
11551   auto computeResultTy = [&]() {
11552     if (Opc != BO_Cmp)
11553       return Context.getLogicalOperationType();
11554     assert(getLangOpts().CPlusPlus);
11555     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11556 
11557     QualType CompositeTy = LHS.get()->getType();
11558     assert(!CompositeTy->isReferenceType());
11559 
11560     Optional<ComparisonCategoryType> CCT =
11561         getComparisonCategoryForBuiltinCmp(CompositeTy);
11562     if (!CCT)
11563       return InvalidOperands(Loc, LHS, RHS);
11564 
11565     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11566       // P0946R0: Comparisons between a null pointer constant and an object
11567       // pointer result in std::strong_equality, which is ill-formed under
11568       // P1959R0.
11569       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11570           << (LHSIsNull ? LHS.get()->getSourceRange()
11571                         : RHS.get()->getSourceRange());
11572       return QualType();
11573     }
11574 
11575     return CheckComparisonCategoryType(
11576         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11577   };
11578 
11579   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11580     bool IsEquality = Opc == BO_EQ;
11581     if (RHSIsNull)
11582       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11583                                    RHS.get()->getSourceRange());
11584     else
11585       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11586                                    LHS.get()->getSourceRange());
11587   }
11588 
11589   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11590       (RHSType->isIntegerType() && !RHSIsNull)) {
11591     // Skip normal pointer conversion checks in this case; we have better
11592     // diagnostics for this below.
11593   } else if (getLangOpts().CPlusPlus) {
11594     // Equality comparison of a function pointer to a void pointer is invalid,
11595     // but we allow it as an extension.
11596     // FIXME: If we really want to allow this, should it be part of composite
11597     // pointer type computation so it works in conditionals too?
11598     if (!IsOrdered &&
11599         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11600          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11601       // This is a gcc extension compatibility comparison.
11602       // In a SFINAE context, we treat this as a hard error to maintain
11603       // conformance with the C++ standard.
11604       diagnoseFunctionPointerToVoidComparison(
11605           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11606 
11607       if (isSFINAEContext())
11608         return QualType();
11609 
11610       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11611       return computeResultTy();
11612     }
11613 
11614     // C++ [expr.eq]p2:
11615     //   If at least one operand is a pointer [...] bring them to their
11616     //   composite pointer type.
11617     // C++ [expr.spaceship]p6
11618     //  If at least one of the operands is of pointer type, [...] bring them
11619     //  to their composite pointer type.
11620     // C++ [expr.rel]p2:
11621     //   If both operands are pointers, [...] bring them to their composite
11622     //   pointer type.
11623     // For <=>, the only valid non-pointer types are arrays and functions, and
11624     // we already decayed those, so this is really the same as the relational
11625     // comparison rule.
11626     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11627             (IsOrdered ? 2 : 1) &&
11628         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11629                                          RHSType->isObjCObjectPointerType()))) {
11630       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11631         return QualType();
11632       return computeResultTy();
11633     }
11634   } else if (LHSType->isPointerType() &&
11635              RHSType->isPointerType()) { // C99 6.5.8p2
11636     // All of the following pointer-related warnings are GCC extensions, except
11637     // when handling null pointer constants.
11638     QualType LCanPointeeTy =
11639       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11640     QualType RCanPointeeTy =
11641       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11642 
11643     // C99 6.5.9p2 and C99 6.5.8p2
11644     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11645                                    RCanPointeeTy.getUnqualifiedType())) {
11646       if (IsRelational) {
11647         // Pointers both need to point to complete or incomplete types
11648         if ((LCanPointeeTy->isIncompleteType() !=
11649              RCanPointeeTy->isIncompleteType()) &&
11650             !getLangOpts().C11) {
11651           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11652               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11653               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11654               << RCanPointeeTy->isIncompleteType();
11655         }
11656         if (LCanPointeeTy->isFunctionType()) {
11657           // Valid unless a relational comparison of function pointers
11658           Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11659               << LHSType << RHSType << LHS.get()->getSourceRange()
11660               << RHS.get()->getSourceRange();
11661         }
11662       }
11663     } else if (!IsRelational &&
11664                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11665       // Valid unless comparison between non-null pointer and function pointer
11666       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11667           && !LHSIsNull && !RHSIsNull)
11668         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11669                                                 /*isError*/false);
11670     } else {
11671       // Invalid
11672       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11673     }
11674     if (LCanPointeeTy != RCanPointeeTy) {
11675       // Treat NULL constant as a special case in OpenCL.
11676       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11677         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11678           Diag(Loc,
11679                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11680               << LHSType << RHSType << 0 /* comparison */
11681               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11682         }
11683       }
11684       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11685       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11686       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11687                                                : CK_BitCast;
11688       if (LHSIsNull && !RHSIsNull)
11689         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11690       else
11691         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11692     }
11693     return computeResultTy();
11694   }
11695 
11696   if (getLangOpts().CPlusPlus) {
11697     // C++ [expr.eq]p4:
11698     //   Two operands of type std::nullptr_t or one operand of type
11699     //   std::nullptr_t and the other a null pointer constant compare equal.
11700     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11701       if (LHSType->isNullPtrType()) {
11702         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11703         return computeResultTy();
11704       }
11705       if (RHSType->isNullPtrType()) {
11706         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11707         return computeResultTy();
11708       }
11709     }
11710 
11711     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11712     // These aren't covered by the composite pointer type rules.
11713     if (!IsOrdered && RHSType->isNullPtrType() &&
11714         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11715       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11716       return computeResultTy();
11717     }
11718     if (!IsOrdered && LHSType->isNullPtrType() &&
11719         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11720       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11721       return computeResultTy();
11722     }
11723 
11724     if (IsRelational &&
11725         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11726          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11727       // HACK: Relational comparison of nullptr_t against a pointer type is
11728       // invalid per DR583, but we allow it within std::less<> and friends,
11729       // since otherwise common uses of it break.
11730       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11731       // friends to have std::nullptr_t overload candidates.
11732       DeclContext *DC = CurContext;
11733       if (isa<FunctionDecl>(DC))
11734         DC = DC->getParent();
11735       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11736         if (CTSD->isInStdNamespace() &&
11737             llvm::StringSwitch<bool>(CTSD->getName())
11738                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11739                 .Default(false)) {
11740           if (RHSType->isNullPtrType())
11741             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11742           else
11743             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11744           return computeResultTy();
11745         }
11746       }
11747     }
11748 
11749     // C++ [expr.eq]p2:
11750     //   If at least one operand is a pointer to member, [...] bring them to
11751     //   their composite pointer type.
11752     if (!IsOrdered &&
11753         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11754       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11755         return QualType();
11756       else
11757         return computeResultTy();
11758     }
11759   }
11760 
11761   // Handle block pointer types.
11762   if (!IsOrdered && LHSType->isBlockPointerType() &&
11763       RHSType->isBlockPointerType()) {
11764     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11765     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11766 
11767     if (!LHSIsNull && !RHSIsNull &&
11768         !Context.typesAreCompatible(lpointee, rpointee)) {
11769       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11770         << LHSType << RHSType << LHS.get()->getSourceRange()
11771         << RHS.get()->getSourceRange();
11772     }
11773     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11774     return computeResultTy();
11775   }
11776 
11777   // Allow block pointers to be compared with null pointer constants.
11778   if (!IsOrdered
11779       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11780           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11781     if (!LHSIsNull && !RHSIsNull) {
11782       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11783              ->getPointeeType()->isVoidType())
11784             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11785                 ->getPointeeType()->isVoidType())))
11786         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11787           << LHSType << RHSType << LHS.get()->getSourceRange()
11788           << RHS.get()->getSourceRange();
11789     }
11790     if (LHSIsNull && !RHSIsNull)
11791       LHS = ImpCastExprToType(LHS.get(), RHSType,
11792                               RHSType->isPointerType() ? CK_BitCast
11793                                 : CK_AnyPointerToBlockPointerCast);
11794     else
11795       RHS = ImpCastExprToType(RHS.get(), LHSType,
11796                               LHSType->isPointerType() ? CK_BitCast
11797                                 : CK_AnyPointerToBlockPointerCast);
11798     return computeResultTy();
11799   }
11800 
11801   if (LHSType->isObjCObjectPointerType() ||
11802       RHSType->isObjCObjectPointerType()) {
11803     const PointerType *LPT = LHSType->getAs<PointerType>();
11804     const PointerType *RPT = RHSType->getAs<PointerType>();
11805     if (LPT || RPT) {
11806       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11807       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11808 
11809       if (!LPtrToVoid && !RPtrToVoid &&
11810           !Context.typesAreCompatible(LHSType, RHSType)) {
11811         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11812                                           /*isError*/false);
11813       }
11814       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11815       // the RHS, but we have test coverage for this behavior.
11816       // FIXME: Consider using convertPointersToCompositeType in C++.
11817       if (LHSIsNull && !RHSIsNull) {
11818         Expr *E = LHS.get();
11819         if (getLangOpts().ObjCAutoRefCount)
11820           CheckObjCConversion(SourceRange(), RHSType, E,
11821                               CCK_ImplicitConversion);
11822         LHS = ImpCastExprToType(E, RHSType,
11823                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11824       }
11825       else {
11826         Expr *E = RHS.get();
11827         if (getLangOpts().ObjCAutoRefCount)
11828           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11829                               /*Diagnose=*/true,
11830                               /*DiagnoseCFAudited=*/false, Opc);
11831         RHS = ImpCastExprToType(E, LHSType,
11832                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11833       }
11834       return computeResultTy();
11835     }
11836     if (LHSType->isObjCObjectPointerType() &&
11837         RHSType->isObjCObjectPointerType()) {
11838       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11839         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11840                                           /*isError*/false);
11841       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11842         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11843 
11844       if (LHSIsNull && !RHSIsNull)
11845         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11846       else
11847         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11848       return computeResultTy();
11849     }
11850 
11851     if (!IsOrdered && LHSType->isBlockPointerType() &&
11852         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11853       LHS = ImpCastExprToType(LHS.get(), RHSType,
11854                               CK_BlockPointerToObjCPointerCast);
11855       return computeResultTy();
11856     } else if (!IsOrdered &&
11857                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11858                RHSType->isBlockPointerType()) {
11859       RHS = ImpCastExprToType(RHS.get(), LHSType,
11860                               CK_BlockPointerToObjCPointerCast);
11861       return computeResultTy();
11862     }
11863   }
11864   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11865       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11866     unsigned DiagID = 0;
11867     bool isError = false;
11868     if (LangOpts.DebuggerSupport) {
11869       // Under a debugger, allow the comparison of pointers to integers,
11870       // since users tend to want to compare addresses.
11871     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11872                (RHSIsNull && RHSType->isIntegerType())) {
11873       if (IsOrdered) {
11874         isError = getLangOpts().CPlusPlus;
11875         DiagID =
11876           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11877                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11878       }
11879     } else if (getLangOpts().CPlusPlus) {
11880       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11881       isError = true;
11882     } else if (IsOrdered)
11883       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11884     else
11885       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11886 
11887     if (DiagID) {
11888       Diag(Loc, DiagID)
11889         << LHSType << RHSType << LHS.get()->getSourceRange()
11890         << RHS.get()->getSourceRange();
11891       if (isError)
11892         return QualType();
11893     }
11894 
11895     if (LHSType->isIntegerType())
11896       LHS = ImpCastExprToType(LHS.get(), RHSType,
11897                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11898     else
11899       RHS = ImpCastExprToType(RHS.get(), LHSType,
11900                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11901     return computeResultTy();
11902   }
11903 
11904   // Handle block pointers.
11905   if (!IsOrdered && RHSIsNull
11906       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11907     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11908     return computeResultTy();
11909   }
11910   if (!IsOrdered && LHSIsNull
11911       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11912     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11913     return computeResultTy();
11914   }
11915 
11916   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11917     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11918       return computeResultTy();
11919     }
11920 
11921     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11922       return computeResultTy();
11923     }
11924 
11925     if (LHSIsNull && RHSType->isQueueT()) {
11926       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11927       return computeResultTy();
11928     }
11929 
11930     if (LHSType->isQueueT() && RHSIsNull) {
11931       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11932       return computeResultTy();
11933     }
11934   }
11935 
11936   return InvalidOperands(Loc, LHS, RHS);
11937 }
11938 
11939 // Return a signed ext_vector_type that is of identical size and number of
11940 // elements. For floating point vectors, return an integer type of identical
11941 // size and number of elements. In the non ext_vector_type case, search from
11942 // the largest type to the smallest type to avoid cases where long long == long,
11943 // where long gets picked over long long.
11944 QualType Sema::GetSignedVectorType(QualType V) {
11945   const VectorType *VTy = V->castAs<VectorType>();
11946   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11947 
11948   if (isa<ExtVectorType>(VTy)) {
11949     if (TypeSize == Context.getTypeSize(Context.CharTy))
11950       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11951     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11952       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11953     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11954       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11955     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11956       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11957     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11958            "Unhandled vector element size in vector compare");
11959     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11960   }
11961 
11962   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11963     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11964                                  VectorType::GenericVector);
11965   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11966     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11967                                  VectorType::GenericVector);
11968   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11969     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11970                                  VectorType::GenericVector);
11971   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11972     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11973                                  VectorType::GenericVector);
11974   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11975          "Unhandled vector element size in vector compare");
11976   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11977                                VectorType::GenericVector);
11978 }
11979 
11980 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11981 /// operates on extended vector types.  Instead of producing an IntTy result,
11982 /// like a scalar comparison, a vector comparison produces a vector of integer
11983 /// types.
11984 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11985                                           SourceLocation Loc,
11986                                           BinaryOperatorKind Opc) {
11987   if (Opc == BO_Cmp) {
11988     Diag(Loc, diag::err_three_way_vector_comparison);
11989     return QualType();
11990   }
11991 
11992   // Check to make sure we're operating on vectors of the same type and width,
11993   // Allowing one side to be a scalar of element type.
11994   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11995                               /*AllowBothBool*/true,
11996                               /*AllowBoolConversions*/getLangOpts().ZVector);
11997   if (vType.isNull())
11998     return vType;
11999 
12000   QualType LHSType = LHS.get()->getType();
12001 
12002   // If AltiVec, the comparison results in a numeric type, i.e.
12003   // bool for C++, int for C
12004   if (getLangOpts().AltiVec &&
12005       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
12006     return Context.getLogicalOperationType();
12007 
12008   // For non-floating point types, check for self-comparisons of the form
12009   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12010   // often indicate logic errors in the program.
12011   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12012 
12013   // Check for comparisons of floating point operands using != and ==.
12014   if (BinaryOperator::isEqualityOp(Opc) &&
12015       LHSType->hasFloatingRepresentation()) {
12016     assert(RHS.get()->getType()->hasFloatingRepresentation());
12017     CheckFloatComparison(Loc, LHS.get(), RHS.get());
12018   }
12019 
12020   // Return a signed type for the vector.
12021   return GetSignedVectorType(vType);
12022 }
12023 
12024 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12025                                     const ExprResult &XorRHS,
12026                                     const SourceLocation Loc) {
12027   // Do not diagnose macros.
12028   if (Loc.isMacroID())
12029     return;
12030 
12031   bool Negative = false;
12032   bool ExplicitPlus = false;
12033   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12034   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12035 
12036   if (!LHSInt)
12037     return;
12038   if (!RHSInt) {
12039     // Check negative literals.
12040     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12041       UnaryOperatorKind Opc = UO->getOpcode();
12042       if (Opc != UO_Minus && Opc != UO_Plus)
12043         return;
12044       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12045       if (!RHSInt)
12046         return;
12047       Negative = (Opc == UO_Minus);
12048       ExplicitPlus = !Negative;
12049     } else {
12050       return;
12051     }
12052   }
12053 
12054   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12055   llvm::APInt RightSideValue = RHSInt->getValue();
12056   if (LeftSideValue != 2 && LeftSideValue != 10)
12057     return;
12058 
12059   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12060     return;
12061 
12062   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12063       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12064   llvm::StringRef ExprStr =
12065       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12066 
12067   CharSourceRange XorRange =
12068       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12069   llvm::StringRef XorStr =
12070       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12071   // Do not diagnose if xor keyword/macro is used.
12072   if (XorStr == "xor")
12073     return;
12074 
12075   std::string LHSStr = std::string(Lexer::getSourceText(
12076       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12077       S.getSourceManager(), S.getLangOpts()));
12078   std::string RHSStr = std::string(Lexer::getSourceText(
12079       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12080       S.getSourceManager(), S.getLangOpts()));
12081 
12082   if (Negative) {
12083     RightSideValue = -RightSideValue;
12084     RHSStr = "-" + RHSStr;
12085   } else if (ExplicitPlus) {
12086     RHSStr = "+" + RHSStr;
12087   }
12088 
12089   StringRef LHSStrRef = LHSStr;
12090   StringRef RHSStrRef = RHSStr;
12091   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12092   // literals.
12093   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12094       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12095       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12096       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12097       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12098       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12099       LHSStrRef.find('\'') != StringRef::npos ||
12100       RHSStrRef.find('\'') != StringRef::npos)
12101     return;
12102 
12103   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12104   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12105   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12106   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12107     std::string SuggestedExpr = "1 << " + RHSStr;
12108     bool Overflow = false;
12109     llvm::APInt One = (LeftSideValue - 1);
12110     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12111     if (Overflow) {
12112       if (RightSideIntValue < 64)
12113         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12114             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12115             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12116       else if (RightSideIntValue == 64)
12117         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12118       else
12119         return;
12120     } else {
12121       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12122           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12123           << PowValue.toString(10, true)
12124           << FixItHint::CreateReplacement(
12125                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12126     }
12127 
12128     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12129   } else if (LeftSideValue == 10) {
12130     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12131     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12132         << ExprStr << XorValue.toString(10, true) << SuggestedValue
12133         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12134     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12135   }
12136 }
12137 
12138 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12139                                           SourceLocation Loc) {
12140   // Ensure that either both operands are of the same vector type, or
12141   // one operand is of a vector type and the other is of its element type.
12142   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12143                                        /*AllowBothBool*/true,
12144                                        /*AllowBoolConversions*/false);
12145   if (vType.isNull())
12146     return InvalidOperands(Loc, LHS, RHS);
12147   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12148       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12149     return InvalidOperands(Loc, LHS, RHS);
12150   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12151   //        usage of the logical operators && and || with vectors in C. This
12152   //        check could be notionally dropped.
12153   if (!getLangOpts().CPlusPlus &&
12154       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12155     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12156 
12157   return GetSignedVectorType(LHS.get()->getType());
12158 }
12159 
12160 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12161                                               SourceLocation Loc,
12162                                               bool IsCompAssign) {
12163   if (!IsCompAssign) {
12164     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12165     if (LHS.isInvalid())
12166       return QualType();
12167   }
12168   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12169   if (RHS.isInvalid())
12170     return QualType();
12171 
12172   // For conversion purposes, we ignore any qualifiers.
12173   // For example, "const float" and "float" are equivalent.
12174   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12175   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12176 
12177   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12178   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12179   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12180 
12181   if (Context.hasSameType(LHSType, RHSType))
12182     return LHSType;
12183 
12184   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12185   // case we have to return InvalidOperands.
12186   ExprResult OriginalLHS = LHS;
12187   ExprResult OriginalRHS = RHS;
12188   if (LHSMatType && !RHSMatType) {
12189     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12190     if (!RHS.isInvalid())
12191       return LHSType;
12192 
12193     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12194   }
12195 
12196   if (!LHSMatType && RHSMatType) {
12197     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12198     if (!LHS.isInvalid())
12199       return RHSType;
12200     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12201   }
12202 
12203   return InvalidOperands(Loc, LHS, RHS);
12204 }
12205 
12206 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12207                                            SourceLocation Loc,
12208                                            bool IsCompAssign) {
12209   if (!IsCompAssign) {
12210     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12211     if (LHS.isInvalid())
12212       return QualType();
12213   }
12214   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12215   if (RHS.isInvalid())
12216     return QualType();
12217 
12218   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12219   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12220   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12221 
12222   if (LHSMatType && RHSMatType) {
12223     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12224       return InvalidOperands(Loc, LHS, RHS);
12225 
12226     if (!Context.hasSameType(LHSMatType->getElementType(),
12227                              RHSMatType->getElementType()))
12228       return InvalidOperands(Loc, LHS, RHS);
12229 
12230     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12231                                          LHSMatType->getNumRows(),
12232                                          RHSMatType->getNumColumns());
12233   }
12234   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12235 }
12236 
12237 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12238                                            SourceLocation Loc,
12239                                            BinaryOperatorKind Opc) {
12240   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12241 
12242   bool IsCompAssign =
12243       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12244 
12245   if (LHS.get()->getType()->isVectorType() ||
12246       RHS.get()->getType()->isVectorType()) {
12247     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12248         RHS.get()->getType()->hasIntegerRepresentation())
12249       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12250                         /*AllowBothBool*/true,
12251                         /*AllowBoolConversions*/getLangOpts().ZVector);
12252     return InvalidOperands(Loc, LHS, RHS);
12253   }
12254 
12255   if (Opc == BO_And)
12256     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12257 
12258   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12259       RHS.get()->getType()->hasFloatingRepresentation())
12260     return InvalidOperands(Loc, LHS, RHS);
12261 
12262   ExprResult LHSResult = LHS, RHSResult = RHS;
12263   QualType compType = UsualArithmeticConversions(
12264       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12265   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12266     return QualType();
12267   LHS = LHSResult.get();
12268   RHS = RHSResult.get();
12269 
12270   if (Opc == BO_Xor)
12271     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12272 
12273   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12274     return compType;
12275   return InvalidOperands(Loc, LHS, RHS);
12276 }
12277 
12278 // C99 6.5.[13,14]
12279 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12280                                            SourceLocation Loc,
12281                                            BinaryOperatorKind Opc) {
12282   // Check vector operands differently.
12283   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12284     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12285 
12286   bool EnumConstantInBoolContext = false;
12287   for (const ExprResult &HS : {LHS, RHS}) {
12288     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12289       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12290       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12291         EnumConstantInBoolContext = true;
12292     }
12293   }
12294 
12295   if (EnumConstantInBoolContext)
12296     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12297 
12298   // Diagnose cases where the user write a logical and/or but probably meant a
12299   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12300   // is a constant.
12301   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12302       !LHS.get()->getType()->isBooleanType() &&
12303       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12304       // Don't warn in macros or template instantiations.
12305       !Loc.isMacroID() && !inTemplateInstantiation()) {
12306     // If the RHS can be constant folded, and if it constant folds to something
12307     // that isn't 0 or 1 (which indicate a potential logical operation that
12308     // happened to fold to true/false) then warn.
12309     // Parens on the RHS are ignored.
12310     Expr::EvalResult EVResult;
12311     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12312       llvm::APSInt Result = EVResult.Val.getInt();
12313       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12314            !RHS.get()->getExprLoc().isMacroID()) ||
12315           (Result != 0 && Result != 1)) {
12316         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12317           << RHS.get()->getSourceRange()
12318           << (Opc == BO_LAnd ? "&&" : "||");
12319         // Suggest replacing the logical operator with the bitwise version
12320         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12321             << (Opc == BO_LAnd ? "&" : "|")
12322             << FixItHint::CreateReplacement(SourceRange(
12323                                                  Loc, getLocForEndOfToken(Loc)),
12324                                             Opc == BO_LAnd ? "&" : "|");
12325         if (Opc == BO_LAnd)
12326           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12327           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12328               << FixItHint::CreateRemoval(
12329                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12330                                  RHS.get()->getEndLoc()));
12331       }
12332     }
12333   }
12334 
12335   if (!Context.getLangOpts().CPlusPlus) {
12336     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12337     // not operate on the built-in scalar and vector float types.
12338     if (Context.getLangOpts().OpenCL &&
12339         Context.getLangOpts().OpenCLVersion < 120) {
12340       if (LHS.get()->getType()->isFloatingType() ||
12341           RHS.get()->getType()->isFloatingType())
12342         return InvalidOperands(Loc, LHS, RHS);
12343     }
12344 
12345     LHS = UsualUnaryConversions(LHS.get());
12346     if (LHS.isInvalid())
12347       return QualType();
12348 
12349     RHS = UsualUnaryConversions(RHS.get());
12350     if (RHS.isInvalid())
12351       return QualType();
12352 
12353     if (!LHS.get()->getType()->isScalarType() ||
12354         !RHS.get()->getType()->isScalarType())
12355       return InvalidOperands(Loc, LHS, RHS);
12356 
12357     return Context.IntTy;
12358   }
12359 
12360   // The following is safe because we only use this method for
12361   // non-overloadable operands.
12362 
12363   // C++ [expr.log.and]p1
12364   // C++ [expr.log.or]p1
12365   // The operands are both contextually converted to type bool.
12366   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12367   if (LHSRes.isInvalid())
12368     return InvalidOperands(Loc, LHS, RHS);
12369   LHS = LHSRes;
12370 
12371   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12372   if (RHSRes.isInvalid())
12373     return InvalidOperands(Loc, LHS, RHS);
12374   RHS = RHSRes;
12375 
12376   // C++ [expr.log.and]p2
12377   // C++ [expr.log.or]p2
12378   // The result is a bool.
12379   return Context.BoolTy;
12380 }
12381 
12382 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12383   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12384   if (!ME) return false;
12385   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12386   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12387       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12388   if (!Base) return false;
12389   return Base->getMethodDecl() != nullptr;
12390 }
12391 
12392 /// Is the given expression (which must be 'const') a reference to a
12393 /// variable which was originally non-const, but which has become
12394 /// 'const' due to being captured within a block?
12395 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12396 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12397   assert(E->isLValue() && E->getType().isConstQualified());
12398   E = E->IgnoreParens();
12399 
12400   // Must be a reference to a declaration from an enclosing scope.
12401   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12402   if (!DRE) return NCCK_None;
12403   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12404 
12405   // The declaration must be a variable which is not declared 'const'.
12406   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12407   if (!var) return NCCK_None;
12408   if (var->getType().isConstQualified()) return NCCK_None;
12409   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12410 
12411   // Decide whether the first capture was for a block or a lambda.
12412   DeclContext *DC = S.CurContext, *Prev = nullptr;
12413   // Decide whether the first capture was for a block or a lambda.
12414   while (DC) {
12415     // For init-capture, it is possible that the variable belongs to the
12416     // template pattern of the current context.
12417     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12418       if (var->isInitCapture() &&
12419           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12420         break;
12421     if (DC == var->getDeclContext())
12422       break;
12423     Prev = DC;
12424     DC = DC->getParent();
12425   }
12426   // Unless we have an init-capture, we've gone one step too far.
12427   if (!var->isInitCapture())
12428     DC = Prev;
12429   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12430 }
12431 
12432 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12433   Ty = Ty.getNonReferenceType();
12434   if (IsDereference && Ty->isPointerType())
12435     Ty = Ty->getPointeeType();
12436   return !Ty.isConstQualified();
12437 }
12438 
12439 // Update err_typecheck_assign_const and note_typecheck_assign_const
12440 // when this enum is changed.
12441 enum {
12442   ConstFunction,
12443   ConstVariable,
12444   ConstMember,
12445   ConstMethod,
12446   NestedConstMember,
12447   ConstUnknown,  // Keep as last element
12448 };
12449 
12450 /// Emit the "read-only variable not assignable" error and print notes to give
12451 /// more information about why the variable is not assignable, such as pointing
12452 /// to the declaration of a const variable, showing that a method is const, or
12453 /// that the function is returning a const reference.
12454 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12455                                     SourceLocation Loc) {
12456   SourceRange ExprRange = E->getSourceRange();
12457 
12458   // Only emit one error on the first const found.  All other consts will emit
12459   // a note to the error.
12460   bool DiagnosticEmitted = false;
12461 
12462   // Track if the current expression is the result of a dereference, and if the
12463   // next checked expression is the result of a dereference.
12464   bool IsDereference = false;
12465   bool NextIsDereference = false;
12466 
12467   // Loop to process MemberExpr chains.
12468   while (true) {
12469     IsDereference = NextIsDereference;
12470 
12471     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12472     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12473       NextIsDereference = ME->isArrow();
12474       const ValueDecl *VD = ME->getMemberDecl();
12475       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12476         // Mutable fields can be modified even if the class is const.
12477         if (Field->isMutable()) {
12478           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12479           break;
12480         }
12481 
12482         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12483           if (!DiagnosticEmitted) {
12484             S.Diag(Loc, diag::err_typecheck_assign_const)
12485                 << ExprRange << ConstMember << false /*static*/ << Field
12486                 << Field->getType();
12487             DiagnosticEmitted = true;
12488           }
12489           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12490               << ConstMember << false /*static*/ << Field << Field->getType()
12491               << Field->getSourceRange();
12492         }
12493         E = ME->getBase();
12494         continue;
12495       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12496         if (VDecl->getType().isConstQualified()) {
12497           if (!DiagnosticEmitted) {
12498             S.Diag(Loc, diag::err_typecheck_assign_const)
12499                 << ExprRange << ConstMember << true /*static*/ << VDecl
12500                 << VDecl->getType();
12501             DiagnosticEmitted = true;
12502           }
12503           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12504               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12505               << VDecl->getSourceRange();
12506         }
12507         // Static fields do not inherit constness from parents.
12508         break;
12509       }
12510       break; // End MemberExpr
12511     } else if (const ArraySubscriptExpr *ASE =
12512                    dyn_cast<ArraySubscriptExpr>(E)) {
12513       E = ASE->getBase()->IgnoreParenImpCasts();
12514       continue;
12515     } else if (const ExtVectorElementExpr *EVE =
12516                    dyn_cast<ExtVectorElementExpr>(E)) {
12517       E = EVE->getBase()->IgnoreParenImpCasts();
12518       continue;
12519     }
12520     break;
12521   }
12522 
12523   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12524     // Function calls
12525     const FunctionDecl *FD = CE->getDirectCallee();
12526     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12527       if (!DiagnosticEmitted) {
12528         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12529                                                       << ConstFunction << FD;
12530         DiagnosticEmitted = true;
12531       }
12532       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12533              diag::note_typecheck_assign_const)
12534           << ConstFunction << FD << FD->getReturnType()
12535           << FD->getReturnTypeSourceRange();
12536     }
12537   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12538     // Point to variable declaration.
12539     if (const ValueDecl *VD = DRE->getDecl()) {
12540       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12541         if (!DiagnosticEmitted) {
12542           S.Diag(Loc, diag::err_typecheck_assign_const)
12543               << ExprRange << ConstVariable << VD << VD->getType();
12544           DiagnosticEmitted = true;
12545         }
12546         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12547             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12548       }
12549     }
12550   } else if (isa<CXXThisExpr>(E)) {
12551     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12552       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12553         if (MD->isConst()) {
12554           if (!DiagnosticEmitted) {
12555             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12556                                                           << ConstMethod << MD;
12557             DiagnosticEmitted = true;
12558           }
12559           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12560               << ConstMethod << MD << MD->getSourceRange();
12561         }
12562       }
12563     }
12564   }
12565 
12566   if (DiagnosticEmitted)
12567     return;
12568 
12569   // Can't determine a more specific message, so display the generic error.
12570   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12571 }
12572 
12573 enum OriginalExprKind {
12574   OEK_Variable,
12575   OEK_Member,
12576   OEK_LValue
12577 };
12578 
12579 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12580                                          const RecordType *Ty,
12581                                          SourceLocation Loc, SourceRange Range,
12582                                          OriginalExprKind OEK,
12583                                          bool &DiagnosticEmitted) {
12584   std::vector<const RecordType *> RecordTypeList;
12585   RecordTypeList.push_back(Ty);
12586   unsigned NextToCheckIndex = 0;
12587   // We walk the record hierarchy breadth-first to ensure that we print
12588   // diagnostics in field nesting order.
12589   while (RecordTypeList.size() > NextToCheckIndex) {
12590     bool IsNested = NextToCheckIndex > 0;
12591     for (const FieldDecl *Field :
12592          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12593       // First, check every field for constness.
12594       QualType FieldTy = Field->getType();
12595       if (FieldTy.isConstQualified()) {
12596         if (!DiagnosticEmitted) {
12597           S.Diag(Loc, diag::err_typecheck_assign_const)
12598               << Range << NestedConstMember << OEK << VD
12599               << IsNested << Field;
12600           DiagnosticEmitted = true;
12601         }
12602         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12603             << NestedConstMember << IsNested << Field
12604             << FieldTy << Field->getSourceRange();
12605       }
12606 
12607       // Then we append it to the list to check next in order.
12608       FieldTy = FieldTy.getCanonicalType();
12609       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12610         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12611           RecordTypeList.push_back(FieldRecTy);
12612       }
12613     }
12614     ++NextToCheckIndex;
12615   }
12616 }
12617 
12618 /// Emit an error for the case where a record we are trying to assign to has a
12619 /// const-qualified field somewhere in its hierarchy.
12620 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12621                                          SourceLocation Loc) {
12622   QualType Ty = E->getType();
12623   assert(Ty->isRecordType() && "lvalue was not record?");
12624   SourceRange Range = E->getSourceRange();
12625   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12626   bool DiagEmitted = false;
12627 
12628   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12629     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12630             Range, OEK_Member, DiagEmitted);
12631   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12632     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12633             Range, OEK_Variable, DiagEmitted);
12634   else
12635     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12636             Range, OEK_LValue, DiagEmitted);
12637   if (!DiagEmitted)
12638     DiagnoseConstAssignment(S, E, Loc);
12639 }
12640 
12641 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12642 /// emit an error and return true.  If so, return false.
12643 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12644   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12645 
12646   S.CheckShadowingDeclModification(E, Loc);
12647 
12648   SourceLocation OrigLoc = Loc;
12649   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12650                                                               &Loc);
12651   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12652     IsLV = Expr::MLV_InvalidMessageExpression;
12653   if (IsLV == Expr::MLV_Valid)
12654     return false;
12655 
12656   unsigned DiagID = 0;
12657   bool NeedType = false;
12658   switch (IsLV) { // C99 6.5.16p2
12659   case Expr::MLV_ConstQualified:
12660     // Use a specialized diagnostic when we're assigning to an object
12661     // from an enclosing function or block.
12662     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12663       if (NCCK == NCCK_Block)
12664         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12665       else
12666         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12667       break;
12668     }
12669 
12670     // In ARC, use some specialized diagnostics for occasions where we
12671     // infer 'const'.  These are always pseudo-strong variables.
12672     if (S.getLangOpts().ObjCAutoRefCount) {
12673       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12674       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12675         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12676 
12677         // Use the normal diagnostic if it's pseudo-__strong but the
12678         // user actually wrote 'const'.
12679         if (var->isARCPseudoStrong() &&
12680             (!var->getTypeSourceInfo() ||
12681              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12682           // There are three pseudo-strong cases:
12683           //  - self
12684           ObjCMethodDecl *method = S.getCurMethodDecl();
12685           if (method && var == method->getSelfDecl()) {
12686             DiagID = method->isClassMethod()
12687               ? diag::err_typecheck_arc_assign_self_class_method
12688               : diag::err_typecheck_arc_assign_self;
12689 
12690           //  - Objective-C externally_retained attribute.
12691           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12692                      isa<ParmVarDecl>(var)) {
12693             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12694 
12695           //  - fast enumeration variables
12696           } else {
12697             DiagID = diag::err_typecheck_arr_assign_enumeration;
12698           }
12699 
12700           SourceRange Assign;
12701           if (Loc != OrigLoc)
12702             Assign = SourceRange(OrigLoc, OrigLoc);
12703           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12704           // We need to preserve the AST regardless, so migration tool
12705           // can do its job.
12706           return false;
12707         }
12708       }
12709     }
12710 
12711     // If none of the special cases above are triggered, then this is a
12712     // simple const assignment.
12713     if (DiagID == 0) {
12714       DiagnoseConstAssignment(S, E, Loc);
12715       return true;
12716     }
12717 
12718     break;
12719   case Expr::MLV_ConstAddrSpace:
12720     DiagnoseConstAssignment(S, E, Loc);
12721     return true;
12722   case Expr::MLV_ConstQualifiedField:
12723     DiagnoseRecursiveConstFields(S, E, Loc);
12724     return true;
12725   case Expr::MLV_ArrayType:
12726   case Expr::MLV_ArrayTemporary:
12727     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12728     NeedType = true;
12729     break;
12730   case Expr::MLV_NotObjectType:
12731     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12732     NeedType = true;
12733     break;
12734   case Expr::MLV_LValueCast:
12735     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12736     break;
12737   case Expr::MLV_Valid:
12738     llvm_unreachable("did not take early return for MLV_Valid");
12739   case Expr::MLV_InvalidExpression:
12740   case Expr::MLV_MemberFunction:
12741   case Expr::MLV_ClassTemporary:
12742     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12743     break;
12744   case Expr::MLV_IncompleteType:
12745   case Expr::MLV_IncompleteVoidType:
12746     return S.RequireCompleteType(Loc, E->getType(),
12747              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12748   case Expr::MLV_DuplicateVectorComponents:
12749     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12750     break;
12751   case Expr::MLV_NoSetterProperty:
12752     llvm_unreachable("readonly properties should be processed differently");
12753   case Expr::MLV_InvalidMessageExpression:
12754     DiagID = diag::err_readonly_message_assignment;
12755     break;
12756   case Expr::MLV_SubObjCPropertySetting:
12757     DiagID = diag::err_no_subobject_property_setting;
12758     break;
12759   }
12760 
12761   SourceRange Assign;
12762   if (Loc != OrigLoc)
12763     Assign = SourceRange(OrigLoc, OrigLoc);
12764   if (NeedType)
12765     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12766   else
12767     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12768   return true;
12769 }
12770 
12771 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12772                                          SourceLocation Loc,
12773                                          Sema &Sema) {
12774   if (Sema.inTemplateInstantiation())
12775     return;
12776   if (Sema.isUnevaluatedContext())
12777     return;
12778   if (Loc.isInvalid() || Loc.isMacroID())
12779     return;
12780   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12781     return;
12782 
12783   // C / C++ fields
12784   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12785   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12786   if (ML && MR) {
12787     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12788       return;
12789     const ValueDecl *LHSDecl =
12790         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12791     const ValueDecl *RHSDecl =
12792         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12793     if (LHSDecl != RHSDecl)
12794       return;
12795     if (LHSDecl->getType().isVolatileQualified())
12796       return;
12797     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12798       if (RefTy->getPointeeType().isVolatileQualified())
12799         return;
12800 
12801     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12802   }
12803 
12804   // Objective-C instance variables
12805   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12806   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12807   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12808     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12809     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12810     if (RL && RR && RL->getDecl() == RR->getDecl())
12811       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12812   }
12813 }
12814 
12815 // C99 6.5.16.1
12816 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12817                                        SourceLocation Loc,
12818                                        QualType CompoundType) {
12819   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12820 
12821   // Verify that LHS is a modifiable lvalue, and emit error if not.
12822   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12823     return QualType();
12824 
12825   QualType LHSType = LHSExpr->getType();
12826   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12827                                              CompoundType;
12828   // OpenCL v1.2 s6.1.1.1 p2:
12829   // The half data type can only be used to declare a pointer to a buffer that
12830   // contains half values
12831   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12832     LHSType->isHalfType()) {
12833     Diag(Loc, diag::err_opencl_half_load_store) << 1
12834         << LHSType.getUnqualifiedType();
12835     return QualType();
12836   }
12837 
12838   AssignConvertType ConvTy;
12839   if (CompoundType.isNull()) {
12840     Expr *RHSCheck = RHS.get();
12841 
12842     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12843 
12844     QualType LHSTy(LHSType);
12845     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12846     if (RHS.isInvalid())
12847       return QualType();
12848     // Special case of NSObject attributes on c-style pointer types.
12849     if (ConvTy == IncompatiblePointer &&
12850         ((Context.isObjCNSObjectType(LHSType) &&
12851           RHSType->isObjCObjectPointerType()) ||
12852          (Context.isObjCNSObjectType(RHSType) &&
12853           LHSType->isObjCObjectPointerType())))
12854       ConvTy = Compatible;
12855 
12856     if (ConvTy == Compatible &&
12857         LHSType->isObjCObjectType())
12858         Diag(Loc, diag::err_objc_object_assignment)
12859           << LHSType;
12860 
12861     // If the RHS is a unary plus or minus, check to see if they = and + are
12862     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12863     // instead of "x += 4".
12864     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12865       RHSCheck = ICE->getSubExpr();
12866     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12867       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12868           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12869           // Only if the two operators are exactly adjacent.
12870           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12871           // And there is a space or other character before the subexpr of the
12872           // unary +/-.  We don't want to warn on "x=-1".
12873           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12874           UO->getSubExpr()->getBeginLoc().isFileID()) {
12875         Diag(Loc, diag::warn_not_compound_assign)
12876           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12877           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12878       }
12879     }
12880 
12881     if (ConvTy == Compatible) {
12882       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12883         // Warn about retain cycles where a block captures the LHS, but
12884         // not if the LHS is a simple variable into which the block is
12885         // being stored...unless that variable can be captured by reference!
12886         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12887         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12888         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12889           checkRetainCycles(LHSExpr, RHS.get());
12890       }
12891 
12892       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12893           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12894         // It is safe to assign a weak reference into a strong variable.
12895         // Although this code can still have problems:
12896         //   id x = self.weakProp;
12897         //   id y = self.weakProp;
12898         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12899         // paths through the function. This should be revisited if
12900         // -Wrepeated-use-of-weak is made flow-sensitive.
12901         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12902         // variable, which will be valid for the current autorelease scope.
12903         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12904                              RHS.get()->getBeginLoc()))
12905           getCurFunction()->markSafeWeakUse(RHS.get());
12906 
12907       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12908         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12909       }
12910     }
12911   } else {
12912     // Compound assignment "x += y"
12913     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12914   }
12915 
12916   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12917                                RHS.get(), AA_Assigning))
12918     return QualType();
12919 
12920   CheckForNullPointerDereference(*this, LHSExpr);
12921 
12922   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12923     if (CompoundType.isNull()) {
12924       // C++2a [expr.ass]p5:
12925       //   A simple-assignment whose left operand is of a volatile-qualified
12926       //   type is deprecated unless the assignment is either a discarded-value
12927       //   expression or an unevaluated operand
12928       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12929     } else {
12930       // C++2a [expr.ass]p6:
12931       //   [Compound-assignment] expressions are deprecated if E1 has
12932       //   volatile-qualified type
12933       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12934     }
12935   }
12936 
12937   // C99 6.5.16p3: The type of an assignment expression is the type of the
12938   // left operand unless the left operand has qualified type, in which case
12939   // it is the unqualified version of the type of the left operand.
12940   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12941   // is converted to the type of the assignment expression (above).
12942   // C++ 5.17p1: the type of the assignment expression is that of its left
12943   // operand.
12944   return (getLangOpts().CPlusPlus
12945           ? LHSType : LHSType.getUnqualifiedType());
12946 }
12947 
12948 // Only ignore explicit casts to void.
12949 static bool IgnoreCommaOperand(const Expr *E) {
12950   E = E->IgnoreParens();
12951 
12952   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12953     if (CE->getCastKind() == CK_ToVoid) {
12954       return true;
12955     }
12956 
12957     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12958     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12959         CE->getSubExpr()->getType()->isDependentType()) {
12960       return true;
12961     }
12962   }
12963 
12964   return false;
12965 }
12966 
12967 // Look for instances where it is likely the comma operator is confused with
12968 // another operator.  There is an explicit list of acceptable expressions for
12969 // the left hand side of the comma operator, otherwise emit a warning.
12970 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12971   // No warnings in macros
12972   if (Loc.isMacroID())
12973     return;
12974 
12975   // Don't warn in template instantiations.
12976   if (inTemplateInstantiation())
12977     return;
12978 
12979   // Scope isn't fine-grained enough to explicitly list the specific cases, so
12980   // instead, skip more than needed, then call back into here with the
12981   // CommaVisitor in SemaStmt.cpp.
12982   // The listed locations are the initialization and increment portions
12983   // of a for loop.  The additional checks are on the condition of
12984   // if statements, do/while loops, and for loops.
12985   // Differences in scope flags for C89 mode requires the extra logic.
12986   const unsigned ForIncrementFlags =
12987       getLangOpts().C99 || getLangOpts().CPlusPlus
12988           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12989           : Scope::ContinueScope | Scope::BreakScope;
12990   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12991   const unsigned ScopeFlags = getCurScope()->getFlags();
12992   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12993       (ScopeFlags & ForInitFlags) == ForInitFlags)
12994     return;
12995 
12996   // If there are multiple comma operators used together, get the RHS of the
12997   // of the comma operator as the LHS.
12998   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12999     if (BO->getOpcode() != BO_Comma)
13000       break;
13001     LHS = BO->getRHS();
13002   }
13003 
13004   // Only allow some expressions on LHS to not warn.
13005   if (IgnoreCommaOperand(LHS))
13006     return;
13007 
13008   Diag(Loc, diag::warn_comma_operator);
13009   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13010       << LHS->getSourceRange()
13011       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13012                                     LangOpts.CPlusPlus ? "static_cast<void>("
13013                                                        : "(void)(")
13014       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13015                                     ")");
13016 }
13017 
13018 // C99 6.5.17
13019 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13020                                    SourceLocation Loc) {
13021   LHS = S.CheckPlaceholderExpr(LHS.get());
13022   RHS = S.CheckPlaceholderExpr(RHS.get());
13023   if (LHS.isInvalid() || RHS.isInvalid())
13024     return QualType();
13025 
13026   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13027   // operands, but not unary promotions.
13028   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13029 
13030   // So we treat the LHS as a ignored value, and in C++ we allow the
13031   // containing site to determine what should be done with the RHS.
13032   LHS = S.IgnoredValueConversions(LHS.get());
13033   if (LHS.isInvalid())
13034     return QualType();
13035 
13036   S.DiagnoseUnusedExprResult(LHS.get());
13037 
13038   if (!S.getLangOpts().CPlusPlus) {
13039     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13040     if (RHS.isInvalid())
13041       return QualType();
13042     if (!RHS.get()->getType()->isVoidType())
13043       S.RequireCompleteType(Loc, RHS.get()->getType(),
13044                             diag::err_incomplete_type);
13045   }
13046 
13047   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13048     S.DiagnoseCommaOperator(LHS.get(), Loc);
13049 
13050   return RHS.get()->getType();
13051 }
13052 
13053 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13054 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13055 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13056                                                ExprValueKind &VK,
13057                                                ExprObjectKind &OK,
13058                                                SourceLocation OpLoc,
13059                                                bool IsInc, bool IsPrefix) {
13060   if (Op->isTypeDependent())
13061     return S.Context.DependentTy;
13062 
13063   QualType ResType = Op->getType();
13064   // Atomic types can be used for increment / decrement where the non-atomic
13065   // versions can, so ignore the _Atomic() specifier for the purpose of
13066   // checking.
13067   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13068     ResType = ResAtomicType->getValueType();
13069 
13070   assert(!ResType.isNull() && "no type for increment/decrement expression");
13071 
13072   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13073     // Decrement of bool is not allowed.
13074     if (!IsInc) {
13075       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13076       return QualType();
13077     }
13078     // Increment of bool sets it to true, but is deprecated.
13079     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13080                                               : diag::warn_increment_bool)
13081       << Op->getSourceRange();
13082   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13083     // Error on enum increments and decrements in C++ mode
13084     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13085     return QualType();
13086   } else if (ResType->isRealType()) {
13087     // OK!
13088   } else if (ResType->isPointerType()) {
13089     // C99 6.5.2.4p2, 6.5.6p2
13090     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13091       return QualType();
13092   } else if (ResType->isObjCObjectPointerType()) {
13093     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13094     // Otherwise, we just need a complete type.
13095     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13096         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13097       return QualType();
13098   } else if (ResType->isAnyComplexType()) {
13099     // C99 does not support ++/-- on complex types, we allow as an extension.
13100     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13101       << ResType << Op->getSourceRange();
13102   } else if (ResType->isPlaceholderType()) {
13103     ExprResult PR = S.CheckPlaceholderExpr(Op);
13104     if (PR.isInvalid()) return QualType();
13105     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13106                                           IsInc, IsPrefix);
13107   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13108     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13109   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13110              (ResType->castAs<VectorType>()->getVectorKind() !=
13111               VectorType::AltiVecBool)) {
13112     // The z vector extensions allow ++ and -- for non-bool vectors.
13113   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13114             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13115     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13116   } else {
13117     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13118       << ResType << int(IsInc) << Op->getSourceRange();
13119     return QualType();
13120   }
13121   // At this point, we know we have a real, complex or pointer type.
13122   // Now make sure the operand is a modifiable lvalue.
13123   if (CheckForModifiableLvalue(Op, OpLoc, S))
13124     return QualType();
13125   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13126     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13127     //   An operand with volatile-qualified type is deprecated
13128     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13129         << IsInc << ResType;
13130   }
13131   // In C++, a prefix increment is the same type as the operand. Otherwise
13132   // (in C or with postfix), the increment is the unqualified type of the
13133   // operand.
13134   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13135     VK = VK_LValue;
13136     OK = Op->getObjectKind();
13137     return ResType;
13138   } else {
13139     VK = VK_RValue;
13140     return ResType.getUnqualifiedType();
13141   }
13142 }
13143 
13144 
13145 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13146 /// This routine allows us to typecheck complex/recursive expressions
13147 /// where the declaration is needed for type checking. We only need to
13148 /// handle cases when the expression references a function designator
13149 /// or is an lvalue. Here are some examples:
13150 ///  - &(x) => x
13151 ///  - &*****f => f for f a function designator.
13152 ///  - &s.xx => s
13153 ///  - &s.zz[1].yy -> s, if zz is an array
13154 ///  - *(x + 1) -> x, if x is an array
13155 ///  - &"123"[2] -> 0
13156 ///  - & __real__ x -> x
13157 ///
13158 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13159 /// members.
13160 static ValueDecl *getPrimaryDecl(Expr *E) {
13161   switch (E->getStmtClass()) {
13162   case Stmt::DeclRefExprClass:
13163     return cast<DeclRefExpr>(E)->getDecl();
13164   case Stmt::MemberExprClass:
13165     // If this is an arrow operator, the address is an offset from
13166     // the base's value, so the object the base refers to is
13167     // irrelevant.
13168     if (cast<MemberExpr>(E)->isArrow())
13169       return nullptr;
13170     // Otherwise, the expression refers to a part of the base
13171     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13172   case Stmt::ArraySubscriptExprClass: {
13173     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13174     // promotion of register arrays earlier.
13175     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13176     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13177       if (ICE->getSubExpr()->getType()->isArrayType())
13178         return getPrimaryDecl(ICE->getSubExpr());
13179     }
13180     return nullptr;
13181   }
13182   case Stmt::UnaryOperatorClass: {
13183     UnaryOperator *UO = cast<UnaryOperator>(E);
13184 
13185     switch(UO->getOpcode()) {
13186     case UO_Real:
13187     case UO_Imag:
13188     case UO_Extension:
13189       return getPrimaryDecl(UO->getSubExpr());
13190     default:
13191       return nullptr;
13192     }
13193   }
13194   case Stmt::ParenExprClass:
13195     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13196   case Stmt::ImplicitCastExprClass:
13197     // If the result of an implicit cast is an l-value, we care about
13198     // the sub-expression; otherwise, the result here doesn't matter.
13199     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13200   case Stmt::CXXUuidofExprClass:
13201     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13202   default:
13203     return nullptr;
13204   }
13205 }
13206 
13207 namespace {
13208 enum {
13209   AO_Bit_Field = 0,
13210   AO_Vector_Element = 1,
13211   AO_Property_Expansion = 2,
13212   AO_Register_Variable = 3,
13213   AO_Matrix_Element = 4,
13214   AO_No_Error = 5
13215 };
13216 }
13217 /// Diagnose invalid operand for address of operations.
13218 ///
13219 /// \param Type The type of operand which cannot have its address taken.
13220 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13221                                          Expr *E, unsigned Type) {
13222   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13223 }
13224 
13225 /// CheckAddressOfOperand - The operand of & must be either a function
13226 /// designator or an lvalue designating an object. If it is an lvalue, the
13227 /// object cannot be declared with storage class register or be a bit field.
13228 /// Note: The usual conversions are *not* applied to the operand of the &
13229 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13230 /// In C++, the operand might be an overloaded function name, in which case
13231 /// we allow the '&' but retain the overloaded-function type.
13232 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13233   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13234     if (PTy->getKind() == BuiltinType::Overload) {
13235       Expr *E = OrigOp.get()->IgnoreParens();
13236       if (!isa<OverloadExpr>(E)) {
13237         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13238         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13239           << OrigOp.get()->getSourceRange();
13240         return QualType();
13241       }
13242 
13243       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13244       if (isa<UnresolvedMemberExpr>(Ovl))
13245         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13246           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13247             << OrigOp.get()->getSourceRange();
13248           return QualType();
13249         }
13250 
13251       return Context.OverloadTy;
13252     }
13253 
13254     if (PTy->getKind() == BuiltinType::UnknownAny)
13255       return Context.UnknownAnyTy;
13256 
13257     if (PTy->getKind() == BuiltinType::BoundMember) {
13258       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13259         << OrigOp.get()->getSourceRange();
13260       return QualType();
13261     }
13262 
13263     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13264     if (OrigOp.isInvalid()) return QualType();
13265   }
13266 
13267   if (OrigOp.get()->isTypeDependent())
13268     return Context.DependentTy;
13269 
13270   assert(!OrigOp.get()->getType()->isPlaceholderType());
13271 
13272   // Make sure to ignore parentheses in subsequent checks
13273   Expr *op = OrigOp.get()->IgnoreParens();
13274 
13275   // In OpenCL captures for blocks called as lambda functions
13276   // are located in the private address space. Blocks used in
13277   // enqueue_kernel can be located in a different address space
13278   // depending on a vendor implementation. Thus preventing
13279   // taking an address of the capture to avoid invalid AS casts.
13280   if (LangOpts.OpenCL) {
13281     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13282     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13283       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13284       return QualType();
13285     }
13286   }
13287 
13288   if (getLangOpts().C99) {
13289     // Implement C99-only parts of addressof rules.
13290     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13291       if (uOp->getOpcode() == UO_Deref)
13292         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13293         // (assuming the deref expression is valid).
13294         return uOp->getSubExpr()->getType();
13295     }
13296     // Technically, there should be a check for array subscript
13297     // expressions here, but the result of one is always an lvalue anyway.
13298   }
13299   ValueDecl *dcl = getPrimaryDecl(op);
13300 
13301   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13302     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13303                                            op->getBeginLoc()))
13304       return QualType();
13305 
13306   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13307   unsigned AddressOfError = AO_No_Error;
13308 
13309   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13310     bool sfinae = (bool)isSFINAEContext();
13311     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13312                                   : diag::ext_typecheck_addrof_temporary)
13313       << op->getType() << op->getSourceRange();
13314     if (sfinae)
13315       return QualType();
13316     // Materialize the temporary as an lvalue so that we can take its address.
13317     OrigOp = op =
13318         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13319   } else if (isa<ObjCSelectorExpr>(op)) {
13320     return Context.getPointerType(op->getType());
13321   } else if (lval == Expr::LV_MemberFunction) {
13322     // If it's an instance method, make a member pointer.
13323     // The expression must have exactly the form &A::foo.
13324 
13325     // If the underlying expression isn't a decl ref, give up.
13326     if (!isa<DeclRefExpr>(op)) {
13327       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13328         << OrigOp.get()->getSourceRange();
13329       return QualType();
13330     }
13331     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13332     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13333 
13334     // The id-expression was parenthesized.
13335     if (OrigOp.get() != DRE) {
13336       Diag(OpLoc, diag::err_parens_pointer_member_function)
13337         << OrigOp.get()->getSourceRange();
13338 
13339     // The method was named without a qualifier.
13340     } else if (!DRE->getQualifier()) {
13341       if (MD->getParent()->getName().empty())
13342         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13343           << op->getSourceRange();
13344       else {
13345         SmallString<32> Str;
13346         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13347         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13348           << op->getSourceRange()
13349           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13350       }
13351     }
13352 
13353     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13354     if (isa<CXXDestructorDecl>(MD))
13355       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13356 
13357     QualType MPTy = Context.getMemberPointerType(
13358         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13359     // Under the MS ABI, lock down the inheritance model now.
13360     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13361       (void)isCompleteType(OpLoc, MPTy);
13362     return MPTy;
13363   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13364     // C99 6.5.3.2p1
13365     // The operand must be either an l-value or a function designator
13366     if (!op->getType()->isFunctionType()) {
13367       // Use a special diagnostic for loads from property references.
13368       if (isa<PseudoObjectExpr>(op)) {
13369         AddressOfError = AO_Property_Expansion;
13370       } else {
13371         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13372           << op->getType() << op->getSourceRange();
13373         return QualType();
13374       }
13375     }
13376   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13377     // The operand cannot be a bit-field
13378     AddressOfError = AO_Bit_Field;
13379   } else if (op->getObjectKind() == OK_VectorComponent) {
13380     // The operand cannot be an element of a vector
13381     AddressOfError = AO_Vector_Element;
13382   } else if (op->getObjectKind() == OK_MatrixComponent) {
13383     // The operand cannot be an element of a matrix.
13384     AddressOfError = AO_Matrix_Element;
13385   } else if (dcl) { // C99 6.5.3.2p1
13386     // We have an lvalue with a decl. Make sure the decl is not declared
13387     // with the register storage-class specifier.
13388     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13389       // in C++ it is not error to take address of a register
13390       // variable (c++03 7.1.1P3)
13391       if (vd->getStorageClass() == SC_Register &&
13392           !getLangOpts().CPlusPlus) {
13393         AddressOfError = AO_Register_Variable;
13394       }
13395     } else if (isa<MSPropertyDecl>(dcl)) {
13396       AddressOfError = AO_Property_Expansion;
13397     } else if (isa<FunctionTemplateDecl>(dcl)) {
13398       return Context.OverloadTy;
13399     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13400       // Okay: we can take the address of a field.
13401       // Could be a pointer to member, though, if there is an explicit
13402       // scope qualifier for the class.
13403       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13404         DeclContext *Ctx = dcl->getDeclContext();
13405         if (Ctx && Ctx->isRecord()) {
13406           if (dcl->getType()->isReferenceType()) {
13407             Diag(OpLoc,
13408                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13409               << dcl->getDeclName() << dcl->getType();
13410             return QualType();
13411           }
13412 
13413           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13414             Ctx = Ctx->getParent();
13415 
13416           QualType MPTy = Context.getMemberPointerType(
13417               op->getType(),
13418               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13419           // Under the MS ABI, lock down the inheritance model now.
13420           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13421             (void)isCompleteType(OpLoc, MPTy);
13422           return MPTy;
13423         }
13424       }
13425     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13426                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13427       llvm_unreachable("Unknown/unexpected decl type");
13428   }
13429 
13430   if (AddressOfError != AO_No_Error) {
13431     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13432     return QualType();
13433   }
13434 
13435   if (lval == Expr::LV_IncompleteVoidType) {
13436     // Taking the address of a void variable is technically illegal, but we
13437     // allow it in cases which are otherwise valid.
13438     // Example: "extern void x; void* y = &x;".
13439     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13440   }
13441 
13442   // If the operand has type "type", the result has type "pointer to type".
13443   if (op->getType()->isObjCObjectType())
13444     return Context.getObjCObjectPointerType(op->getType());
13445 
13446   CheckAddressOfPackedMember(op);
13447 
13448   return Context.getPointerType(op->getType());
13449 }
13450 
13451 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13452   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13453   if (!DRE)
13454     return;
13455   const Decl *D = DRE->getDecl();
13456   if (!D)
13457     return;
13458   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13459   if (!Param)
13460     return;
13461   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13462     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13463       return;
13464   if (FunctionScopeInfo *FD = S.getCurFunction())
13465     if (!FD->ModifiedNonNullParams.count(Param))
13466       FD->ModifiedNonNullParams.insert(Param);
13467 }
13468 
13469 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13470 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13471                                         SourceLocation OpLoc) {
13472   if (Op->isTypeDependent())
13473     return S.Context.DependentTy;
13474 
13475   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13476   if (ConvResult.isInvalid())
13477     return QualType();
13478   Op = ConvResult.get();
13479   QualType OpTy = Op->getType();
13480   QualType Result;
13481 
13482   if (isa<CXXReinterpretCastExpr>(Op)) {
13483     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13484     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13485                                      Op->getSourceRange());
13486   }
13487 
13488   if (const PointerType *PT = OpTy->getAs<PointerType>())
13489   {
13490     Result = PT->getPointeeType();
13491   }
13492   else if (const ObjCObjectPointerType *OPT =
13493              OpTy->getAs<ObjCObjectPointerType>())
13494     Result = OPT->getPointeeType();
13495   else {
13496     ExprResult PR = S.CheckPlaceholderExpr(Op);
13497     if (PR.isInvalid()) return QualType();
13498     if (PR.get() != Op)
13499       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13500   }
13501 
13502   if (Result.isNull()) {
13503     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13504       << OpTy << Op->getSourceRange();
13505     return QualType();
13506   }
13507 
13508   // Note that per both C89 and C99, indirection is always legal, even if Result
13509   // is an incomplete type or void.  It would be possible to warn about
13510   // dereferencing a void pointer, but it's completely well-defined, and such a
13511   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13512   // for pointers to 'void' but is fine for any other pointer type:
13513   //
13514   // C++ [expr.unary.op]p1:
13515   //   [...] the expression to which [the unary * operator] is applied shall
13516   //   be a pointer to an object type, or a pointer to a function type
13517   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13518     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13519       << OpTy << Op->getSourceRange();
13520 
13521   // Dereferences are usually l-values...
13522   VK = VK_LValue;
13523 
13524   // ...except that certain expressions are never l-values in C.
13525   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13526     VK = VK_RValue;
13527 
13528   return Result;
13529 }
13530 
13531 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13532   BinaryOperatorKind Opc;
13533   switch (Kind) {
13534   default: llvm_unreachable("Unknown binop!");
13535   case tok::periodstar:           Opc = BO_PtrMemD; break;
13536   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13537   case tok::star:                 Opc = BO_Mul; break;
13538   case tok::slash:                Opc = BO_Div; break;
13539   case tok::percent:              Opc = BO_Rem; break;
13540   case tok::plus:                 Opc = BO_Add; break;
13541   case tok::minus:                Opc = BO_Sub; break;
13542   case tok::lessless:             Opc = BO_Shl; break;
13543   case tok::greatergreater:       Opc = BO_Shr; break;
13544   case tok::lessequal:            Opc = BO_LE; break;
13545   case tok::less:                 Opc = BO_LT; break;
13546   case tok::greaterequal:         Opc = BO_GE; break;
13547   case tok::greater:              Opc = BO_GT; break;
13548   case tok::exclaimequal:         Opc = BO_NE; break;
13549   case tok::equalequal:           Opc = BO_EQ; break;
13550   case tok::spaceship:            Opc = BO_Cmp; break;
13551   case tok::amp:                  Opc = BO_And; break;
13552   case tok::caret:                Opc = BO_Xor; break;
13553   case tok::pipe:                 Opc = BO_Or; break;
13554   case tok::ampamp:               Opc = BO_LAnd; break;
13555   case tok::pipepipe:             Opc = BO_LOr; break;
13556   case tok::equal:                Opc = BO_Assign; break;
13557   case tok::starequal:            Opc = BO_MulAssign; break;
13558   case tok::slashequal:           Opc = BO_DivAssign; break;
13559   case tok::percentequal:         Opc = BO_RemAssign; break;
13560   case tok::plusequal:            Opc = BO_AddAssign; break;
13561   case tok::minusequal:           Opc = BO_SubAssign; break;
13562   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13563   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13564   case tok::ampequal:             Opc = BO_AndAssign; break;
13565   case tok::caretequal:           Opc = BO_XorAssign; break;
13566   case tok::pipeequal:            Opc = BO_OrAssign; break;
13567   case tok::comma:                Opc = BO_Comma; break;
13568   }
13569   return Opc;
13570 }
13571 
13572 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13573   tok::TokenKind Kind) {
13574   UnaryOperatorKind Opc;
13575   switch (Kind) {
13576   default: llvm_unreachable("Unknown unary op!");
13577   case tok::plusplus:     Opc = UO_PreInc; break;
13578   case tok::minusminus:   Opc = UO_PreDec; break;
13579   case tok::amp:          Opc = UO_AddrOf; break;
13580   case tok::star:         Opc = UO_Deref; break;
13581   case tok::plus:         Opc = UO_Plus; break;
13582   case tok::minus:        Opc = UO_Minus; break;
13583   case tok::tilde:        Opc = UO_Not; break;
13584   case tok::exclaim:      Opc = UO_LNot; break;
13585   case tok::kw___real:    Opc = UO_Real; break;
13586   case tok::kw___imag:    Opc = UO_Imag; break;
13587   case tok::kw___extension__: Opc = UO_Extension; break;
13588   }
13589   return Opc;
13590 }
13591 
13592 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13593 /// This warning suppressed in the event of macro expansions.
13594 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13595                                    SourceLocation OpLoc, bool IsBuiltin) {
13596   if (S.inTemplateInstantiation())
13597     return;
13598   if (S.isUnevaluatedContext())
13599     return;
13600   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13601     return;
13602   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13603   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13604   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13605   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13606   if (!LHSDeclRef || !RHSDeclRef ||
13607       LHSDeclRef->getLocation().isMacroID() ||
13608       RHSDeclRef->getLocation().isMacroID())
13609     return;
13610   const ValueDecl *LHSDecl =
13611     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13612   const ValueDecl *RHSDecl =
13613     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13614   if (LHSDecl != RHSDecl)
13615     return;
13616   if (LHSDecl->getType().isVolatileQualified())
13617     return;
13618   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13619     if (RefTy->getPointeeType().isVolatileQualified())
13620       return;
13621 
13622   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13623                           : diag::warn_self_assignment_overloaded)
13624       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13625       << RHSExpr->getSourceRange();
13626 }
13627 
13628 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13629 /// is usually indicative of introspection within the Objective-C pointer.
13630 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13631                                           SourceLocation OpLoc) {
13632   if (!S.getLangOpts().ObjC)
13633     return;
13634 
13635   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13636   const Expr *LHS = L.get();
13637   const Expr *RHS = R.get();
13638 
13639   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13640     ObjCPointerExpr = LHS;
13641     OtherExpr = RHS;
13642   }
13643   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13644     ObjCPointerExpr = RHS;
13645     OtherExpr = LHS;
13646   }
13647 
13648   // This warning is deliberately made very specific to reduce false
13649   // positives with logic that uses '&' for hashing.  This logic mainly
13650   // looks for code trying to introspect into tagged pointers, which
13651   // code should generally never do.
13652   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13653     unsigned Diag = diag::warn_objc_pointer_masking;
13654     // Determine if we are introspecting the result of performSelectorXXX.
13655     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13656     // Special case messages to -performSelector and friends, which
13657     // can return non-pointer values boxed in a pointer value.
13658     // Some clients may wish to silence warnings in this subcase.
13659     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13660       Selector S = ME->getSelector();
13661       StringRef SelArg0 = S.getNameForSlot(0);
13662       if (SelArg0.startswith("performSelector"))
13663         Diag = diag::warn_objc_pointer_masking_performSelector;
13664     }
13665 
13666     S.Diag(OpLoc, Diag)
13667       << ObjCPointerExpr->getSourceRange();
13668   }
13669 }
13670 
13671 static NamedDecl *getDeclFromExpr(Expr *E) {
13672   if (!E)
13673     return nullptr;
13674   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13675     return DRE->getDecl();
13676   if (auto *ME = dyn_cast<MemberExpr>(E))
13677     return ME->getMemberDecl();
13678   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13679     return IRE->getDecl();
13680   return nullptr;
13681 }
13682 
13683 // This helper function promotes a binary operator's operands (which are of a
13684 // half vector type) to a vector of floats and then truncates the result to
13685 // a vector of either half or short.
13686 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13687                                       BinaryOperatorKind Opc, QualType ResultTy,
13688                                       ExprValueKind VK, ExprObjectKind OK,
13689                                       bool IsCompAssign, SourceLocation OpLoc,
13690                                       FPOptionsOverride FPFeatures) {
13691   auto &Context = S.getASTContext();
13692   assert((isVector(ResultTy, Context.HalfTy) ||
13693           isVector(ResultTy, Context.ShortTy)) &&
13694          "Result must be a vector of half or short");
13695   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13696          isVector(RHS.get()->getType(), Context.HalfTy) &&
13697          "both operands expected to be a half vector");
13698 
13699   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13700   QualType BinOpResTy = RHS.get()->getType();
13701 
13702   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13703   // change BinOpResTy to a vector of ints.
13704   if (isVector(ResultTy, Context.ShortTy))
13705     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13706 
13707   if (IsCompAssign)
13708     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13709                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13710                                           BinOpResTy, BinOpResTy);
13711 
13712   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13713   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13714                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13715   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13716 }
13717 
13718 static std::pair<ExprResult, ExprResult>
13719 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13720                            Expr *RHSExpr) {
13721   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13722   if (!S.Context.isDependenceAllowed()) {
13723     // C cannot handle TypoExpr nodes on either side of a binop because it
13724     // doesn't handle dependent types properly, so make sure any TypoExprs have
13725     // been dealt with before checking the operands.
13726     LHS = S.CorrectDelayedTyposInExpr(LHS);
13727     RHS = S.CorrectDelayedTyposInExpr(
13728         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13729         [Opc, LHS](Expr *E) {
13730           if (Opc != BO_Assign)
13731             return ExprResult(E);
13732           // Avoid correcting the RHS to the same Expr as the LHS.
13733           Decl *D = getDeclFromExpr(E);
13734           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13735         });
13736   }
13737   return std::make_pair(LHS, RHS);
13738 }
13739 
13740 /// Returns true if conversion between vectors of halfs and vectors of floats
13741 /// is needed.
13742 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13743                                      Expr *E0, Expr *E1 = nullptr) {
13744   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13745       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13746     return false;
13747 
13748   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13749     QualType Ty = E->IgnoreImplicit()->getType();
13750 
13751     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13752     // to vectors of floats. Although the element type of the vectors is __fp16,
13753     // the vectors shouldn't be treated as storage-only types. See the
13754     // discussion here: https://reviews.llvm.org/rG825235c140e7
13755     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13756       if (VT->getVectorKind() == VectorType::NeonVector)
13757         return false;
13758       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13759     }
13760     return false;
13761   };
13762 
13763   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13764 }
13765 
13766 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13767 /// operator @p Opc at location @c TokLoc. This routine only supports
13768 /// built-in operations; ActOnBinOp handles overloaded operators.
13769 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13770                                     BinaryOperatorKind Opc,
13771                                     Expr *LHSExpr, Expr *RHSExpr) {
13772   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13773     // The syntax only allows initializer lists on the RHS of assignment,
13774     // so we don't need to worry about accepting invalid code for
13775     // non-assignment operators.
13776     // C++11 5.17p9:
13777     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13778     //   of x = {} is x = T().
13779     InitializationKind Kind = InitializationKind::CreateDirectList(
13780         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13781     InitializedEntity Entity =
13782         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13783     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13784     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13785     if (Init.isInvalid())
13786       return Init;
13787     RHSExpr = Init.get();
13788   }
13789 
13790   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13791   QualType ResultTy;     // Result type of the binary operator.
13792   // The following two variables are used for compound assignment operators
13793   QualType CompLHSTy;    // Type of LHS after promotions for computation
13794   QualType CompResultTy; // Type of computation result
13795   ExprValueKind VK = VK_RValue;
13796   ExprObjectKind OK = OK_Ordinary;
13797   bool ConvertHalfVec = false;
13798 
13799   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13800   if (!LHS.isUsable() || !RHS.isUsable())
13801     return ExprError();
13802 
13803   if (getLangOpts().OpenCL) {
13804     QualType LHSTy = LHSExpr->getType();
13805     QualType RHSTy = RHSExpr->getType();
13806     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13807     // the ATOMIC_VAR_INIT macro.
13808     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13809       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13810       if (BO_Assign == Opc)
13811         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13812       else
13813         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13814       return ExprError();
13815     }
13816 
13817     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13818     // only with a builtin functions and therefore should be disallowed here.
13819     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13820         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13821         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13822         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13823       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13824       return ExprError();
13825     }
13826   }
13827 
13828   switch (Opc) {
13829   case BO_Assign:
13830     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13831     if (getLangOpts().CPlusPlus &&
13832         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13833       VK = LHS.get()->getValueKind();
13834       OK = LHS.get()->getObjectKind();
13835     }
13836     if (!ResultTy.isNull()) {
13837       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13838       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13839 
13840       // Avoid copying a block to the heap if the block is assigned to a local
13841       // auto variable that is declared in the same scope as the block. This
13842       // optimization is unsafe if the local variable is declared in an outer
13843       // scope. For example:
13844       //
13845       // BlockTy b;
13846       // {
13847       //   b = ^{...};
13848       // }
13849       // // It is unsafe to invoke the block here if it wasn't copied to the
13850       // // heap.
13851       // b();
13852 
13853       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13854         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13855           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13856             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13857               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13858 
13859       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13860         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13861                               NTCUC_Assignment, NTCUK_Copy);
13862     }
13863     RecordModifiableNonNullParam(*this, LHS.get());
13864     break;
13865   case BO_PtrMemD:
13866   case BO_PtrMemI:
13867     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13868                                             Opc == BO_PtrMemI);
13869     break;
13870   case BO_Mul:
13871   case BO_Div:
13872     ConvertHalfVec = true;
13873     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13874                                            Opc == BO_Div);
13875     break;
13876   case BO_Rem:
13877     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13878     break;
13879   case BO_Add:
13880     ConvertHalfVec = true;
13881     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13882     break;
13883   case BO_Sub:
13884     ConvertHalfVec = true;
13885     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13886     break;
13887   case BO_Shl:
13888   case BO_Shr:
13889     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13890     break;
13891   case BO_LE:
13892   case BO_LT:
13893   case BO_GE:
13894   case BO_GT:
13895     ConvertHalfVec = true;
13896     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13897     break;
13898   case BO_EQ:
13899   case BO_NE:
13900     ConvertHalfVec = true;
13901     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13902     break;
13903   case BO_Cmp:
13904     ConvertHalfVec = true;
13905     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13906     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13907     break;
13908   case BO_And:
13909     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13910     LLVM_FALLTHROUGH;
13911   case BO_Xor:
13912   case BO_Or:
13913     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13914     break;
13915   case BO_LAnd:
13916   case BO_LOr:
13917     ConvertHalfVec = true;
13918     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13919     break;
13920   case BO_MulAssign:
13921   case BO_DivAssign:
13922     ConvertHalfVec = true;
13923     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13924                                                Opc == BO_DivAssign);
13925     CompLHSTy = CompResultTy;
13926     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13927       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13928     break;
13929   case BO_RemAssign:
13930     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13931     CompLHSTy = CompResultTy;
13932     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13933       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13934     break;
13935   case BO_AddAssign:
13936     ConvertHalfVec = true;
13937     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13938     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13939       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13940     break;
13941   case BO_SubAssign:
13942     ConvertHalfVec = true;
13943     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13944     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13945       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13946     break;
13947   case BO_ShlAssign:
13948   case BO_ShrAssign:
13949     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13950     CompLHSTy = CompResultTy;
13951     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13952       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13953     break;
13954   case BO_AndAssign:
13955   case BO_OrAssign: // fallthrough
13956     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13957     LLVM_FALLTHROUGH;
13958   case BO_XorAssign:
13959     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13960     CompLHSTy = CompResultTy;
13961     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13962       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13963     break;
13964   case BO_Comma:
13965     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13966     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13967       VK = RHS.get()->getValueKind();
13968       OK = RHS.get()->getObjectKind();
13969     }
13970     break;
13971   }
13972   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13973     return ExprError();
13974 
13975   // Some of the binary operations require promoting operands of half vector to
13976   // float vectors and truncating the result back to half vector. For now, we do
13977   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13978   // arm64).
13979   assert(
13980       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
13981                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
13982       "both sides are half vectors or neither sides are");
13983   ConvertHalfVec =
13984       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13985 
13986   // Check for array bounds violations for both sides of the BinaryOperator
13987   CheckArrayAccess(LHS.get());
13988   CheckArrayAccess(RHS.get());
13989 
13990   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13991     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13992                                                  &Context.Idents.get("object_setClass"),
13993                                                  SourceLocation(), LookupOrdinaryName);
13994     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13995       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13996       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13997           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13998                                         "object_setClass(")
13999           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14000                                           ",")
14001           << FixItHint::CreateInsertion(RHSLocEnd, ")");
14002     }
14003     else
14004       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14005   }
14006   else if (const ObjCIvarRefExpr *OIRE =
14007            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14008     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14009 
14010   // Opc is not a compound assignment if CompResultTy is null.
14011   if (CompResultTy.isNull()) {
14012     if (ConvertHalfVec)
14013       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14014                                  OpLoc, CurFPFeatureOverrides());
14015     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14016                                   VK, OK, OpLoc, CurFPFeatureOverrides());
14017   }
14018 
14019   // Handle compound assignments.
14020   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14021       OK_ObjCProperty) {
14022     VK = VK_LValue;
14023     OK = LHS.get()->getObjectKind();
14024   }
14025 
14026   // The LHS is not converted to the result type for fixed-point compound
14027   // assignment as the common type is computed on demand. Reset the CompLHSTy
14028   // to the LHS type we would have gotten after unary conversions.
14029   if (CompResultTy->isFixedPointType())
14030     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14031 
14032   if (ConvertHalfVec)
14033     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14034                                OpLoc, CurFPFeatureOverrides());
14035 
14036   return CompoundAssignOperator::Create(
14037       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14038       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14039 }
14040 
14041 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14042 /// operators are mixed in a way that suggests that the programmer forgot that
14043 /// comparison operators have higher precedence. The most typical example of
14044 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14045 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14046                                       SourceLocation OpLoc, Expr *LHSExpr,
14047                                       Expr *RHSExpr) {
14048   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14049   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14050 
14051   // Check that one of the sides is a comparison operator and the other isn't.
14052   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14053   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14054   if (isLeftComp == isRightComp)
14055     return;
14056 
14057   // Bitwise operations are sometimes used as eager logical ops.
14058   // Don't diagnose this.
14059   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14060   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14061   if (isLeftBitwise || isRightBitwise)
14062     return;
14063 
14064   SourceRange DiagRange = isLeftComp
14065                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14066                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14067   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14068   SourceRange ParensRange =
14069       isLeftComp
14070           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14071           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14072 
14073   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14074     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14075   SuggestParentheses(Self, OpLoc,
14076     Self.PDiag(diag::note_precedence_silence) << OpStr,
14077     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14078   SuggestParentheses(Self, OpLoc,
14079     Self.PDiag(diag::note_precedence_bitwise_first)
14080       << BinaryOperator::getOpcodeStr(Opc),
14081     ParensRange);
14082 }
14083 
14084 /// It accepts a '&&' expr that is inside a '||' one.
14085 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14086 /// in parentheses.
14087 static void
14088 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14089                                        BinaryOperator *Bop) {
14090   assert(Bop->getOpcode() == BO_LAnd);
14091   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14092       << Bop->getSourceRange() << OpLoc;
14093   SuggestParentheses(Self, Bop->getOperatorLoc(),
14094     Self.PDiag(diag::note_precedence_silence)
14095       << Bop->getOpcodeStr(),
14096     Bop->getSourceRange());
14097 }
14098 
14099 /// Returns true if the given expression can be evaluated as a constant
14100 /// 'true'.
14101 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14102   bool Res;
14103   return !E->isValueDependent() &&
14104          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14105 }
14106 
14107 /// Returns true if the given expression can be evaluated as a constant
14108 /// 'false'.
14109 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14110   bool Res;
14111   return !E->isValueDependent() &&
14112          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14113 }
14114 
14115 /// Look for '&&' in the left hand of a '||' expr.
14116 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14117                                              Expr *LHSExpr, Expr *RHSExpr) {
14118   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14119     if (Bop->getOpcode() == BO_LAnd) {
14120       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14121       if (EvaluatesAsFalse(S, RHSExpr))
14122         return;
14123       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14124       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14125         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14126     } else if (Bop->getOpcode() == BO_LOr) {
14127       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14128         // If it's "a || b && 1 || c" we didn't warn earlier for
14129         // "a || b && 1", but warn now.
14130         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14131           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14132       }
14133     }
14134   }
14135 }
14136 
14137 /// Look for '&&' in the right hand of a '||' expr.
14138 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14139                                              Expr *LHSExpr, Expr *RHSExpr) {
14140   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14141     if (Bop->getOpcode() == BO_LAnd) {
14142       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14143       if (EvaluatesAsFalse(S, LHSExpr))
14144         return;
14145       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14146       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14147         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14148     }
14149   }
14150 }
14151 
14152 /// Look for bitwise op in the left or right hand of a bitwise op with
14153 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14154 /// the '&' expression in parentheses.
14155 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14156                                          SourceLocation OpLoc, Expr *SubExpr) {
14157   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14158     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14159       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14160         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14161         << Bop->getSourceRange() << OpLoc;
14162       SuggestParentheses(S, Bop->getOperatorLoc(),
14163         S.PDiag(diag::note_precedence_silence)
14164           << Bop->getOpcodeStr(),
14165         Bop->getSourceRange());
14166     }
14167   }
14168 }
14169 
14170 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14171                                     Expr *SubExpr, StringRef Shift) {
14172   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14173     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14174       StringRef Op = Bop->getOpcodeStr();
14175       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14176           << Bop->getSourceRange() << OpLoc << Shift << Op;
14177       SuggestParentheses(S, Bop->getOperatorLoc(),
14178           S.PDiag(diag::note_precedence_silence) << Op,
14179           Bop->getSourceRange());
14180     }
14181   }
14182 }
14183 
14184 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14185                                  Expr *LHSExpr, Expr *RHSExpr) {
14186   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14187   if (!OCE)
14188     return;
14189 
14190   FunctionDecl *FD = OCE->getDirectCallee();
14191   if (!FD || !FD->isOverloadedOperator())
14192     return;
14193 
14194   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14195   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14196     return;
14197 
14198   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14199       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14200       << (Kind == OO_LessLess);
14201   SuggestParentheses(S, OCE->getOperatorLoc(),
14202                      S.PDiag(diag::note_precedence_silence)
14203                          << (Kind == OO_LessLess ? "<<" : ">>"),
14204                      OCE->getSourceRange());
14205   SuggestParentheses(
14206       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14207       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14208 }
14209 
14210 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14211 /// precedence.
14212 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14213                                     SourceLocation OpLoc, Expr *LHSExpr,
14214                                     Expr *RHSExpr){
14215   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14216   if (BinaryOperator::isBitwiseOp(Opc))
14217     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14218 
14219   // Diagnose "arg1 & arg2 | arg3"
14220   if ((Opc == BO_Or || Opc == BO_Xor) &&
14221       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14222     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14223     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14224   }
14225 
14226   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14227   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14228   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14229     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14230     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14231   }
14232 
14233   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14234       || Opc == BO_Shr) {
14235     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14236     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14237     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14238   }
14239 
14240   // Warn on overloaded shift operators and comparisons, such as:
14241   // cout << 5 == 4;
14242   if (BinaryOperator::isComparisonOp(Opc))
14243     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14244 }
14245 
14246 // Binary Operators.  'Tok' is the token for the operator.
14247 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14248                             tok::TokenKind Kind,
14249                             Expr *LHSExpr, Expr *RHSExpr) {
14250   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14251   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14252   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14253 
14254   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14255   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14256 
14257   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14258 }
14259 
14260 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14261                        UnresolvedSetImpl &Functions) {
14262   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14263   if (OverOp != OO_None && OverOp != OO_Equal)
14264     LookupOverloadedOperatorName(OverOp, S, Functions);
14265 
14266   // In C++20 onwards, we may have a second operator to look up.
14267   if (getLangOpts().CPlusPlus20) {
14268     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14269       LookupOverloadedOperatorName(ExtraOp, S, Functions);
14270   }
14271 }
14272 
14273 /// Build an overloaded binary operator expression in the given scope.
14274 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14275                                        BinaryOperatorKind Opc,
14276                                        Expr *LHS, Expr *RHS) {
14277   switch (Opc) {
14278   case BO_Assign:
14279   case BO_DivAssign:
14280   case BO_RemAssign:
14281   case BO_SubAssign:
14282   case BO_AndAssign:
14283   case BO_OrAssign:
14284   case BO_XorAssign:
14285     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14286     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14287     break;
14288   default:
14289     break;
14290   }
14291 
14292   // Find all of the overloaded operators visible from this point.
14293   UnresolvedSet<16> Functions;
14294   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14295 
14296   // Build the (potentially-overloaded, potentially-dependent)
14297   // binary operation.
14298   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14299 }
14300 
14301 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14302                             BinaryOperatorKind Opc,
14303                             Expr *LHSExpr, Expr *RHSExpr) {
14304   ExprResult LHS, RHS;
14305   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14306   if (!LHS.isUsable() || !RHS.isUsable())
14307     return ExprError();
14308   LHSExpr = LHS.get();
14309   RHSExpr = RHS.get();
14310 
14311   // We want to end up calling one of checkPseudoObjectAssignment
14312   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14313   // both expressions are overloadable or either is type-dependent),
14314   // or CreateBuiltinBinOp (in any other case).  We also want to get
14315   // any placeholder types out of the way.
14316 
14317   // Handle pseudo-objects in the LHS.
14318   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14319     // Assignments with a pseudo-object l-value need special analysis.
14320     if (pty->getKind() == BuiltinType::PseudoObject &&
14321         BinaryOperator::isAssignmentOp(Opc))
14322       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14323 
14324     // Don't resolve overloads if the other type is overloadable.
14325     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14326       // We can't actually test that if we still have a placeholder,
14327       // though.  Fortunately, none of the exceptions we see in that
14328       // code below are valid when the LHS is an overload set.  Note
14329       // that an overload set can be dependently-typed, but it never
14330       // instantiates to having an overloadable type.
14331       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14332       if (resolvedRHS.isInvalid()) return ExprError();
14333       RHSExpr = resolvedRHS.get();
14334 
14335       if (RHSExpr->isTypeDependent() ||
14336           RHSExpr->getType()->isOverloadableType())
14337         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14338     }
14339 
14340     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14341     // template, diagnose the missing 'template' keyword instead of diagnosing
14342     // an invalid use of a bound member function.
14343     //
14344     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14345     // to C++1z [over.over]/1.4, but we already checked for that case above.
14346     if (Opc == BO_LT && inTemplateInstantiation() &&
14347         (pty->getKind() == BuiltinType::BoundMember ||
14348          pty->getKind() == BuiltinType::Overload)) {
14349       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14350       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14351           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14352             return isa<FunctionTemplateDecl>(ND);
14353           })) {
14354         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14355                                 : OE->getNameLoc(),
14356              diag::err_template_kw_missing)
14357           << OE->getName().getAsString() << "";
14358         return ExprError();
14359       }
14360     }
14361 
14362     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14363     if (LHS.isInvalid()) return ExprError();
14364     LHSExpr = LHS.get();
14365   }
14366 
14367   // Handle pseudo-objects in the RHS.
14368   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14369     // An overload in the RHS can potentially be resolved by the type
14370     // being assigned to.
14371     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14372       if (getLangOpts().CPlusPlus &&
14373           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14374            LHSExpr->getType()->isOverloadableType()))
14375         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14376 
14377       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14378     }
14379 
14380     // Don't resolve overloads if the other type is overloadable.
14381     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14382         LHSExpr->getType()->isOverloadableType())
14383       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14384 
14385     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14386     if (!resolvedRHS.isUsable()) return ExprError();
14387     RHSExpr = resolvedRHS.get();
14388   }
14389 
14390   if (getLangOpts().CPlusPlus) {
14391     // If either expression is type-dependent, always build an
14392     // overloaded op.
14393     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14394       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14395 
14396     // Otherwise, build an overloaded op if either expression has an
14397     // overloadable type.
14398     if (LHSExpr->getType()->isOverloadableType() ||
14399         RHSExpr->getType()->isOverloadableType())
14400       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14401   }
14402 
14403   if (getLangOpts().RecoveryAST &&
14404       (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
14405     assert(!getLangOpts().CPlusPlus);
14406     assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
14407            "Should only occur in error-recovery path.");
14408     if (BinaryOperator::isCompoundAssignmentOp(Opc))
14409       // C [6.15.16] p3:
14410       // An assignment expression has the value of the left operand after the
14411       // assignment, but is not an lvalue.
14412       return CompoundAssignOperator::Create(
14413           Context, LHSExpr, RHSExpr, Opc,
14414           LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary,
14415           OpLoc, CurFPFeatureOverrides());
14416     QualType ResultType;
14417     switch (Opc) {
14418     case BO_Assign:
14419       ResultType = LHSExpr->getType().getUnqualifiedType();
14420       break;
14421     case BO_LT:
14422     case BO_GT:
14423     case BO_LE:
14424     case BO_GE:
14425     case BO_EQ:
14426     case BO_NE:
14427     case BO_LAnd:
14428     case BO_LOr:
14429       // These operators have a fixed result type regardless of operands.
14430       ResultType = Context.IntTy;
14431       break;
14432     case BO_Comma:
14433       ResultType = RHSExpr->getType();
14434       break;
14435     default:
14436       ResultType = Context.DependentTy;
14437       break;
14438     }
14439     return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
14440                                   VK_RValue, OK_Ordinary, OpLoc,
14441                                   CurFPFeatureOverrides());
14442   }
14443 
14444   // Build a built-in binary operation.
14445   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14446 }
14447 
14448 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14449   if (T.isNull() || T->isDependentType())
14450     return false;
14451 
14452   if (!T->isPromotableIntegerType())
14453     return true;
14454 
14455   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14456 }
14457 
14458 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14459                                       UnaryOperatorKind Opc,
14460                                       Expr *InputExpr) {
14461   ExprResult Input = InputExpr;
14462   ExprValueKind VK = VK_RValue;
14463   ExprObjectKind OK = OK_Ordinary;
14464   QualType resultType;
14465   bool CanOverflow = false;
14466 
14467   bool ConvertHalfVec = false;
14468   if (getLangOpts().OpenCL) {
14469     QualType Ty = InputExpr->getType();
14470     // The only legal unary operation for atomics is '&'.
14471     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14472     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14473     // only with a builtin functions and therefore should be disallowed here.
14474         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14475         || Ty->isBlockPointerType())) {
14476       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14477                        << InputExpr->getType()
14478                        << Input.get()->getSourceRange());
14479     }
14480   }
14481 
14482   switch (Opc) {
14483   case UO_PreInc:
14484   case UO_PreDec:
14485   case UO_PostInc:
14486   case UO_PostDec:
14487     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14488                                                 OpLoc,
14489                                                 Opc == UO_PreInc ||
14490                                                 Opc == UO_PostInc,
14491                                                 Opc == UO_PreInc ||
14492                                                 Opc == UO_PreDec);
14493     CanOverflow = isOverflowingIntegerType(Context, resultType);
14494     break;
14495   case UO_AddrOf:
14496     resultType = CheckAddressOfOperand(Input, OpLoc);
14497     CheckAddressOfNoDeref(InputExpr);
14498     RecordModifiableNonNullParam(*this, InputExpr);
14499     break;
14500   case UO_Deref: {
14501     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14502     if (Input.isInvalid()) return ExprError();
14503     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14504     break;
14505   }
14506   case UO_Plus:
14507   case UO_Minus:
14508     CanOverflow = Opc == UO_Minus &&
14509                   isOverflowingIntegerType(Context, Input.get()->getType());
14510     Input = UsualUnaryConversions(Input.get());
14511     if (Input.isInvalid()) return ExprError();
14512     // Unary plus and minus require promoting an operand of half vector to a
14513     // float vector and truncating the result back to a half vector. For now, we
14514     // do this only when HalfArgsAndReturns is set (that is, when the target is
14515     // arm or arm64).
14516     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14517 
14518     // If the operand is a half vector, promote it to a float vector.
14519     if (ConvertHalfVec)
14520       Input = convertVector(Input.get(), Context.FloatTy, *this);
14521     resultType = Input.get()->getType();
14522     if (resultType->isDependentType())
14523       break;
14524     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14525       break;
14526     else if (resultType->isVectorType() &&
14527              // The z vector extensions don't allow + or - with bool vectors.
14528              (!Context.getLangOpts().ZVector ||
14529               resultType->castAs<VectorType>()->getVectorKind() !=
14530               VectorType::AltiVecBool))
14531       break;
14532     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14533              Opc == UO_Plus &&
14534              resultType->isPointerType())
14535       break;
14536 
14537     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14538       << resultType << Input.get()->getSourceRange());
14539 
14540   case UO_Not: // bitwise complement
14541     Input = UsualUnaryConversions(Input.get());
14542     if (Input.isInvalid())
14543       return ExprError();
14544     resultType = Input.get()->getType();
14545     if (resultType->isDependentType())
14546       break;
14547     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14548     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14549       // C99 does not support '~' for complex conjugation.
14550       Diag(OpLoc, diag::ext_integer_complement_complex)
14551           << resultType << Input.get()->getSourceRange();
14552     else if (resultType->hasIntegerRepresentation())
14553       break;
14554     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14555       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14556       // on vector float types.
14557       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14558       if (!T->isIntegerType())
14559         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14560                           << resultType << Input.get()->getSourceRange());
14561     } else {
14562       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14563                        << resultType << Input.get()->getSourceRange());
14564     }
14565     break;
14566 
14567   case UO_LNot: // logical negation
14568     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14569     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14570     if (Input.isInvalid()) return ExprError();
14571     resultType = Input.get()->getType();
14572 
14573     // Though we still have to promote half FP to float...
14574     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14575       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14576       resultType = Context.FloatTy;
14577     }
14578 
14579     if (resultType->isDependentType())
14580       break;
14581     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14582       // C99 6.5.3.3p1: ok, fallthrough;
14583       if (Context.getLangOpts().CPlusPlus) {
14584         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14585         // operand contextually converted to bool.
14586         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14587                                   ScalarTypeToBooleanCastKind(resultType));
14588       } else if (Context.getLangOpts().OpenCL &&
14589                  Context.getLangOpts().OpenCLVersion < 120) {
14590         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14591         // operate on scalar float types.
14592         if (!resultType->isIntegerType() && !resultType->isPointerType())
14593           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14594                            << resultType << Input.get()->getSourceRange());
14595       }
14596     } else if (resultType->isExtVectorType()) {
14597       if (Context.getLangOpts().OpenCL &&
14598           Context.getLangOpts().OpenCLVersion < 120 &&
14599           !Context.getLangOpts().OpenCLCPlusPlus) {
14600         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14601         // operate on vector float types.
14602         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14603         if (!T->isIntegerType())
14604           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14605                            << resultType << Input.get()->getSourceRange());
14606       }
14607       // Vector logical not returns the signed variant of the operand type.
14608       resultType = GetSignedVectorType(resultType);
14609       break;
14610     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14611       const VectorType *VTy = resultType->castAs<VectorType>();
14612       if (VTy->getVectorKind() != VectorType::GenericVector)
14613         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14614                          << resultType << Input.get()->getSourceRange());
14615 
14616       // Vector logical not returns the signed variant of the operand type.
14617       resultType = GetSignedVectorType(resultType);
14618       break;
14619     } else {
14620       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14621         << resultType << Input.get()->getSourceRange());
14622     }
14623 
14624     // LNot always has type int. C99 6.5.3.3p5.
14625     // In C++, it's bool. C++ 5.3.1p8
14626     resultType = Context.getLogicalOperationType();
14627     break;
14628   case UO_Real:
14629   case UO_Imag:
14630     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14631     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14632     // complex l-values to ordinary l-values and all other values to r-values.
14633     if (Input.isInvalid()) return ExprError();
14634     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14635       if (Input.get()->getValueKind() != VK_RValue &&
14636           Input.get()->getObjectKind() == OK_Ordinary)
14637         VK = Input.get()->getValueKind();
14638     } else if (!getLangOpts().CPlusPlus) {
14639       // In C, a volatile scalar is read by __imag. In C++, it is not.
14640       Input = DefaultLvalueConversion(Input.get());
14641     }
14642     break;
14643   case UO_Extension:
14644     resultType = Input.get()->getType();
14645     VK = Input.get()->getValueKind();
14646     OK = Input.get()->getObjectKind();
14647     break;
14648   case UO_Coawait:
14649     // It's unnecessary to represent the pass-through operator co_await in the
14650     // AST; just return the input expression instead.
14651     assert(!Input.get()->getType()->isDependentType() &&
14652                    "the co_await expression must be non-dependant before "
14653                    "building operator co_await");
14654     return Input;
14655   }
14656   if (resultType.isNull() || Input.isInvalid())
14657     return ExprError();
14658 
14659   // Check for array bounds violations in the operand of the UnaryOperator,
14660   // except for the '*' and '&' operators that have to be handled specially
14661   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14662   // that are explicitly defined as valid by the standard).
14663   if (Opc != UO_AddrOf && Opc != UO_Deref)
14664     CheckArrayAccess(Input.get());
14665 
14666   auto *UO =
14667       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14668                             OpLoc, CanOverflow, CurFPFeatureOverrides());
14669 
14670   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14671       !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
14672       !isUnevaluatedContext())
14673     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14674 
14675   // Convert the result back to a half vector.
14676   if (ConvertHalfVec)
14677     return convertVector(UO, Context.HalfTy, *this);
14678   return UO;
14679 }
14680 
14681 /// Determine whether the given expression is a qualified member
14682 /// access expression, of a form that could be turned into a pointer to member
14683 /// with the address-of operator.
14684 bool Sema::isQualifiedMemberAccess(Expr *E) {
14685   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14686     if (!DRE->getQualifier())
14687       return false;
14688 
14689     ValueDecl *VD = DRE->getDecl();
14690     if (!VD->isCXXClassMember())
14691       return false;
14692 
14693     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14694       return true;
14695     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14696       return Method->isInstance();
14697 
14698     return false;
14699   }
14700 
14701   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14702     if (!ULE->getQualifier())
14703       return false;
14704 
14705     for (NamedDecl *D : ULE->decls()) {
14706       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14707         if (Method->isInstance())
14708           return true;
14709       } else {
14710         // Overload set does not contain methods.
14711         break;
14712       }
14713     }
14714 
14715     return false;
14716   }
14717 
14718   return false;
14719 }
14720 
14721 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14722                               UnaryOperatorKind Opc, Expr *Input) {
14723   // First things first: handle placeholders so that the
14724   // overloaded-operator check considers the right type.
14725   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14726     // Increment and decrement of pseudo-object references.
14727     if (pty->getKind() == BuiltinType::PseudoObject &&
14728         UnaryOperator::isIncrementDecrementOp(Opc))
14729       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14730 
14731     // extension is always a builtin operator.
14732     if (Opc == UO_Extension)
14733       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14734 
14735     // & gets special logic for several kinds of placeholder.
14736     // The builtin code knows what to do.
14737     if (Opc == UO_AddrOf &&
14738         (pty->getKind() == BuiltinType::Overload ||
14739          pty->getKind() == BuiltinType::UnknownAny ||
14740          pty->getKind() == BuiltinType::BoundMember))
14741       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14742 
14743     // Anything else needs to be handled now.
14744     ExprResult Result = CheckPlaceholderExpr(Input);
14745     if (Result.isInvalid()) return ExprError();
14746     Input = Result.get();
14747   }
14748 
14749   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14750       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14751       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14752     // Find all of the overloaded operators visible from this point.
14753     UnresolvedSet<16> Functions;
14754     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14755     if (S && OverOp != OO_None)
14756       LookupOverloadedOperatorName(OverOp, S, Functions);
14757 
14758     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14759   }
14760 
14761   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14762 }
14763 
14764 // Unary Operators.  'Tok' is the token for the operator.
14765 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14766                               tok::TokenKind Op, Expr *Input) {
14767   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14768 }
14769 
14770 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14771 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14772                                 LabelDecl *TheDecl) {
14773   TheDecl->markUsed(Context);
14774   // Create the AST node.  The address of a label always has type 'void*'.
14775   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14776                                      Context.getPointerType(Context.VoidTy));
14777 }
14778 
14779 void Sema::ActOnStartStmtExpr() {
14780   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14781 }
14782 
14783 void Sema::ActOnStmtExprError() {
14784   // Note that function is also called by TreeTransform when leaving a
14785   // StmtExpr scope without rebuilding anything.
14786 
14787   DiscardCleanupsInEvaluationContext();
14788   PopExpressionEvaluationContext();
14789 }
14790 
14791 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14792                                SourceLocation RPLoc) {
14793   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14794 }
14795 
14796 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14797                                SourceLocation RPLoc, unsigned TemplateDepth) {
14798   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14799   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14800 
14801   if (hasAnyUnrecoverableErrorsInThisFunction())
14802     DiscardCleanupsInEvaluationContext();
14803   assert(!Cleanup.exprNeedsCleanups() &&
14804          "cleanups within StmtExpr not correctly bound!");
14805   PopExpressionEvaluationContext();
14806 
14807   // FIXME: there are a variety of strange constraints to enforce here, for
14808   // example, it is not possible to goto into a stmt expression apparently.
14809   // More semantic analysis is needed.
14810 
14811   // If there are sub-stmts in the compound stmt, take the type of the last one
14812   // as the type of the stmtexpr.
14813   QualType Ty = Context.VoidTy;
14814   bool StmtExprMayBindToTemp = false;
14815   if (!Compound->body_empty()) {
14816     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14817     if (const auto *LastStmt =
14818             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14819       if (const Expr *Value = LastStmt->getExprStmt()) {
14820         StmtExprMayBindToTemp = true;
14821         Ty = Value->getType();
14822       }
14823     }
14824   }
14825 
14826   // FIXME: Check that expression type is complete/non-abstract; statement
14827   // expressions are not lvalues.
14828   Expr *ResStmtExpr =
14829       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14830   if (StmtExprMayBindToTemp)
14831     return MaybeBindToTemporary(ResStmtExpr);
14832   return ResStmtExpr;
14833 }
14834 
14835 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14836   if (ER.isInvalid())
14837     return ExprError();
14838 
14839   // Do function/array conversion on the last expression, but not
14840   // lvalue-to-rvalue.  However, initialize an unqualified type.
14841   ER = DefaultFunctionArrayConversion(ER.get());
14842   if (ER.isInvalid())
14843     return ExprError();
14844   Expr *E = ER.get();
14845 
14846   if (E->isTypeDependent())
14847     return E;
14848 
14849   // In ARC, if the final expression ends in a consume, splice
14850   // the consume out and bind it later.  In the alternate case
14851   // (when dealing with a retainable type), the result
14852   // initialization will create a produce.  In both cases the
14853   // result will be +1, and we'll need to balance that out with
14854   // a bind.
14855   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14856   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14857     return Cast->getSubExpr();
14858 
14859   // FIXME: Provide a better location for the initialization.
14860   return PerformCopyInitialization(
14861       InitializedEntity::InitializeStmtExprResult(
14862           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14863       SourceLocation(), E);
14864 }
14865 
14866 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14867                                       TypeSourceInfo *TInfo,
14868                                       ArrayRef<OffsetOfComponent> Components,
14869                                       SourceLocation RParenLoc) {
14870   QualType ArgTy = TInfo->getType();
14871   bool Dependent = ArgTy->isDependentType();
14872   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14873 
14874   // We must have at least one component that refers to the type, and the first
14875   // one is known to be a field designator.  Verify that the ArgTy represents
14876   // a struct/union/class.
14877   if (!Dependent && !ArgTy->isRecordType())
14878     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14879                        << ArgTy << TypeRange);
14880 
14881   // Type must be complete per C99 7.17p3 because a declaring a variable
14882   // with an incomplete type would be ill-formed.
14883   if (!Dependent
14884       && RequireCompleteType(BuiltinLoc, ArgTy,
14885                              diag::err_offsetof_incomplete_type, TypeRange))
14886     return ExprError();
14887 
14888   bool DidWarnAboutNonPOD = false;
14889   QualType CurrentType = ArgTy;
14890   SmallVector<OffsetOfNode, 4> Comps;
14891   SmallVector<Expr*, 4> Exprs;
14892   for (const OffsetOfComponent &OC : Components) {
14893     if (OC.isBrackets) {
14894       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14895       if (!CurrentType->isDependentType()) {
14896         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14897         if(!AT)
14898           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14899                            << CurrentType);
14900         CurrentType = AT->getElementType();
14901       } else
14902         CurrentType = Context.DependentTy;
14903 
14904       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14905       if (IdxRval.isInvalid())
14906         return ExprError();
14907       Expr *Idx = IdxRval.get();
14908 
14909       // The expression must be an integral expression.
14910       // FIXME: An integral constant expression?
14911       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14912           !Idx->getType()->isIntegerType())
14913         return ExprError(
14914             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14915             << Idx->getSourceRange());
14916 
14917       // Record this array index.
14918       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14919       Exprs.push_back(Idx);
14920       continue;
14921     }
14922 
14923     // Offset of a field.
14924     if (CurrentType->isDependentType()) {
14925       // We have the offset of a field, but we can't look into the dependent
14926       // type. Just record the identifier of the field.
14927       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14928       CurrentType = Context.DependentTy;
14929       continue;
14930     }
14931 
14932     // We need to have a complete type to look into.
14933     if (RequireCompleteType(OC.LocStart, CurrentType,
14934                             diag::err_offsetof_incomplete_type))
14935       return ExprError();
14936 
14937     // Look for the designated field.
14938     const RecordType *RC = CurrentType->getAs<RecordType>();
14939     if (!RC)
14940       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14941                        << CurrentType);
14942     RecordDecl *RD = RC->getDecl();
14943 
14944     // C++ [lib.support.types]p5:
14945     //   The macro offsetof accepts a restricted set of type arguments in this
14946     //   International Standard. type shall be a POD structure or a POD union
14947     //   (clause 9).
14948     // C++11 [support.types]p4:
14949     //   If type is not a standard-layout class (Clause 9), the results are
14950     //   undefined.
14951     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14952       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14953       unsigned DiagID =
14954         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14955                             : diag::ext_offsetof_non_pod_type;
14956 
14957       if (!IsSafe && !DidWarnAboutNonPOD &&
14958           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14959                               PDiag(DiagID)
14960                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14961                               << CurrentType))
14962         DidWarnAboutNonPOD = true;
14963     }
14964 
14965     // Look for the field.
14966     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14967     LookupQualifiedName(R, RD);
14968     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14969     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14970     if (!MemberDecl) {
14971       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14972         MemberDecl = IndirectMemberDecl->getAnonField();
14973     }
14974 
14975     if (!MemberDecl)
14976       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14977                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14978                                                               OC.LocEnd));
14979 
14980     // C99 7.17p3:
14981     //   (If the specified member is a bit-field, the behavior is undefined.)
14982     //
14983     // We diagnose this as an error.
14984     if (MemberDecl->isBitField()) {
14985       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14986         << MemberDecl->getDeclName()
14987         << SourceRange(BuiltinLoc, RParenLoc);
14988       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14989       return ExprError();
14990     }
14991 
14992     RecordDecl *Parent = MemberDecl->getParent();
14993     if (IndirectMemberDecl)
14994       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14995 
14996     // If the member was found in a base class, introduce OffsetOfNodes for
14997     // the base class indirections.
14998     CXXBasePaths Paths;
14999     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15000                       Paths)) {
15001       if (Paths.getDetectedVirtual()) {
15002         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15003           << MemberDecl->getDeclName()
15004           << SourceRange(BuiltinLoc, RParenLoc);
15005         return ExprError();
15006       }
15007 
15008       CXXBasePath &Path = Paths.front();
15009       for (const CXXBasePathElement &B : Path)
15010         Comps.push_back(OffsetOfNode(B.Base));
15011     }
15012 
15013     if (IndirectMemberDecl) {
15014       for (auto *FI : IndirectMemberDecl->chain()) {
15015         assert(isa<FieldDecl>(FI));
15016         Comps.push_back(OffsetOfNode(OC.LocStart,
15017                                      cast<FieldDecl>(FI), OC.LocEnd));
15018       }
15019     } else
15020       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15021 
15022     CurrentType = MemberDecl->getType().getNonReferenceType();
15023   }
15024 
15025   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15026                               Comps, Exprs, RParenLoc);
15027 }
15028 
15029 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15030                                       SourceLocation BuiltinLoc,
15031                                       SourceLocation TypeLoc,
15032                                       ParsedType ParsedArgTy,
15033                                       ArrayRef<OffsetOfComponent> Components,
15034                                       SourceLocation RParenLoc) {
15035 
15036   TypeSourceInfo *ArgTInfo;
15037   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15038   if (ArgTy.isNull())
15039     return ExprError();
15040 
15041   if (!ArgTInfo)
15042     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15043 
15044   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15045 }
15046 
15047 
15048 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15049                                  Expr *CondExpr,
15050                                  Expr *LHSExpr, Expr *RHSExpr,
15051                                  SourceLocation RPLoc) {
15052   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15053 
15054   ExprValueKind VK = VK_RValue;
15055   ExprObjectKind OK = OK_Ordinary;
15056   QualType resType;
15057   bool CondIsTrue = false;
15058   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15059     resType = Context.DependentTy;
15060   } else {
15061     // The conditional expression is required to be a constant expression.
15062     llvm::APSInt condEval(32);
15063     ExprResult CondICE = VerifyIntegerConstantExpression(
15064         CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15065     if (CondICE.isInvalid())
15066       return ExprError();
15067     CondExpr = CondICE.get();
15068     CondIsTrue = condEval.getZExtValue();
15069 
15070     // If the condition is > zero, then the AST type is the same as the LHSExpr.
15071     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15072 
15073     resType = ActiveExpr->getType();
15074     VK = ActiveExpr->getValueKind();
15075     OK = ActiveExpr->getObjectKind();
15076   }
15077 
15078   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15079                                   resType, VK, OK, RPLoc, CondIsTrue);
15080 }
15081 
15082 //===----------------------------------------------------------------------===//
15083 // Clang Extensions.
15084 //===----------------------------------------------------------------------===//
15085 
15086 /// ActOnBlockStart - This callback is invoked when a block literal is started.
15087 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15088   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15089 
15090   if (LangOpts.CPlusPlus) {
15091     MangleNumberingContext *MCtx;
15092     Decl *ManglingContextDecl;
15093     std::tie(MCtx, ManglingContextDecl) =
15094         getCurrentMangleNumberContext(Block->getDeclContext());
15095     if (MCtx) {
15096       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15097       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15098     }
15099   }
15100 
15101   PushBlockScope(CurScope, Block);
15102   CurContext->addDecl(Block);
15103   if (CurScope)
15104     PushDeclContext(CurScope, Block);
15105   else
15106     CurContext = Block;
15107 
15108   getCurBlock()->HasImplicitReturnType = true;
15109 
15110   // Enter a new evaluation context to insulate the block from any
15111   // cleanups from the enclosing full-expression.
15112   PushExpressionEvaluationContext(
15113       ExpressionEvaluationContext::PotentiallyEvaluated);
15114 }
15115 
15116 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15117                                Scope *CurScope) {
15118   assert(ParamInfo.getIdentifier() == nullptr &&
15119          "block-id should have no identifier!");
15120   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15121   BlockScopeInfo *CurBlock = getCurBlock();
15122 
15123   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15124   QualType T = Sig->getType();
15125 
15126   // FIXME: We should allow unexpanded parameter packs here, but that would,
15127   // in turn, make the block expression contain unexpanded parameter packs.
15128   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15129     // Drop the parameters.
15130     FunctionProtoType::ExtProtoInfo EPI;
15131     EPI.HasTrailingReturn = false;
15132     EPI.TypeQuals.addConst();
15133     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15134     Sig = Context.getTrivialTypeSourceInfo(T);
15135   }
15136 
15137   // GetTypeForDeclarator always produces a function type for a block
15138   // literal signature.  Furthermore, it is always a FunctionProtoType
15139   // unless the function was written with a typedef.
15140   assert(T->isFunctionType() &&
15141          "GetTypeForDeclarator made a non-function block signature");
15142 
15143   // Look for an explicit signature in that function type.
15144   FunctionProtoTypeLoc ExplicitSignature;
15145 
15146   if ((ExplicitSignature = Sig->getTypeLoc()
15147                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15148 
15149     // Check whether that explicit signature was synthesized by
15150     // GetTypeForDeclarator.  If so, don't save that as part of the
15151     // written signature.
15152     if (ExplicitSignature.getLocalRangeBegin() ==
15153         ExplicitSignature.getLocalRangeEnd()) {
15154       // This would be much cheaper if we stored TypeLocs instead of
15155       // TypeSourceInfos.
15156       TypeLoc Result = ExplicitSignature.getReturnLoc();
15157       unsigned Size = Result.getFullDataSize();
15158       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15159       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15160 
15161       ExplicitSignature = FunctionProtoTypeLoc();
15162     }
15163   }
15164 
15165   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15166   CurBlock->FunctionType = T;
15167 
15168   const auto *Fn = T->castAs<FunctionType>();
15169   QualType RetTy = Fn->getReturnType();
15170   bool isVariadic =
15171       (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15172 
15173   CurBlock->TheDecl->setIsVariadic(isVariadic);
15174 
15175   // Context.DependentTy is used as a placeholder for a missing block
15176   // return type.  TODO:  what should we do with declarators like:
15177   //   ^ * { ... }
15178   // If the answer is "apply template argument deduction"....
15179   if (RetTy != Context.DependentTy) {
15180     CurBlock->ReturnType = RetTy;
15181     CurBlock->TheDecl->setBlockMissingReturnType(false);
15182     CurBlock->HasImplicitReturnType = false;
15183   }
15184 
15185   // Push block parameters from the declarator if we had them.
15186   SmallVector<ParmVarDecl*, 8> Params;
15187   if (ExplicitSignature) {
15188     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15189       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15190       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15191           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15192         // Diagnose this as an extension in C17 and earlier.
15193         if (!getLangOpts().C2x)
15194           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15195       }
15196       Params.push_back(Param);
15197     }
15198 
15199   // Fake up parameter variables if we have a typedef, like
15200   //   ^ fntype { ... }
15201   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15202     for (const auto &I : Fn->param_types()) {
15203       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15204           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15205       Params.push_back(Param);
15206     }
15207   }
15208 
15209   // Set the parameters on the block decl.
15210   if (!Params.empty()) {
15211     CurBlock->TheDecl->setParams(Params);
15212     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15213                              /*CheckParameterNames=*/false);
15214   }
15215 
15216   // Finally we can process decl attributes.
15217   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15218 
15219   // Put the parameter variables in scope.
15220   for (auto AI : CurBlock->TheDecl->parameters()) {
15221     AI->setOwningFunction(CurBlock->TheDecl);
15222 
15223     // If this has an identifier, add it to the scope stack.
15224     if (AI->getIdentifier()) {
15225       CheckShadow(CurBlock->TheScope, AI);
15226 
15227       PushOnScopeChains(AI, CurBlock->TheScope);
15228     }
15229   }
15230 }
15231 
15232 /// ActOnBlockError - If there is an error parsing a block, this callback
15233 /// is invoked to pop the information about the block from the action impl.
15234 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15235   // Leave the expression-evaluation context.
15236   DiscardCleanupsInEvaluationContext();
15237   PopExpressionEvaluationContext();
15238 
15239   // Pop off CurBlock, handle nested blocks.
15240   PopDeclContext();
15241   PopFunctionScopeInfo();
15242 }
15243 
15244 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15245 /// literal was successfully completed.  ^(int x){...}
15246 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15247                                     Stmt *Body, Scope *CurScope) {
15248   // If blocks are disabled, emit an error.
15249   if (!LangOpts.Blocks)
15250     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15251 
15252   // Leave the expression-evaluation context.
15253   if (hasAnyUnrecoverableErrorsInThisFunction())
15254     DiscardCleanupsInEvaluationContext();
15255   assert(!Cleanup.exprNeedsCleanups() &&
15256          "cleanups within block not correctly bound!");
15257   PopExpressionEvaluationContext();
15258 
15259   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15260   BlockDecl *BD = BSI->TheDecl;
15261 
15262   if (BSI->HasImplicitReturnType)
15263     deduceClosureReturnType(*BSI);
15264 
15265   QualType RetTy = Context.VoidTy;
15266   if (!BSI->ReturnType.isNull())
15267     RetTy = BSI->ReturnType;
15268 
15269   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15270   QualType BlockTy;
15271 
15272   // If the user wrote a function type in some form, try to use that.
15273   if (!BSI->FunctionType.isNull()) {
15274     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15275 
15276     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15277     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15278 
15279     // Turn protoless block types into nullary block types.
15280     if (isa<FunctionNoProtoType>(FTy)) {
15281       FunctionProtoType::ExtProtoInfo EPI;
15282       EPI.ExtInfo = Ext;
15283       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15284 
15285     // Otherwise, if we don't need to change anything about the function type,
15286     // preserve its sugar structure.
15287     } else if (FTy->getReturnType() == RetTy &&
15288                (!NoReturn || FTy->getNoReturnAttr())) {
15289       BlockTy = BSI->FunctionType;
15290 
15291     // Otherwise, make the minimal modifications to the function type.
15292     } else {
15293       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15294       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15295       EPI.TypeQuals = Qualifiers();
15296       EPI.ExtInfo = Ext;
15297       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15298     }
15299 
15300   // If we don't have a function type, just build one from nothing.
15301   } else {
15302     FunctionProtoType::ExtProtoInfo EPI;
15303     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15304     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15305   }
15306 
15307   DiagnoseUnusedParameters(BD->parameters());
15308   BlockTy = Context.getBlockPointerType(BlockTy);
15309 
15310   // If needed, diagnose invalid gotos and switches in the block.
15311   if (getCurFunction()->NeedsScopeChecking() &&
15312       !PP.isCodeCompletionEnabled())
15313     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15314 
15315   BD->setBody(cast<CompoundStmt>(Body));
15316 
15317   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15318     DiagnoseUnguardedAvailabilityViolations(BD);
15319 
15320   // Try to apply the named return value optimization. We have to check again
15321   // if we can do this, though, because blocks keep return statements around
15322   // to deduce an implicit return type.
15323   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15324       !BD->isDependentContext())
15325     computeNRVO(Body, BSI);
15326 
15327   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15328       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15329     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15330                           NTCUK_Destruct|NTCUK_Copy);
15331 
15332   PopDeclContext();
15333 
15334   // Pop the block scope now but keep it alive to the end of this function.
15335   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15336   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15337 
15338   // Set the captured variables on the block.
15339   SmallVector<BlockDecl::Capture, 4> Captures;
15340   for (Capture &Cap : BSI->Captures) {
15341     if (Cap.isInvalid() || Cap.isThisCapture())
15342       continue;
15343 
15344     VarDecl *Var = Cap.getVariable();
15345     Expr *CopyExpr = nullptr;
15346     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15347       if (const RecordType *Record =
15348               Cap.getCaptureType()->getAs<RecordType>()) {
15349         // The capture logic needs the destructor, so make sure we mark it.
15350         // Usually this is unnecessary because most local variables have
15351         // their destructors marked at declaration time, but parameters are
15352         // an exception because it's technically only the call site that
15353         // actually requires the destructor.
15354         if (isa<ParmVarDecl>(Var))
15355           FinalizeVarWithDestructor(Var, Record);
15356 
15357         // Enter a separate potentially-evaluated context while building block
15358         // initializers to isolate their cleanups from those of the block
15359         // itself.
15360         // FIXME: Is this appropriate even when the block itself occurs in an
15361         // unevaluated operand?
15362         EnterExpressionEvaluationContext EvalContext(
15363             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15364 
15365         SourceLocation Loc = Cap.getLocation();
15366 
15367         ExprResult Result = BuildDeclarationNameExpr(
15368             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15369 
15370         // According to the blocks spec, the capture of a variable from
15371         // the stack requires a const copy constructor.  This is not true
15372         // of the copy/move done to move a __block variable to the heap.
15373         if (!Result.isInvalid() &&
15374             !Result.get()->getType().isConstQualified()) {
15375           Result = ImpCastExprToType(Result.get(),
15376                                      Result.get()->getType().withConst(),
15377                                      CK_NoOp, VK_LValue);
15378         }
15379 
15380         if (!Result.isInvalid()) {
15381           Result = PerformCopyInitialization(
15382               InitializedEntity::InitializeBlock(Var->getLocation(),
15383                                                  Cap.getCaptureType(), false),
15384               Loc, Result.get());
15385         }
15386 
15387         // Build a full-expression copy expression if initialization
15388         // succeeded and used a non-trivial constructor.  Recover from
15389         // errors by pretending that the copy isn't necessary.
15390         if (!Result.isInvalid() &&
15391             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15392                 ->isTrivial()) {
15393           Result = MaybeCreateExprWithCleanups(Result);
15394           CopyExpr = Result.get();
15395         }
15396       }
15397     }
15398 
15399     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15400                               CopyExpr);
15401     Captures.push_back(NewCap);
15402   }
15403   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15404 
15405   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15406 
15407   // If the block isn't obviously global, i.e. it captures anything at
15408   // all, then we need to do a few things in the surrounding context:
15409   if (Result->getBlockDecl()->hasCaptures()) {
15410     // First, this expression has a new cleanup object.
15411     ExprCleanupObjects.push_back(Result->getBlockDecl());
15412     Cleanup.setExprNeedsCleanups(true);
15413 
15414     // It also gets a branch-protected scope if any of the captured
15415     // variables needs destruction.
15416     for (const auto &CI : Result->getBlockDecl()->captures()) {
15417       const VarDecl *var = CI.getVariable();
15418       if (var->getType().isDestructedType() != QualType::DK_none) {
15419         setFunctionHasBranchProtectedScope();
15420         break;
15421       }
15422     }
15423   }
15424 
15425   if (getCurFunction())
15426     getCurFunction()->addBlock(BD);
15427 
15428   return Result;
15429 }
15430 
15431 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15432                             SourceLocation RPLoc) {
15433   TypeSourceInfo *TInfo;
15434   GetTypeFromParser(Ty, &TInfo);
15435   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15436 }
15437 
15438 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15439                                 Expr *E, TypeSourceInfo *TInfo,
15440                                 SourceLocation RPLoc) {
15441   Expr *OrigExpr = E;
15442   bool IsMS = false;
15443 
15444   // CUDA device code does not support varargs.
15445   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15446     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15447       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15448       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15449         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15450     }
15451   }
15452 
15453   // NVPTX does not support va_arg expression.
15454   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15455       Context.getTargetInfo().getTriple().isNVPTX())
15456     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15457 
15458   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15459   // as Microsoft ABI on an actual Microsoft platform, where
15460   // __builtin_ms_va_list and __builtin_va_list are the same.)
15461   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15462       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15463     QualType MSVaListType = Context.getBuiltinMSVaListType();
15464     if (Context.hasSameType(MSVaListType, E->getType())) {
15465       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15466         return ExprError();
15467       IsMS = true;
15468     }
15469   }
15470 
15471   // Get the va_list type
15472   QualType VaListType = Context.getBuiltinVaListType();
15473   if (!IsMS) {
15474     if (VaListType->isArrayType()) {
15475       // Deal with implicit array decay; for example, on x86-64,
15476       // va_list is an array, but it's supposed to decay to
15477       // a pointer for va_arg.
15478       VaListType = Context.getArrayDecayedType(VaListType);
15479       // Make sure the input expression also decays appropriately.
15480       ExprResult Result = UsualUnaryConversions(E);
15481       if (Result.isInvalid())
15482         return ExprError();
15483       E = Result.get();
15484     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15485       // If va_list is a record type and we are compiling in C++ mode,
15486       // check the argument using reference binding.
15487       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15488           Context, Context.getLValueReferenceType(VaListType), false);
15489       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15490       if (Init.isInvalid())
15491         return ExprError();
15492       E = Init.getAs<Expr>();
15493     } else {
15494       // Otherwise, the va_list argument must be an l-value because
15495       // it is modified by va_arg.
15496       if (!E->isTypeDependent() &&
15497           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15498         return ExprError();
15499     }
15500   }
15501 
15502   if (!IsMS && !E->isTypeDependent() &&
15503       !Context.hasSameType(VaListType, E->getType()))
15504     return ExprError(
15505         Diag(E->getBeginLoc(),
15506              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15507         << OrigExpr->getType() << E->getSourceRange());
15508 
15509   if (!TInfo->getType()->isDependentType()) {
15510     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15511                             diag::err_second_parameter_to_va_arg_incomplete,
15512                             TInfo->getTypeLoc()))
15513       return ExprError();
15514 
15515     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15516                                TInfo->getType(),
15517                                diag::err_second_parameter_to_va_arg_abstract,
15518                                TInfo->getTypeLoc()))
15519       return ExprError();
15520 
15521     if (!TInfo->getType().isPODType(Context)) {
15522       Diag(TInfo->getTypeLoc().getBeginLoc(),
15523            TInfo->getType()->isObjCLifetimeType()
15524              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15525              : diag::warn_second_parameter_to_va_arg_not_pod)
15526         << TInfo->getType()
15527         << TInfo->getTypeLoc().getSourceRange();
15528     }
15529 
15530     // Check for va_arg where arguments of the given type will be promoted
15531     // (i.e. this va_arg is guaranteed to have undefined behavior).
15532     QualType PromoteType;
15533     if (TInfo->getType()->isPromotableIntegerType()) {
15534       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15535       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15536         PromoteType = QualType();
15537     }
15538     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15539       PromoteType = Context.DoubleTy;
15540     if (!PromoteType.isNull())
15541       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15542                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15543                           << TInfo->getType()
15544                           << PromoteType
15545                           << TInfo->getTypeLoc().getSourceRange());
15546   }
15547 
15548   QualType T = TInfo->getType().getNonLValueExprType(Context);
15549   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15550 }
15551 
15552 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15553   // The type of __null will be int or long, depending on the size of
15554   // pointers on the target.
15555   QualType Ty;
15556   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15557   if (pw == Context.getTargetInfo().getIntWidth())
15558     Ty = Context.IntTy;
15559   else if (pw == Context.getTargetInfo().getLongWidth())
15560     Ty = Context.LongTy;
15561   else if (pw == Context.getTargetInfo().getLongLongWidth())
15562     Ty = Context.LongLongTy;
15563   else {
15564     llvm_unreachable("I don't know size of pointer!");
15565   }
15566 
15567   return new (Context) GNUNullExpr(Ty, TokenLoc);
15568 }
15569 
15570 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15571                                     SourceLocation BuiltinLoc,
15572                                     SourceLocation RPLoc) {
15573   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15574 }
15575 
15576 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15577                                     SourceLocation BuiltinLoc,
15578                                     SourceLocation RPLoc,
15579                                     DeclContext *ParentContext) {
15580   return new (Context)
15581       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15582 }
15583 
15584 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15585                                         bool Diagnose) {
15586   if (!getLangOpts().ObjC)
15587     return false;
15588 
15589   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15590   if (!PT)
15591     return false;
15592   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15593 
15594   // Ignore any parens, implicit casts (should only be
15595   // array-to-pointer decays), and not-so-opaque values.  The last is
15596   // important for making this trigger for property assignments.
15597   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15598   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15599     if (OV->getSourceExpr())
15600       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15601 
15602   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15603     if (!PT->isObjCIdType() &&
15604         !(ID && ID->getIdentifier()->isStr("NSString")))
15605       return false;
15606     if (!SL->isAscii())
15607       return false;
15608 
15609     if (Diagnose) {
15610       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15611           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15612       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15613     }
15614     return true;
15615   }
15616 
15617   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15618       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15619       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15620       !SrcExpr->isNullPointerConstant(
15621           getASTContext(), Expr::NPC_NeverValueDependent)) {
15622     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15623       return false;
15624     if (Diagnose) {
15625       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15626           << /*number*/1
15627           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15628       Expr *NumLit =
15629           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15630       if (NumLit)
15631         Exp = NumLit;
15632     }
15633     return true;
15634   }
15635 
15636   return false;
15637 }
15638 
15639 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15640                                               const Expr *SrcExpr) {
15641   if (!DstType->isFunctionPointerType() ||
15642       !SrcExpr->getType()->isFunctionType())
15643     return false;
15644 
15645   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15646   if (!DRE)
15647     return false;
15648 
15649   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15650   if (!FD)
15651     return false;
15652 
15653   return !S.checkAddressOfFunctionIsAvailable(FD,
15654                                               /*Complain=*/true,
15655                                               SrcExpr->getBeginLoc());
15656 }
15657 
15658 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15659                                     SourceLocation Loc,
15660                                     QualType DstType, QualType SrcType,
15661                                     Expr *SrcExpr, AssignmentAction Action,
15662                                     bool *Complained) {
15663   if (Complained)
15664     *Complained = false;
15665 
15666   // Decode the result (notice that AST's are still created for extensions).
15667   bool CheckInferredResultType = false;
15668   bool isInvalid = false;
15669   unsigned DiagKind = 0;
15670   ConversionFixItGenerator ConvHints;
15671   bool MayHaveConvFixit = false;
15672   bool MayHaveFunctionDiff = false;
15673   const ObjCInterfaceDecl *IFace = nullptr;
15674   const ObjCProtocolDecl *PDecl = nullptr;
15675 
15676   switch (ConvTy) {
15677   case Compatible:
15678       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15679       return false;
15680 
15681   case PointerToInt:
15682     if (getLangOpts().CPlusPlus) {
15683       DiagKind = diag::err_typecheck_convert_pointer_int;
15684       isInvalid = true;
15685     } else {
15686       DiagKind = diag::ext_typecheck_convert_pointer_int;
15687     }
15688     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15689     MayHaveConvFixit = true;
15690     break;
15691   case IntToPointer:
15692     if (getLangOpts().CPlusPlus) {
15693       DiagKind = diag::err_typecheck_convert_int_pointer;
15694       isInvalid = true;
15695     } else {
15696       DiagKind = diag::ext_typecheck_convert_int_pointer;
15697     }
15698     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15699     MayHaveConvFixit = true;
15700     break;
15701   case IncompatibleFunctionPointer:
15702     if (getLangOpts().CPlusPlus) {
15703       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15704       isInvalid = true;
15705     } else {
15706       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15707     }
15708     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15709     MayHaveConvFixit = true;
15710     break;
15711   case IncompatiblePointer:
15712     if (Action == AA_Passing_CFAudited) {
15713       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15714     } else if (getLangOpts().CPlusPlus) {
15715       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15716       isInvalid = true;
15717     } else {
15718       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15719     }
15720     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15721       SrcType->isObjCObjectPointerType();
15722     if (!CheckInferredResultType) {
15723       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15724     } else if (CheckInferredResultType) {
15725       SrcType = SrcType.getUnqualifiedType();
15726       DstType = DstType.getUnqualifiedType();
15727     }
15728     MayHaveConvFixit = true;
15729     break;
15730   case IncompatiblePointerSign:
15731     if (getLangOpts().CPlusPlus) {
15732       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15733       isInvalid = true;
15734     } else {
15735       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15736     }
15737     break;
15738   case FunctionVoidPointer:
15739     if (getLangOpts().CPlusPlus) {
15740       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15741       isInvalid = true;
15742     } else {
15743       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15744     }
15745     break;
15746   case IncompatiblePointerDiscardsQualifiers: {
15747     // Perform array-to-pointer decay if necessary.
15748     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15749 
15750     isInvalid = true;
15751 
15752     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15753     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15754     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15755       DiagKind = diag::err_typecheck_incompatible_address_space;
15756       break;
15757 
15758     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15759       DiagKind = diag::err_typecheck_incompatible_ownership;
15760       break;
15761     }
15762 
15763     llvm_unreachable("unknown error case for discarding qualifiers!");
15764     // fallthrough
15765   }
15766   case CompatiblePointerDiscardsQualifiers:
15767     // If the qualifiers lost were because we were applying the
15768     // (deprecated) C++ conversion from a string literal to a char*
15769     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15770     // Ideally, this check would be performed in
15771     // checkPointerTypesForAssignment. However, that would require a
15772     // bit of refactoring (so that the second argument is an
15773     // expression, rather than a type), which should be done as part
15774     // of a larger effort to fix checkPointerTypesForAssignment for
15775     // C++ semantics.
15776     if (getLangOpts().CPlusPlus &&
15777         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15778       return false;
15779     if (getLangOpts().CPlusPlus) {
15780       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15781       isInvalid = true;
15782     } else {
15783       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15784     }
15785 
15786     break;
15787   case IncompatibleNestedPointerQualifiers:
15788     if (getLangOpts().CPlusPlus) {
15789       isInvalid = true;
15790       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15791     } else {
15792       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15793     }
15794     break;
15795   case IncompatibleNestedPointerAddressSpaceMismatch:
15796     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15797     isInvalid = true;
15798     break;
15799   case IntToBlockPointer:
15800     DiagKind = diag::err_int_to_block_pointer;
15801     isInvalid = true;
15802     break;
15803   case IncompatibleBlockPointer:
15804     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15805     isInvalid = true;
15806     break;
15807   case IncompatibleObjCQualifiedId: {
15808     if (SrcType->isObjCQualifiedIdType()) {
15809       const ObjCObjectPointerType *srcOPT =
15810                 SrcType->castAs<ObjCObjectPointerType>();
15811       for (auto *srcProto : srcOPT->quals()) {
15812         PDecl = srcProto;
15813         break;
15814       }
15815       if (const ObjCInterfaceType *IFaceT =
15816             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15817         IFace = IFaceT->getDecl();
15818     }
15819     else if (DstType->isObjCQualifiedIdType()) {
15820       const ObjCObjectPointerType *dstOPT =
15821         DstType->castAs<ObjCObjectPointerType>();
15822       for (auto *dstProto : dstOPT->quals()) {
15823         PDecl = dstProto;
15824         break;
15825       }
15826       if (const ObjCInterfaceType *IFaceT =
15827             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15828         IFace = IFaceT->getDecl();
15829     }
15830     if (getLangOpts().CPlusPlus) {
15831       DiagKind = diag::err_incompatible_qualified_id;
15832       isInvalid = true;
15833     } else {
15834       DiagKind = diag::warn_incompatible_qualified_id;
15835     }
15836     break;
15837   }
15838   case IncompatibleVectors:
15839     if (getLangOpts().CPlusPlus) {
15840       DiagKind = diag::err_incompatible_vectors;
15841       isInvalid = true;
15842     } else {
15843       DiagKind = diag::warn_incompatible_vectors;
15844     }
15845     break;
15846   case IncompatibleObjCWeakRef:
15847     DiagKind = diag::err_arc_weak_unavailable_assign;
15848     isInvalid = true;
15849     break;
15850   case Incompatible:
15851     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15852       if (Complained)
15853         *Complained = true;
15854       return true;
15855     }
15856 
15857     DiagKind = diag::err_typecheck_convert_incompatible;
15858     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15859     MayHaveConvFixit = true;
15860     isInvalid = true;
15861     MayHaveFunctionDiff = true;
15862     break;
15863   }
15864 
15865   QualType FirstType, SecondType;
15866   switch (Action) {
15867   case AA_Assigning:
15868   case AA_Initializing:
15869     // The destination type comes first.
15870     FirstType = DstType;
15871     SecondType = SrcType;
15872     break;
15873 
15874   case AA_Returning:
15875   case AA_Passing:
15876   case AA_Passing_CFAudited:
15877   case AA_Converting:
15878   case AA_Sending:
15879   case AA_Casting:
15880     // The source type comes first.
15881     FirstType = SrcType;
15882     SecondType = DstType;
15883     break;
15884   }
15885 
15886   PartialDiagnostic FDiag = PDiag(DiagKind);
15887   if (Action == AA_Passing_CFAudited)
15888     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15889   else
15890     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15891 
15892   // If we can fix the conversion, suggest the FixIts.
15893   if (!ConvHints.isNull()) {
15894     for (FixItHint &H : ConvHints.Hints)
15895       FDiag << H;
15896   }
15897 
15898   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15899 
15900   if (MayHaveFunctionDiff)
15901     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15902 
15903   Diag(Loc, FDiag);
15904   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15905        DiagKind == diag::err_incompatible_qualified_id) &&
15906       PDecl && IFace && !IFace->hasDefinition())
15907     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15908         << IFace << PDecl;
15909 
15910   if (SecondType == Context.OverloadTy)
15911     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15912                               FirstType, /*TakingAddress=*/true);
15913 
15914   if (CheckInferredResultType)
15915     EmitRelatedResultTypeNote(SrcExpr);
15916 
15917   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15918     EmitRelatedResultTypeNoteForReturn(DstType);
15919 
15920   if (Complained)
15921     *Complained = true;
15922   return isInvalid;
15923 }
15924 
15925 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15926                                                  llvm::APSInt *Result,
15927                                                  AllowFoldKind CanFold) {
15928   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15929   public:
15930     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
15931                                              QualType T) override {
15932       return S.Diag(Loc, diag::err_ice_not_integral)
15933              << T << S.LangOpts.CPlusPlus;
15934     }
15935     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
15936       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
15937     }
15938   } Diagnoser;
15939 
15940   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
15941 }
15942 
15943 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15944                                                  llvm::APSInt *Result,
15945                                                  unsigned DiagID,
15946                                                  AllowFoldKind CanFold) {
15947   class IDDiagnoser : public VerifyICEDiagnoser {
15948     unsigned DiagID;
15949 
15950   public:
15951     IDDiagnoser(unsigned DiagID)
15952       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15953 
15954     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
15955       return S.Diag(Loc, DiagID);
15956     }
15957   } Diagnoser(DiagID);
15958 
15959   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
15960 }
15961 
15962 Sema::SemaDiagnosticBuilder
15963 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
15964                                              QualType T) {
15965   return diagnoseNotICE(S, Loc);
15966 }
15967 
15968 Sema::SemaDiagnosticBuilder
15969 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
15970   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
15971 }
15972 
15973 ExprResult
15974 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15975                                       VerifyICEDiagnoser &Diagnoser,
15976                                       AllowFoldKind CanFold) {
15977   SourceLocation DiagLoc = E->getBeginLoc();
15978 
15979   if (getLangOpts().CPlusPlus11) {
15980     // C++11 [expr.const]p5:
15981     //   If an expression of literal class type is used in a context where an
15982     //   integral constant expression is required, then that class type shall
15983     //   have a single non-explicit conversion function to an integral or
15984     //   unscoped enumeration type
15985     ExprResult Converted;
15986     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15987       VerifyICEDiagnoser &BaseDiagnoser;
15988     public:
15989       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
15990           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
15991                                 BaseDiagnoser.Suppress, true),
15992             BaseDiagnoser(BaseDiagnoser) {}
15993 
15994       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15995                                            QualType T) override {
15996         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
15997       }
15998 
15999       SemaDiagnosticBuilder diagnoseIncomplete(
16000           Sema &S, SourceLocation Loc, QualType T) override {
16001         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16002       }
16003 
16004       SemaDiagnosticBuilder diagnoseExplicitConv(
16005           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16006         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16007       }
16008 
16009       SemaDiagnosticBuilder noteExplicitConv(
16010           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16011         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16012                  << ConvTy->isEnumeralType() << ConvTy;
16013       }
16014 
16015       SemaDiagnosticBuilder diagnoseAmbiguous(
16016           Sema &S, SourceLocation Loc, QualType T) override {
16017         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16018       }
16019 
16020       SemaDiagnosticBuilder noteAmbiguous(
16021           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16022         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16023                  << ConvTy->isEnumeralType() << ConvTy;
16024       }
16025 
16026       SemaDiagnosticBuilder diagnoseConversion(
16027           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16028         llvm_unreachable("conversion functions are permitted");
16029       }
16030     } ConvertDiagnoser(Diagnoser);
16031 
16032     Converted = PerformContextualImplicitConversion(DiagLoc, E,
16033                                                     ConvertDiagnoser);
16034     if (Converted.isInvalid())
16035       return Converted;
16036     E = Converted.get();
16037     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16038       return ExprError();
16039   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16040     // An ICE must be of integral or unscoped enumeration type.
16041     if (!Diagnoser.Suppress)
16042       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16043           << E->getSourceRange();
16044     return ExprError();
16045   }
16046 
16047   ExprResult RValueExpr = DefaultLvalueConversion(E);
16048   if (RValueExpr.isInvalid())
16049     return ExprError();
16050 
16051   E = RValueExpr.get();
16052 
16053   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16054   // in the non-ICE case.
16055   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16056     if (Result)
16057       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16058     if (!isa<ConstantExpr>(E))
16059       E = ConstantExpr::Create(Context, E);
16060     return E;
16061   }
16062 
16063   Expr::EvalResult EvalResult;
16064   SmallVector<PartialDiagnosticAt, 8> Notes;
16065   EvalResult.Diag = &Notes;
16066 
16067   // Try to evaluate the expression, and produce diagnostics explaining why it's
16068   // not a constant expression as a side-effect.
16069   bool Folded =
16070       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16071       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16072 
16073   if (!isa<ConstantExpr>(E))
16074     E = ConstantExpr::Create(Context, E, EvalResult.Val);
16075 
16076   // In C++11, we can rely on diagnostics being produced for any expression
16077   // which is not a constant expression. If no diagnostics were produced, then
16078   // this is a constant expression.
16079   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16080     if (Result)
16081       *Result = EvalResult.Val.getInt();
16082     return E;
16083   }
16084 
16085   // If our only note is the usual "invalid subexpression" note, just point
16086   // the caret at its location rather than producing an essentially
16087   // redundant note.
16088   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16089         diag::note_invalid_subexpr_in_const_expr) {
16090     DiagLoc = Notes[0].first;
16091     Notes.clear();
16092   }
16093 
16094   if (!Folded || !CanFold) {
16095     if (!Diagnoser.Suppress) {
16096       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16097       for (const PartialDiagnosticAt &Note : Notes)
16098         Diag(Note.first, Note.second);
16099     }
16100 
16101     return ExprError();
16102   }
16103 
16104   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16105   for (const PartialDiagnosticAt &Note : Notes)
16106     Diag(Note.first, Note.second);
16107 
16108   if (Result)
16109     *Result = EvalResult.Val.getInt();
16110   return E;
16111 }
16112 
16113 namespace {
16114   // Handle the case where we conclude a expression which we speculatively
16115   // considered to be unevaluated is actually evaluated.
16116   class TransformToPE : public TreeTransform<TransformToPE> {
16117     typedef TreeTransform<TransformToPE> BaseTransform;
16118 
16119   public:
16120     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16121 
16122     // Make sure we redo semantic analysis
16123     bool AlwaysRebuild() { return true; }
16124     bool ReplacingOriginal() { return true; }
16125 
16126     // We need to special-case DeclRefExprs referring to FieldDecls which
16127     // are not part of a member pointer formation; normal TreeTransforming
16128     // doesn't catch this case because of the way we represent them in the AST.
16129     // FIXME: This is a bit ugly; is it really the best way to handle this
16130     // case?
16131     //
16132     // Error on DeclRefExprs referring to FieldDecls.
16133     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16134       if (isa<FieldDecl>(E->getDecl()) &&
16135           !SemaRef.isUnevaluatedContext())
16136         return SemaRef.Diag(E->getLocation(),
16137                             diag::err_invalid_non_static_member_use)
16138             << E->getDecl() << E->getSourceRange();
16139 
16140       return BaseTransform::TransformDeclRefExpr(E);
16141     }
16142 
16143     // Exception: filter out member pointer formation
16144     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16145       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16146         return E;
16147 
16148       return BaseTransform::TransformUnaryOperator(E);
16149     }
16150 
16151     // The body of a lambda-expression is in a separate expression evaluation
16152     // context so never needs to be transformed.
16153     // FIXME: Ideally we wouldn't transform the closure type either, and would
16154     // just recreate the capture expressions and lambda expression.
16155     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16156       return SkipLambdaBody(E, Body);
16157     }
16158   };
16159 }
16160 
16161 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16162   assert(isUnevaluatedContext() &&
16163          "Should only transform unevaluated expressions");
16164   ExprEvalContexts.back().Context =
16165       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16166   if (isUnevaluatedContext())
16167     return E;
16168   return TransformToPE(*this).TransformExpr(E);
16169 }
16170 
16171 void
16172 Sema::PushExpressionEvaluationContext(
16173     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16174     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16175   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16176                                 LambdaContextDecl, ExprContext);
16177   Cleanup.reset();
16178   if (!MaybeODRUseExprs.empty())
16179     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16180 }
16181 
16182 void
16183 Sema::PushExpressionEvaluationContext(
16184     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16185     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16186   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16187   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16188 }
16189 
16190 namespace {
16191 
16192 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16193   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16194   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16195     if (E->getOpcode() == UO_Deref)
16196       return CheckPossibleDeref(S, E->getSubExpr());
16197   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16198     return CheckPossibleDeref(S, E->getBase());
16199   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16200     return CheckPossibleDeref(S, E->getBase());
16201   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16202     QualType Inner;
16203     QualType Ty = E->getType();
16204     if (const auto *Ptr = Ty->getAs<PointerType>())
16205       Inner = Ptr->getPointeeType();
16206     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16207       Inner = Arr->getElementType();
16208     else
16209       return nullptr;
16210 
16211     if (Inner->hasAttr(attr::NoDeref))
16212       return E;
16213   }
16214   return nullptr;
16215 }
16216 
16217 } // namespace
16218 
16219 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16220   for (const Expr *E : Rec.PossibleDerefs) {
16221     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16222     if (DeclRef) {
16223       const ValueDecl *Decl = DeclRef->getDecl();
16224       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16225           << Decl->getName() << E->getSourceRange();
16226       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16227     } else {
16228       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16229           << E->getSourceRange();
16230     }
16231   }
16232   Rec.PossibleDerefs.clear();
16233 }
16234 
16235 /// Check whether E, which is either a discarded-value expression or an
16236 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16237 /// and if so, remove it from the list of volatile-qualified assignments that
16238 /// we are going to warn are deprecated.
16239 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16240   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16241     return;
16242 
16243   // Note: ignoring parens here is not justified by the standard rules, but
16244   // ignoring parentheses seems like a more reasonable approach, and this only
16245   // drives a deprecation warning so doesn't affect conformance.
16246   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16247     if (BO->getOpcode() == BO_Assign) {
16248       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16249       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16250                  LHSs.end());
16251     }
16252   }
16253 }
16254 
16255 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16256   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16257       RebuildingImmediateInvocation)
16258     return E;
16259 
16260   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16261   /// It's OK if this fails; we'll also remove this in
16262   /// HandleImmediateInvocations, but catching it here allows us to avoid
16263   /// walking the AST looking for it in simple cases.
16264   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16265     if (auto *DeclRef =
16266             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16267       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16268 
16269   E = MaybeCreateExprWithCleanups(E);
16270 
16271   ConstantExpr *Res = ConstantExpr::Create(
16272       getASTContext(), E.get(),
16273       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16274                                    getASTContext()),
16275       /*IsImmediateInvocation*/ true);
16276   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16277   return Res;
16278 }
16279 
16280 static void EvaluateAndDiagnoseImmediateInvocation(
16281     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16282   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16283   Expr::EvalResult Eval;
16284   Eval.Diag = &Notes;
16285   ConstantExpr *CE = Candidate.getPointer();
16286   bool Result = CE->EvaluateAsConstantExpr(
16287       Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
16288   if (!Result || !Notes.empty()) {
16289     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16290     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16291       InnerExpr = FunctionalCast->getSubExpr();
16292     FunctionDecl *FD = nullptr;
16293     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16294       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16295     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16296       FD = Call->getConstructor();
16297     else
16298       llvm_unreachable("unhandled decl kind");
16299     assert(FD->isConsteval());
16300     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16301     for (auto &Note : Notes)
16302       SemaRef.Diag(Note.first, Note.second);
16303     return;
16304   }
16305   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16306 }
16307 
16308 static void RemoveNestedImmediateInvocation(
16309     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16310     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16311   struct ComplexRemove : TreeTransform<ComplexRemove> {
16312     using Base = TreeTransform<ComplexRemove>;
16313     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16314     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16315     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16316         CurrentII;
16317     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16318                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16319                   SmallVector<Sema::ImmediateInvocationCandidate,
16320                               4>::reverse_iterator Current)
16321         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16322     void RemoveImmediateInvocation(ConstantExpr* E) {
16323       auto It = std::find_if(CurrentII, IISet.rend(),
16324                              [E](Sema::ImmediateInvocationCandidate Elem) {
16325                                return Elem.getPointer() == E;
16326                              });
16327       assert(It != IISet.rend() &&
16328              "ConstantExpr marked IsImmediateInvocation should "
16329              "be present");
16330       It->setInt(1); // Mark as deleted
16331     }
16332     ExprResult TransformConstantExpr(ConstantExpr *E) {
16333       if (!E->isImmediateInvocation())
16334         return Base::TransformConstantExpr(E);
16335       RemoveImmediateInvocation(E);
16336       return Base::TransformExpr(E->getSubExpr());
16337     }
16338     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16339     /// we need to remove its DeclRefExpr from the DRSet.
16340     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16341       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16342       return Base::TransformCXXOperatorCallExpr(E);
16343     }
16344     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16345     /// here.
16346     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16347       if (!Init)
16348         return Init;
16349       /// ConstantExpr are the first layer of implicit node to be removed so if
16350       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16351       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16352         if (CE->isImmediateInvocation())
16353           RemoveImmediateInvocation(CE);
16354       return Base::TransformInitializer(Init, NotCopyInit);
16355     }
16356     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16357       DRSet.erase(E);
16358       return E;
16359     }
16360     bool AlwaysRebuild() { return false; }
16361     bool ReplacingOriginal() { return true; }
16362     bool AllowSkippingCXXConstructExpr() {
16363       bool Res = AllowSkippingFirstCXXConstructExpr;
16364       AllowSkippingFirstCXXConstructExpr = true;
16365       return Res;
16366     }
16367     bool AllowSkippingFirstCXXConstructExpr = true;
16368   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16369                 Rec.ImmediateInvocationCandidates, It);
16370 
16371   /// CXXConstructExpr with a single argument are getting skipped by
16372   /// TreeTransform in some situtation because they could be implicit. This
16373   /// can only occur for the top-level CXXConstructExpr because it is used
16374   /// nowhere in the expression being transformed therefore will not be rebuilt.
16375   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16376   /// skipping the first CXXConstructExpr.
16377   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16378     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16379 
16380   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16381   assert(Res.isUsable());
16382   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16383   It->getPointer()->setSubExpr(Res.get());
16384 }
16385 
16386 static void
16387 HandleImmediateInvocations(Sema &SemaRef,
16388                            Sema::ExpressionEvaluationContextRecord &Rec) {
16389   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16390        Rec.ReferenceToConsteval.size() == 0) ||
16391       SemaRef.RebuildingImmediateInvocation)
16392     return;
16393 
16394   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16395   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16396   /// need to remove ReferenceToConsteval in the immediate invocation.
16397   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16398 
16399     /// Prevent sema calls during the tree transform from adding pointers that
16400     /// are already in the sets.
16401     llvm::SaveAndRestore<bool> DisableIITracking(
16402         SemaRef.RebuildingImmediateInvocation, true);
16403 
16404     /// Prevent diagnostic during tree transfrom as they are duplicates
16405     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16406 
16407     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16408          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16409       if (!It->getInt())
16410         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16411   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16412              Rec.ReferenceToConsteval.size()) {
16413     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16414       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16415       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16416       bool VisitDeclRefExpr(DeclRefExpr *E) {
16417         DRSet.erase(E);
16418         return DRSet.size();
16419       }
16420     } Visitor(Rec.ReferenceToConsteval);
16421     Visitor.TraverseStmt(
16422         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16423   }
16424   for (auto CE : Rec.ImmediateInvocationCandidates)
16425     if (!CE.getInt())
16426       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16427   for (auto DR : Rec.ReferenceToConsteval) {
16428     auto *FD = cast<FunctionDecl>(DR->getDecl());
16429     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16430         << FD;
16431     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16432   }
16433 }
16434 
16435 void Sema::PopExpressionEvaluationContext() {
16436   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16437   unsigned NumTypos = Rec.NumTypos;
16438 
16439   if (!Rec.Lambdas.empty()) {
16440     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16441     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16442         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16443       unsigned D;
16444       if (Rec.isUnevaluated()) {
16445         // C++11 [expr.prim.lambda]p2:
16446         //   A lambda-expression shall not appear in an unevaluated operand
16447         //   (Clause 5).
16448         D = diag::err_lambda_unevaluated_operand;
16449       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16450         // C++1y [expr.const]p2:
16451         //   A conditional-expression e is a core constant expression unless the
16452         //   evaluation of e, following the rules of the abstract machine, would
16453         //   evaluate [...] a lambda-expression.
16454         D = diag::err_lambda_in_constant_expression;
16455       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16456         // C++17 [expr.prim.lamda]p2:
16457         // A lambda-expression shall not appear [...] in a template-argument.
16458         D = diag::err_lambda_in_invalid_context;
16459       } else
16460         llvm_unreachable("Couldn't infer lambda error message.");
16461 
16462       for (const auto *L : Rec.Lambdas)
16463         Diag(L->getBeginLoc(), D);
16464     }
16465   }
16466 
16467   WarnOnPendingNoDerefs(Rec);
16468   HandleImmediateInvocations(*this, Rec);
16469 
16470   // Warn on any volatile-qualified simple-assignments that are not discarded-
16471   // value expressions nor unevaluated operands (those cases get removed from
16472   // this list by CheckUnusedVolatileAssignment).
16473   for (auto *BO : Rec.VolatileAssignmentLHSs)
16474     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16475         << BO->getType();
16476 
16477   // When are coming out of an unevaluated context, clear out any
16478   // temporaries that we may have created as part of the evaluation of
16479   // the expression in that context: they aren't relevant because they
16480   // will never be constructed.
16481   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16482     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16483                              ExprCleanupObjects.end());
16484     Cleanup = Rec.ParentCleanup;
16485     CleanupVarDeclMarking();
16486     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16487   // Otherwise, merge the contexts together.
16488   } else {
16489     Cleanup.mergeFrom(Rec.ParentCleanup);
16490     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16491                             Rec.SavedMaybeODRUseExprs.end());
16492   }
16493 
16494   // Pop the current expression evaluation context off the stack.
16495   ExprEvalContexts.pop_back();
16496 
16497   // The global expression evaluation context record is never popped.
16498   ExprEvalContexts.back().NumTypos += NumTypos;
16499 }
16500 
16501 void Sema::DiscardCleanupsInEvaluationContext() {
16502   ExprCleanupObjects.erase(
16503          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16504          ExprCleanupObjects.end());
16505   Cleanup.reset();
16506   MaybeODRUseExprs.clear();
16507 }
16508 
16509 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16510   ExprResult Result = CheckPlaceholderExpr(E);
16511   if (Result.isInvalid())
16512     return ExprError();
16513   E = Result.get();
16514   if (!E->getType()->isVariablyModifiedType())
16515     return E;
16516   return TransformToPotentiallyEvaluated(E);
16517 }
16518 
16519 /// Are we in a context that is potentially constant evaluated per C++20
16520 /// [expr.const]p12?
16521 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16522   /// C++2a [expr.const]p12:
16523   //   An expression or conversion is potentially constant evaluated if it is
16524   switch (SemaRef.ExprEvalContexts.back().Context) {
16525     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16526       // -- a manifestly constant-evaluated expression,
16527     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16528     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16529     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16530       // -- a potentially-evaluated expression,
16531     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16532       // -- an immediate subexpression of a braced-init-list,
16533 
16534       // -- [FIXME] an expression of the form & cast-expression that occurs
16535       //    within a templated entity
16536       // -- a subexpression of one of the above that is not a subexpression of
16537       // a nested unevaluated operand.
16538       return true;
16539 
16540     case Sema::ExpressionEvaluationContext::Unevaluated:
16541     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16542       // Expressions in this context are never evaluated.
16543       return false;
16544   }
16545   llvm_unreachable("Invalid context");
16546 }
16547 
16548 /// Return true if this function has a calling convention that requires mangling
16549 /// in the size of the parameter pack.
16550 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16551   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16552   // we don't need parameter type sizes.
16553   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16554   if (!TT.isOSWindows() || !TT.isX86())
16555     return false;
16556 
16557   // If this is C++ and this isn't an extern "C" function, parameters do not
16558   // need to be complete. In this case, C++ mangling will apply, which doesn't
16559   // use the size of the parameters.
16560   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16561     return false;
16562 
16563   // Stdcall, fastcall, and vectorcall need this special treatment.
16564   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16565   switch (CC) {
16566   case CC_X86StdCall:
16567   case CC_X86FastCall:
16568   case CC_X86VectorCall:
16569     return true;
16570   default:
16571     break;
16572   }
16573   return false;
16574 }
16575 
16576 /// Require that all of the parameter types of function be complete. Normally,
16577 /// parameter types are only required to be complete when a function is called
16578 /// or defined, but to mangle functions with certain calling conventions, the
16579 /// mangler needs to know the size of the parameter list. In this situation,
16580 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16581 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16582 /// result in a linker error. Clang doesn't implement this behavior, and instead
16583 /// attempts to error at compile time.
16584 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16585                                                   SourceLocation Loc) {
16586   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16587     FunctionDecl *FD;
16588     ParmVarDecl *Param;
16589 
16590   public:
16591     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16592         : FD(FD), Param(Param) {}
16593 
16594     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16595       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16596       StringRef CCName;
16597       switch (CC) {
16598       case CC_X86StdCall:
16599         CCName = "stdcall";
16600         break;
16601       case CC_X86FastCall:
16602         CCName = "fastcall";
16603         break;
16604       case CC_X86VectorCall:
16605         CCName = "vectorcall";
16606         break;
16607       default:
16608         llvm_unreachable("CC does not need mangling");
16609       }
16610 
16611       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16612           << Param->getDeclName() << FD->getDeclName() << CCName;
16613     }
16614   };
16615 
16616   for (ParmVarDecl *Param : FD->parameters()) {
16617     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16618     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16619   }
16620 }
16621 
16622 namespace {
16623 enum class OdrUseContext {
16624   /// Declarations in this context are not odr-used.
16625   None,
16626   /// Declarations in this context are formally odr-used, but this is a
16627   /// dependent context.
16628   Dependent,
16629   /// Declarations in this context are odr-used but not actually used (yet).
16630   FormallyOdrUsed,
16631   /// Declarations in this context are used.
16632   Used
16633 };
16634 }
16635 
16636 /// Are we within a context in which references to resolved functions or to
16637 /// variables result in odr-use?
16638 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16639   OdrUseContext Result;
16640 
16641   switch (SemaRef.ExprEvalContexts.back().Context) {
16642     case Sema::ExpressionEvaluationContext::Unevaluated:
16643     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16644     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16645       return OdrUseContext::None;
16646 
16647     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16648     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16649       Result = OdrUseContext::Used;
16650       break;
16651 
16652     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16653       Result = OdrUseContext::FormallyOdrUsed;
16654       break;
16655 
16656     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16657       // A default argument formally results in odr-use, but doesn't actually
16658       // result in a use in any real sense until it itself is used.
16659       Result = OdrUseContext::FormallyOdrUsed;
16660       break;
16661   }
16662 
16663   if (SemaRef.CurContext->isDependentContext())
16664     return OdrUseContext::Dependent;
16665 
16666   return Result;
16667 }
16668 
16669 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16670   if (!Func->isConstexpr())
16671     return false;
16672 
16673   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
16674     return true;
16675   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
16676   return CCD && CCD->getInheritedConstructor();
16677 }
16678 
16679 /// Mark a function referenced, and check whether it is odr-used
16680 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16681 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16682                                   bool MightBeOdrUse) {
16683   assert(Func && "No function?");
16684 
16685   Func->setReferenced();
16686 
16687   // Recursive functions aren't really used until they're used from some other
16688   // context.
16689   bool IsRecursiveCall = CurContext == Func;
16690 
16691   // C++11 [basic.def.odr]p3:
16692   //   A function whose name appears as a potentially-evaluated expression is
16693   //   odr-used if it is the unique lookup result or the selected member of a
16694   //   set of overloaded functions [...].
16695   //
16696   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16697   // can just check that here.
16698   OdrUseContext OdrUse =
16699       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16700   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16701     OdrUse = OdrUseContext::FormallyOdrUsed;
16702 
16703   // Trivial default constructors and destructors are never actually used.
16704   // FIXME: What about other special members?
16705   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16706       OdrUse == OdrUseContext::Used) {
16707     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16708       if (Constructor->isDefaultConstructor())
16709         OdrUse = OdrUseContext::FormallyOdrUsed;
16710     if (isa<CXXDestructorDecl>(Func))
16711       OdrUse = OdrUseContext::FormallyOdrUsed;
16712   }
16713 
16714   // C++20 [expr.const]p12:
16715   //   A function [...] is needed for constant evaluation if it is [...] a
16716   //   constexpr function that is named by an expression that is potentially
16717   //   constant evaluated
16718   bool NeededForConstantEvaluation =
16719       isPotentiallyConstantEvaluatedContext(*this) &&
16720       isImplicitlyDefinableConstexprFunction(Func);
16721 
16722   // Determine whether we require a function definition to exist, per
16723   // C++11 [temp.inst]p3:
16724   //   Unless a function template specialization has been explicitly
16725   //   instantiated or explicitly specialized, the function template
16726   //   specialization is implicitly instantiated when the specialization is
16727   //   referenced in a context that requires a function definition to exist.
16728   // C++20 [temp.inst]p7:
16729   //   The existence of a definition of a [...] function is considered to
16730   //   affect the semantics of the program if the [...] function is needed for
16731   //   constant evaluation by an expression
16732   // C++20 [basic.def.odr]p10:
16733   //   Every program shall contain exactly one definition of every non-inline
16734   //   function or variable that is odr-used in that program outside of a
16735   //   discarded statement
16736   // C++20 [special]p1:
16737   //   The implementation will implicitly define [defaulted special members]
16738   //   if they are odr-used or needed for constant evaluation.
16739   //
16740   // Note that we skip the implicit instantiation of templates that are only
16741   // used in unused default arguments or by recursive calls to themselves.
16742   // This is formally non-conforming, but seems reasonable in practice.
16743   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16744                                              NeededForConstantEvaluation);
16745 
16746   // C++14 [temp.expl.spec]p6:
16747   //   If a template [...] is explicitly specialized then that specialization
16748   //   shall be declared before the first use of that specialization that would
16749   //   cause an implicit instantiation to take place, in every translation unit
16750   //   in which such a use occurs
16751   if (NeedDefinition &&
16752       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16753        Func->getMemberSpecializationInfo()))
16754     checkSpecializationVisibility(Loc, Func);
16755 
16756   if (getLangOpts().CUDA)
16757     CheckCUDACall(Loc, Func);
16758 
16759   if (getLangOpts().SYCLIsDevice)
16760     checkSYCLDeviceFunction(Loc, Func);
16761 
16762   // If we need a definition, try to create one.
16763   if (NeedDefinition && !Func->getBody()) {
16764     runWithSufficientStackSpace(Loc, [&] {
16765       if (CXXConstructorDecl *Constructor =
16766               dyn_cast<CXXConstructorDecl>(Func)) {
16767         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16768         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16769           if (Constructor->isDefaultConstructor()) {
16770             if (Constructor->isTrivial() &&
16771                 !Constructor->hasAttr<DLLExportAttr>())
16772               return;
16773             DefineImplicitDefaultConstructor(Loc, Constructor);
16774           } else if (Constructor->isCopyConstructor()) {
16775             DefineImplicitCopyConstructor(Loc, Constructor);
16776           } else if (Constructor->isMoveConstructor()) {
16777             DefineImplicitMoveConstructor(Loc, Constructor);
16778           }
16779         } else if (Constructor->getInheritedConstructor()) {
16780           DefineInheritingConstructor(Loc, Constructor);
16781         }
16782       } else if (CXXDestructorDecl *Destructor =
16783                      dyn_cast<CXXDestructorDecl>(Func)) {
16784         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16785         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16786           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16787             return;
16788           DefineImplicitDestructor(Loc, Destructor);
16789         }
16790         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16791           MarkVTableUsed(Loc, Destructor->getParent());
16792       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16793         if (MethodDecl->isOverloadedOperator() &&
16794             MethodDecl->getOverloadedOperator() == OO_Equal) {
16795           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16796           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16797             if (MethodDecl->isCopyAssignmentOperator())
16798               DefineImplicitCopyAssignment(Loc, MethodDecl);
16799             else if (MethodDecl->isMoveAssignmentOperator())
16800               DefineImplicitMoveAssignment(Loc, MethodDecl);
16801           }
16802         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16803                    MethodDecl->getParent()->isLambda()) {
16804           CXXConversionDecl *Conversion =
16805               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16806           if (Conversion->isLambdaToBlockPointerConversion())
16807             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16808           else
16809             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16810         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16811           MarkVTableUsed(Loc, MethodDecl->getParent());
16812       }
16813 
16814       if (Func->isDefaulted() && !Func->isDeleted()) {
16815         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16816         if (DCK != DefaultedComparisonKind::None)
16817           DefineDefaultedComparison(Loc, Func, DCK);
16818       }
16819 
16820       // Implicit instantiation of function templates and member functions of
16821       // class templates.
16822       if (Func->isImplicitlyInstantiable()) {
16823         TemplateSpecializationKind TSK =
16824             Func->getTemplateSpecializationKindForInstantiation();
16825         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16826         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16827         if (FirstInstantiation) {
16828           PointOfInstantiation = Loc;
16829           if (auto *MSI = Func->getMemberSpecializationInfo())
16830             MSI->setPointOfInstantiation(Loc);
16831             // FIXME: Notify listener.
16832           else
16833             Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16834         } else if (TSK != TSK_ImplicitInstantiation) {
16835           // Use the point of use as the point of instantiation, instead of the
16836           // point of explicit instantiation (which we track as the actual point
16837           // of instantiation). This gives better backtraces in diagnostics.
16838           PointOfInstantiation = Loc;
16839         }
16840 
16841         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16842             Func->isConstexpr()) {
16843           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16844               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16845               CodeSynthesisContexts.size())
16846             PendingLocalImplicitInstantiations.push_back(
16847                 std::make_pair(Func, PointOfInstantiation));
16848           else if (Func->isConstexpr())
16849             // Do not defer instantiations of constexpr functions, to avoid the
16850             // expression evaluator needing to call back into Sema if it sees a
16851             // call to such a function.
16852             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16853           else {
16854             Func->setInstantiationIsPending(true);
16855             PendingInstantiations.push_back(
16856                 std::make_pair(Func, PointOfInstantiation));
16857             // Notify the consumer that a function was implicitly instantiated.
16858             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16859           }
16860         }
16861       } else {
16862         // Walk redefinitions, as some of them may be instantiable.
16863         for (auto i : Func->redecls()) {
16864           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16865             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16866         }
16867       }
16868     });
16869   }
16870 
16871   // C++14 [except.spec]p17:
16872   //   An exception-specification is considered to be needed when:
16873   //   - the function is odr-used or, if it appears in an unevaluated operand,
16874   //     would be odr-used if the expression were potentially-evaluated;
16875   //
16876   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16877   // function is a pure virtual function we're calling, and in that case the
16878   // function was selected by overload resolution and we need to resolve its
16879   // exception specification for a different reason.
16880   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16881   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16882     ResolveExceptionSpec(Loc, FPT);
16883 
16884   // If this is the first "real" use, act on that.
16885   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16886     // Keep track of used but undefined functions.
16887     if (!Func->isDefined()) {
16888       if (mightHaveNonExternalLinkage(Func))
16889         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16890       else if (Func->getMostRecentDecl()->isInlined() &&
16891                !LangOpts.GNUInline &&
16892                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16893         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16894       else if (isExternalWithNoLinkageType(Func))
16895         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16896     }
16897 
16898     // Some x86 Windows calling conventions mangle the size of the parameter
16899     // pack into the name. Computing the size of the parameters requires the
16900     // parameter types to be complete. Check that now.
16901     if (funcHasParameterSizeMangling(*this, Func))
16902       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16903 
16904     // In the MS C++ ABI, the compiler emits destructor variants where they are
16905     // used. If the destructor is used here but defined elsewhere, mark the
16906     // virtual base destructors referenced. If those virtual base destructors
16907     // are inline, this will ensure they are defined when emitting the complete
16908     // destructor variant. This checking may be redundant if the destructor is
16909     // provided later in this TU.
16910     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16911       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16912         CXXRecordDecl *Parent = Dtor->getParent();
16913         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16914           CheckCompleteDestructorVariant(Loc, Dtor);
16915       }
16916     }
16917 
16918     Func->markUsed(Context);
16919   }
16920 }
16921 
16922 /// Directly mark a variable odr-used. Given a choice, prefer to use
16923 /// MarkVariableReferenced since it does additional checks and then
16924 /// calls MarkVarDeclODRUsed.
16925 /// If the variable must be captured:
16926 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16927 ///  - else capture it in the DeclContext that maps to the
16928 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16929 static void
16930 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16931                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16932   // Keep track of used but undefined variables.
16933   // FIXME: We shouldn't suppress this warning for static data members.
16934   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16935       (!Var->isExternallyVisible() || Var->isInline() ||
16936        SemaRef.isExternalWithNoLinkageType(Var)) &&
16937       !(Var->isStaticDataMember() && Var->hasInit())) {
16938     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16939     if (old.isInvalid())
16940       old = Loc;
16941   }
16942   QualType CaptureType, DeclRefType;
16943   if (SemaRef.LangOpts.OpenMP)
16944     SemaRef.tryCaptureOpenMPLambdas(Var);
16945   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16946     /*EllipsisLoc*/ SourceLocation(),
16947     /*BuildAndDiagnose*/ true,
16948     CaptureType, DeclRefType,
16949     FunctionScopeIndexToStopAt);
16950 
16951   Var->markUsed(SemaRef.Context);
16952 }
16953 
16954 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16955                                              SourceLocation Loc,
16956                                              unsigned CapturingScopeIndex) {
16957   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16958 }
16959 
16960 static void
16961 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16962                                    ValueDecl *var, DeclContext *DC) {
16963   DeclContext *VarDC = var->getDeclContext();
16964 
16965   //  If the parameter still belongs to the translation unit, then
16966   //  we're actually just using one parameter in the declaration of
16967   //  the next.
16968   if (isa<ParmVarDecl>(var) &&
16969       isa<TranslationUnitDecl>(VarDC))
16970     return;
16971 
16972   // For C code, don't diagnose about capture if we're not actually in code
16973   // right now; it's impossible to write a non-constant expression outside of
16974   // function context, so we'll get other (more useful) diagnostics later.
16975   //
16976   // For C++, things get a bit more nasty... it would be nice to suppress this
16977   // diagnostic for certain cases like using a local variable in an array bound
16978   // for a member of a local class, but the correct predicate is not obvious.
16979   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16980     return;
16981 
16982   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16983   unsigned ContextKind = 3; // unknown
16984   if (isa<CXXMethodDecl>(VarDC) &&
16985       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16986     ContextKind = 2;
16987   } else if (isa<FunctionDecl>(VarDC)) {
16988     ContextKind = 0;
16989   } else if (isa<BlockDecl>(VarDC)) {
16990     ContextKind = 1;
16991   }
16992 
16993   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16994     << var << ValueKind << ContextKind << VarDC;
16995   S.Diag(var->getLocation(), diag::note_entity_declared_at)
16996       << var;
16997 
16998   // FIXME: Add additional diagnostic info about class etc. which prevents
16999   // capture.
17000 }
17001 
17002 
17003 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17004                                       bool &SubCapturesAreNested,
17005                                       QualType &CaptureType,
17006                                       QualType &DeclRefType) {
17007    // Check whether we've already captured it.
17008   if (CSI->CaptureMap.count(Var)) {
17009     // If we found a capture, any subcaptures are nested.
17010     SubCapturesAreNested = true;
17011 
17012     // Retrieve the capture type for this variable.
17013     CaptureType = CSI->getCapture(Var).getCaptureType();
17014 
17015     // Compute the type of an expression that refers to this variable.
17016     DeclRefType = CaptureType.getNonReferenceType();
17017 
17018     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17019     // are mutable in the sense that user can change their value - they are
17020     // private instances of the captured declarations.
17021     const Capture &Cap = CSI->getCapture(Var);
17022     if (Cap.isCopyCapture() &&
17023         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17024         !(isa<CapturedRegionScopeInfo>(CSI) &&
17025           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17026       DeclRefType.addConst();
17027     return true;
17028   }
17029   return false;
17030 }
17031 
17032 // Only block literals, captured statements, and lambda expressions can
17033 // capture; other scopes don't work.
17034 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17035                                  SourceLocation Loc,
17036                                  const bool Diagnose, Sema &S) {
17037   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17038     return getLambdaAwareParentOfDeclContext(DC);
17039   else if (Var->hasLocalStorage()) {
17040     if (Diagnose)
17041        diagnoseUncapturableValueReference(S, Loc, Var, DC);
17042   }
17043   return nullptr;
17044 }
17045 
17046 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17047 // certain types of variables (unnamed, variably modified types etc.)
17048 // so check for eligibility.
17049 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17050                                  SourceLocation Loc,
17051                                  const bool Diagnose, Sema &S) {
17052 
17053   bool IsBlock = isa<BlockScopeInfo>(CSI);
17054   bool IsLambda = isa<LambdaScopeInfo>(CSI);
17055 
17056   // Lambdas are not allowed to capture unnamed variables
17057   // (e.g. anonymous unions).
17058   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17059   // assuming that's the intent.
17060   if (IsLambda && !Var->getDeclName()) {
17061     if (Diagnose) {
17062       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17063       S.Diag(Var->getLocation(), diag::note_declared_at);
17064     }
17065     return false;
17066   }
17067 
17068   // Prohibit variably-modified types in blocks; they're difficult to deal with.
17069   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17070     if (Diagnose) {
17071       S.Diag(Loc, diag::err_ref_vm_type);
17072       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17073     }
17074     return false;
17075   }
17076   // Prohibit structs with flexible array members too.
17077   // We cannot capture what is in the tail end of the struct.
17078   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17079     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17080       if (Diagnose) {
17081         if (IsBlock)
17082           S.Diag(Loc, diag::err_ref_flexarray_type);
17083         else
17084           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17085         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17086       }
17087       return false;
17088     }
17089   }
17090   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17091   // Lambdas and captured statements are not allowed to capture __block
17092   // variables; they don't support the expected semantics.
17093   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17094     if (Diagnose) {
17095       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17096       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17097     }
17098     return false;
17099   }
17100   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17101   if (S.getLangOpts().OpenCL && IsBlock &&
17102       Var->getType()->isBlockPointerType()) {
17103     if (Diagnose)
17104       S.Diag(Loc, diag::err_opencl_block_ref_block);
17105     return false;
17106   }
17107 
17108   return true;
17109 }
17110 
17111 // Returns true if the capture by block was successful.
17112 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17113                                  SourceLocation Loc,
17114                                  const bool BuildAndDiagnose,
17115                                  QualType &CaptureType,
17116                                  QualType &DeclRefType,
17117                                  const bool Nested,
17118                                  Sema &S, bool Invalid) {
17119   bool ByRef = false;
17120 
17121   // Blocks are not allowed to capture arrays, excepting OpenCL.
17122   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17123   // (decayed to pointers).
17124   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17125     if (BuildAndDiagnose) {
17126       S.Diag(Loc, diag::err_ref_array_type);
17127       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17128       Invalid = true;
17129     } else {
17130       return false;
17131     }
17132   }
17133 
17134   // Forbid the block-capture of autoreleasing variables.
17135   if (!Invalid &&
17136       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17137     if (BuildAndDiagnose) {
17138       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17139         << /*block*/ 0;
17140       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17141       Invalid = true;
17142     } else {
17143       return false;
17144     }
17145   }
17146 
17147   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17148   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17149     QualType PointeeTy = PT->getPointeeType();
17150 
17151     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17152         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17153         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17154       if (BuildAndDiagnose) {
17155         SourceLocation VarLoc = Var->getLocation();
17156         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17157         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17158       }
17159     }
17160   }
17161 
17162   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17163   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17164       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17165     // Block capture by reference does not change the capture or
17166     // declaration reference types.
17167     ByRef = true;
17168   } else {
17169     // Block capture by copy introduces 'const'.
17170     CaptureType = CaptureType.getNonReferenceType().withConst();
17171     DeclRefType = CaptureType;
17172   }
17173 
17174   // Actually capture the variable.
17175   if (BuildAndDiagnose)
17176     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17177                     CaptureType, Invalid);
17178 
17179   return !Invalid;
17180 }
17181 
17182 
17183 /// Capture the given variable in the captured region.
17184 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17185                                     VarDecl *Var,
17186                                     SourceLocation Loc,
17187                                     const bool BuildAndDiagnose,
17188                                     QualType &CaptureType,
17189                                     QualType &DeclRefType,
17190                                     const bool RefersToCapturedVariable,
17191                                     Sema &S, bool Invalid) {
17192   // By default, capture variables by reference.
17193   bool ByRef = true;
17194   // Using an LValue reference type is consistent with Lambdas (see below).
17195   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17196     if (S.isOpenMPCapturedDecl(Var)) {
17197       bool HasConst = DeclRefType.isConstQualified();
17198       DeclRefType = DeclRefType.getUnqualifiedType();
17199       // Don't lose diagnostics about assignments to const.
17200       if (HasConst)
17201         DeclRefType.addConst();
17202     }
17203     // Do not capture firstprivates in tasks.
17204     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17205         OMPC_unknown)
17206       return true;
17207     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17208                                     RSI->OpenMPCaptureLevel);
17209   }
17210 
17211   if (ByRef)
17212     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17213   else
17214     CaptureType = DeclRefType;
17215 
17216   // Actually capture the variable.
17217   if (BuildAndDiagnose)
17218     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17219                     Loc, SourceLocation(), CaptureType, Invalid);
17220 
17221   return !Invalid;
17222 }
17223 
17224 /// Capture the given variable in the lambda.
17225 static bool captureInLambda(LambdaScopeInfo *LSI,
17226                             VarDecl *Var,
17227                             SourceLocation Loc,
17228                             const bool BuildAndDiagnose,
17229                             QualType &CaptureType,
17230                             QualType &DeclRefType,
17231                             const bool RefersToCapturedVariable,
17232                             const Sema::TryCaptureKind Kind,
17233                             SourceLocation EllipsisLoc,
17234                             const bool IsTopScope,
17235                             Sema &S, bool Invalid) {
17236   // Determine whether we are capturing by reference or by value.
17237   bool ByRef = false;
17238   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17239     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17240   } else {
17241     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17242   }
17243 
17244   // Compute the type of the field that will capture this variable.
17245   if (ByRef) {
17246     // C++11 [expr.prim.lambda]p15:
17247     //   An entity is captured by reference if it is implicitly or
17248     //   explicitly captured but not captured by copy. It is
17249     //   unspecified whether additional unnamed non-static data
17250     //   members are declared in the closure type for entities
17251     //   captured by reference.
17252     //
17253     // FIXME: It is not clear whether we want to build an lvalue reference
17254     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17255     // to do the former, while EDG does the latter. Core issue 1249 will
17256     // clarify, but for now we follow GCC because it's a more permissive and
17257     // easily defensible position.
17258     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17259   } else {
17260     // C++11 [expr.prim.lambda]p14:
17261     //   For each entity captured by copy, an unnamed non-static
17262     //   data member is declared in the closure type. The
17263     //   declaration order of these members is unspecified. The type
17264     //   of such a data member is the type of the corresponding
17265     //   captured entity if the entity is not a reference to an
17266     //   object, or the referenced type otherwise. [Note: If the
17267     //   captured entity is a reference to a function, the
17268     //   corresponding data member is also a reference to a
17269     //   function. - end note ]
17270     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17271       if (!RefType->getPointeeType()->isFunctionType())
17272         CaptureType = RefType->getPointeeType();
17273     }
17274 
17275     // Forbid the lambda copy-capture of autoreleasing variables.
17276     if (!Invalid &&
17277         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17278       if (BuildAndDiagnose) {
17279         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17280         S.Diag(Var->getLocation(), diag::note_previous_decl)
17281           << Var->getDeclName();
17282         Invalid = true;
17283       } else {
17284         return false;
17285       }
17286     }
17287 
17288     // Make sure that by-copy captures are of a complete and non-abstract type.
17289     if (!Invalid && BuildAndDiagnose) {
17290       if (!CaptureType->isDependentType() &&
17291           S.RequireCompleteSizedType(
17292               Loc, CaptureType,
17293               diag::err_capture_of_incomplete_or_sizeless_type,
17294               Var->getDeclName()))
17295         Invalid = true;
17296       else if (S.RequireNonAbstractType(Loc, CaptureType,
17297                                         diag::err_capture_of_abstract_type))
17298         Invalid = true;
17299     }
17300   }
17301 
17302   // Compute the type of a reference to this captured variable.
17303   if (ByRef)
17304     DeclRefType = CaptureType.getNonReferenceType();
17305   else {
17306     // C++ [expr.prim.lambda]p5:
17307     //   The closure type for a lambda-expression has a public inline
17308     //   function call operator [...]. This function call operator is
17309     //   declared const (9.3.1) if and only if the lambda-expression's
17310     //   parameter-declaration-clause is not followed by mutable.
17311     DeclRefType = CaptureType.getNonReferenceType();
17312     if (!LSI->Mutable && !CaptureType->isReferenceType())
17313       DeclRefType.addConst();
17314   }
17315 
17316   // Add the capture.
17317   if (BuildAndDiagnose)
17318     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17319                     Loc, EllipsisLoc, CaptureType, Invalid);
17320 
17321   return !Invalid;
17322 }
17323 
17324 bool Sema::tryCaptureVariable(
17325     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17326     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17327     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17328   // An init-capture is notionally from the context surrounding its
17329   // declaration, but its parent DC is the lambda class.
17330   DeclContext *VarDC = Var->getDeclContext();
17331   if (Var->isInitCapture())
17332     VarDC = VarDC->getParent();
17333 
17334   DeclContext *DC = CurContext;
17335   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17336       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17337   // We need to sync up the Declaration Context with the
17338   // FunctionScopeIndexToStopAt
17339   if (FunctionScopeIndexToStopAt) {
17340     unsigned FSIndex = FunctionScopes.size() - 1;
17341     while (FSIndex != MaxFunctionScopesIndex) {
17342       DC = getLambdaAwareParentOfDeclContext(DC);
17343       --FSIndex;
17344     }
17345   }
17346 
17347 
17348   // If the variable is declared in the current context, there is no need to
17349   // capture it.
17350   if (VarDC == DC) return true;
17351 
17352   // Capture global variables if it is required to use private copy of this
17353   // variable.
17354   bool IsGlobal = !Var->hasLocalStorage();
17355   if (IsGlobal &&
17356       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17357                                                 MaxFunctionScopesIndex)))
17358     return true;
17359   Var = Var->getCanonicalDecl();
17360 
17361   // Walk up the stack to determine whether we can capture the variable,
17362   // performing the "simple" checks that don't depend on type. We stop when
17363   // we've either hit the declared scope of the variable or find an existing
17364   // capture of that variable.  We start from the innermost capturing-entity
17365   // (the DC) and ensure that all intervening capturing-entities
17366   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17367   // declcontext can either capture the variable or have already captured
17368   // the variable.
17369   CaptureType = Var->getType();
17370   DeclRefType = CaptureType.getNonReferenceType();
17371   bool Nested = false;
17372   bool Explicit = (Kind != TryCapture_Implicit);
17373   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17374   do {
17375     // Only block literals, captured statements, and lambda expressions can
17376     // capture; other scopes don't work.
17377     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17378                                                               ExprLoc,
17379                                                               BuildAndDiagnose,
17380                                                               *this);
17381     // We need to check for the parent *first* because, if we *have*
17382     // private-captured a global variable, we need to recursively capture it in
17383     // intermediate blocks, lambdas, etc.
17384     if (!ParentDC) {
17385       if (IsGlobal) {
17386         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17387         break;
17388       }
17389       return true;
17390     }
17391 
17392     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17393     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17394 
17395 
17396     // Check whether we've already captured it.
17397     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17398                                              DeclRefType)) {
17399       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17400       break;
17401     }
17402     // If we are instantiating a generic lambda call operator body,
17403     // we do not want to capture new variables.  What was captured
17404     // during either a lambdas transformation or initial parsing
17405     // should be used.
17406     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17407       if (BuildAndDiagnose) {
17408         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17409         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17410           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17411           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17412           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17413         } else
17414           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17415       }
17416       return true;
17417     }
17418 
17419     // Try to capture variable-length arrays types.
17420     if (Var->getType()->isVariablyModifiedType()) {
17421       // We're going to walk down into the type and look for VLA
17422       // expressions.
17423       QualType QTy = Var->getType();
17424       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17425         QTy = PVD->getOriginalType();
17426       captureVariablyModifiedType(Context, QTy, CSI);
17427     }
17428 
17429     if (getLangOpts().OpenMP) {
17430       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17431         // OpenMP private variables should not be captured in outer scope, so
17432         // just break here. Similarly, global variables that are captured in a
17433         // target region should not be captured outside the scope of the region.
17434         if (RSI->CapRegionKind == CR_OpenMP) {
17435           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17436               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17437           // If the variable is private (i.e. not captured) and has variably
17438           // modified type, we still need to capture the type for correct
17439           // codegen in all regions, associated with the construct. Currently,
17440           // it is captured in the innermost captured region only.
17441           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17442               Var->getType()->isVariablyModifiedType()) {
17443             QualType QTy = Var->getType();
17444             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17445               QTy = PVD->getOriginalType();
17446             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17447                  I < E; ++I) {
17448               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17449                   FunctionScopes[FunctionScopesIndex - I]);
17450               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17451                      "Wrong number of captured regions associated with the "
17452                      "OpenMP construct.");
17453               captureVariablyModifiedType(Context, QTy, OuterRSI);
17454             }
17455           }
17456           bool IsTargetCap =
17457               IsOpenMPPrivateDecl != OMPC_private &&
17458               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17459                                          RSI->OpenMPCaptureLevel);
17460           // Do not capture global if it is not privatized in outer regions.
17461           bool IsGlobalCap =
17462               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17463                                                      RSI->OpenMPCaptureLevel);
17464 
17465           // When we detect target captures we are looking from inside the
17466           // target region, therefore we need to propagate the capture from the
17467           // enclosing region. Therefore, the capture is not initially nested.
17468           if (IsTargetCap)
17469             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17470 
17471           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17472               (IsGlobal && !IsGlobalCap)) {
17473             Nested = !IsTargetCap;
17474             bool HasConst = DeclRefType.isConstQualified();
17475             DeclRefType = DeclRefType.getUnqualifiedType();
17476             // Don't lose diagnostics about assignments to const.
17477             if (HasConst)
17478               DeclRefType.addConst();
17479             CaptureType = Context.getLValueReferenceType(DeclRefType);
17480             break;
17481           }
17482         }
17483       }
17484     }
17485     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17486       // No capture-default, and this is not an explicit capture
17487       // so cannot capture this variable.
17488       if (BuildAndDiagnose) {
17489         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17490         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17491         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17492           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17493                diag::note_lambda_decl);
17494         // FIXME: If we error out because an outer lambda can not implicitly
17495         // capture a variable that an inner lambda explicitly captures, we
17496         // should have the inner lambda do the explicit capture - because
17497         // it makes for cleaner diagnostics later.  This would purely be done
17498         // so that the diagnostic does not misleadingly claim that a variable
17499         // can not be captured by a lambda implicitly even though it is captured
17500         // explicitly.  Suggestion:
17501         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17502         //    at the function head
17503         //  - cache the StartingDeclContext - this must be a lambda
17504         //  - captureInLambda in the innermost lambda the variable.
17505       }
17506       return true;
17507     }
17508 
17509     FunctionScopesIndex--;
17510     DC = ParentDC;
17511     Explicit = false;
17512   } while (!VarDC->Equals(DC));
17513 
17514   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17515   // computing the type of the capture at each step, checking type-specific
17516   // requirements, and adding captures if requested.
17517   // If the variable had already been captured previously, we start capturing
17518   // at the lambda nested within that one.
17519   bool Invalid = false;
17520   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17521        ++I) {
17522     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17523 
17524     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17525     // certain types of variables (unnamed, variably modified types etc.)
17526     // so check for eligibility.
17527     if (!Invalid)
17528       Invalid =
17529           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17530 
17531     // After encountering an error, if we're actually supposed to capture, keep
17532     // capturing in nested contexts to suppress any follow-on diagnostics.
17533     if (Invalid && !BuildAndDiagnose)
17534       return true;
17535 
17536     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17537       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17538                                DeclRefType, Nested, *this, Invalid);
17539       Nested = true;
17540     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17541       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17542                                          CaptureType, DeclRefType, Nested,
17543                                          *this, Invalid);
17544       Nested = true;
17545     } else {
17546       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17547       Invalid =
17548           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17549                            DeclRefType, Nested, Kind, EllipsisLoc,
17550                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17551       Nested = true;
17552     }
17553 
17554     if (Invalid && !BuildAndDiagnose)
17555       return true;
17556   }
17557   return Invalid;
17558 }
17559 
17560 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17561                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17562   QualType CaptureType;
17563   QualType DeclRefType;
17564   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17565                             /*BuildAndDiagnose=*/true, CaptureType,
17566                             DeclRefType, nullptr);
17567 }
17568 
17569 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17570   QualType CaptureType;
17571   QualType DeclRefType;
17572   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17573                              /*BuildAndDiagnose=*/false, CaptureType,
17574                              DeclRefType, nullptr);
17575 }
17576 
17577 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17578   QualType CaptureType;
17579   QualType DeclRefType;
17580 
17581   // Determine whether we can capture this variable.
17582   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17583                          /*BuildAndDiagnose=*/false, CaptureType,
17584                          DeclRefType, nullptr))
17585     return QualType();
17586 
17587   return DeclRefType;
17588 }
17589 
17590 namespace {
17591 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17592 // The produced TemplateArgumentListInfo* points to data stored within this
17593 // object, so should only be used in contexts where the pointer will not be
17594 // used after the CopiedTemplateArgs object is destroyed.
17595 class CopiedTemplateArgs {
17596   bool HasArgs;
17597   TemplateArgumentListInfo TemplateArgStorage;
17598 public:
17599   template<typename RefExpr>
17600   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17601     if (HasArgs)
17602       E->copyTemplateArgumentsInto(TemplateArgStorage);
17603   }
17604   operator TemplateArgumentListInfo*()
17605 #ifdef __has_cpp_attribute
17606 #if __has_cpp_attribute(clang::lifetimebound)
17607   [[clang::lifetimebound]]
17608 #endif
17609 #endif
17610   {
17611     return HasArgs ? &TemplateArgStorage : nullptr;
17612   }
17613 };
17614 }
17615 
17616 /// Walk the set of potential results of an expression and mark them all as
17617 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17618 ///
17619 /// \return A new expression if we found any potential results, ExprEmpty() if
17620 ///         not, and ExprError() if we diagnosed an error.
17621 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17622                                                       NonOdrUseReason NOUR) {
17623   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17624   // an object that satisfies the requirements for appearing in a
17625   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17626   // is immediately applied."  This function handles the lvalue-to-rvalue
17627   // conversion part.
17628   //
17629   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17630   // transform it into the relevant kind of non-odr-use node and rebuild the
17631   // tree of nodes leading to it.
17632   //
17633   // This is a mini-TreeTransform that only transforms a restricted subset of
17634   // nodes (and only certain operands of them).
17635 
17636   // Rebuild a subexpression.
17637   auto Rebuild = [&](Expr *Sub) {
17638     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17639   };
17640 
17641   // Check whether a potential result satisfies the requirements of NOUR.
17642   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17643     // Any entity other than a VarDecl is always odr-used whenever it's named
17644     // in a potentially-evaluated expression.
17645     auto *VD = dyn_cast<VarDecl>(D);
17646     if (!VD)
17647       return true;
17648 
17649     // C++2a [basic.def.odr]p4:
17650     //   A variable x whose name appears as a potentially-evalauted expression
17651     //   e is odr-used by e unless
17652     //   -- x is a reference that is usable in constant expressions, or
17653     //   -- x is a variable of non-reference type that is usable in constant
17654     //      expressions and has no mutable subobjects, and e is an element of
17655     //      the set of potential results of an expression of
17656     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17657     //      conversion is applied, or
17658     //   -- x is a variable of non-reference type, and e is an element of the
17659     //      set of potential results of a discarded-value expression to which
17660     //      the lvalue-to-rvalue conversion is not applied
17661     //
17662     // We check the first bullet and the "potentially-evaluated" condition in
17663     // BuildDeclRefExpr. We check the type requirements in the second bullet
17664     // in CheckLValueToRValueConversionOperand below.
17665     switch (NOUR) {
17666     case NOUR_None:
17667     case NOUR_Unevaluated:
17668       llvm_unreachable("unexpected non-odr-use-reason");
17669 
17670     case NOUR_Constant:
17671       // Constant references were handled when they were built.
17672       if (VD->getType()->isReferenceType())
17673         return true;
17674       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17675         if (RD->hasMutableFields())
17676           return true;
17677       if (!VD->isUsableInConstantExpressions(S.Context))
17678         return true;
17679       break;
17680 
17681     case NOUR_Discarded:
17682       if (VD->getType()->isReferenceType())
17683         return true;
17684       break;
17685     }
17686     return false;
17687   };
17688 
17689   // Mark that this expression does not constitute an odr-use.
17690   auto MarkNotOdrUsed = [&] {
17691     S.MaybeODRUseExprs.remove(E);
17692     if (LambdaScopeInfo *LSI = S.getCurLambda())
17693       LSI->markVariableExprAsNonODRUsed(E);
17694   };
17695 
17696   // C++2a [basic.def.odr]p2:
17697   //   The set of potential results of an expression e is defined as follows:
17698   switch (E->getStmtClass()) {
17699   //   -- If e is an id-expression, ...
17700   case Expr::DeclRefExprClass: {
17701     auto *DRE = cast<DeclRefExpr>(E);
17702     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17703       break;
17704 
17705     // Rebuild as a non-odr-use DeclRefExpr.
17706     MarkNotOdrUsed();
17707     return DeclRefExpr::Create(
17708         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17709         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17710         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17711         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17712   }
17713 
17714   case Expr::FunctionParmPackExprClass: {
17715     auto *FPPE = cast<FunctionParmPackExpr>(E);
17716     // If any of the declarations in the pack is odr-used, then the expression
17717     // as a whole constitutes an odr-use.
17718     for (VarDecl *D : *FPPE)
17719       if (IsPotentialResultOdrUsed(D))
17720         return ExprEmpty();
17721 
17722     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17723     // nothing cares about whether we marked this as an odr-use, but it might
17724     // be useful for non-compiler tools.
17725     MarkNotOdrUsed();
17726     break;
17727   }
17728 
17729   //   -- If e is a subscripting operation with an array operand...
17730   case Expr::ArraySubscriptExprClass: {
17731     auto *ASE = cast<ArraySubscriptExpr>(E);
17732     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17733     if (!OldBase->getType()->isArrayType())
17734       break;
17735     ExprResult Base = Rebuild(OldBase);
17736     if (!Base.isUsable())
17737       return Base;
17738     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17739     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17740     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17741     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17742                                      ASE->getRBracketLoc());
17743   }
17744 
17745   case Expr::MemberExprClass: {
17746     auto *ME = cast<MemberExpr>(E);
17747     // -- If e is a class member access expression [...] naming a non-static
17748     //    data member...
17749     if (isa<FieldDecl>(ME->getMemberDecl())) {
17750       ExprResult Base = Rebuild(ME->getBase());
17751       if (!Base.isUsable())
17752         return Base;
17753       return MemberExpr::Create(
17754           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17755           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17756           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17757           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17758           ME->getObjectKind(), ME->isNonOdrUse());
17759     }
17760 
17761     if (ME->getMemberDecl()->isCXXInstanceMember())
17762       break;
17763 
17764     // -- If e is a class member access expression naming a static data member,
17765     //    ...
17766     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17767       break;
17768 
17769     // Rebuild as a non-odr-use MemberExpr.
17770     MarkNotOdrUsed();
17771     return MemberExpr::Create(
17772         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17773         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17774         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17775         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17776     return ExprEmpty();
17777   }
17778 
17779   case Expr::BinaryOperatorClass: {
17780     auto *BO = cast<BinaryOperator>(E);
17781     Expr *LHS = BO->getLHS();
17782     Expr *RHS = BO->getRHS();
17783     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17784     if (BO->getOpcode() == BO_PtrMemD) {
17785       ExprResult Sub = Rebuild(LHS);
17786       if (!Sub.isUsable())
17787         return Sub;
17788       LHS = Sub.get();
17789     //   -- If e is a comma expression, ...
17790     } else if (BO->getOpcode() == BO_Comma) {
17791       ExprResult Sub = Rebuild(RHS);
17792       if (!Sub.isUsable())
17793         return Sub;
17794       RHS = Sub.get();
17795     } else {
17796       break;
17797     }
17798     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17799                         LHS, RHS);
17800   }
17801 
17802   //   -- If e has the form (e1)...
17803   case Expr::ParenExprClass: {
17804     auto *PE = cast<ParenExpr>(E);
17805     ExprResult Sub = Rebuild(PE->getSubExpr());
17806     if (!Sub.isUsable())
17807       return Sub;
17808     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17809   }
17810 
17811   //   -- If e is a glvalue conditional expression, ...
17812   // We don't apply this to a binary conditional operator. FIXME: Should we?
17813   case Expr::ConditionalOperatorClass: {
17814     auto *CO = cast<ConditionalOperator>(E);
17815     ExprResult LHS = Rebuild(CO->getLHS());
17816     if (LHS.isInvalid())
17817       return ExprError();
17818     ExprResult RHS = Rebuild(CO->getRHS());
17819     if (RHS.isInvalid())
17820       return ExprError();
17821     if (!LHS.isUsable() && !RHS.isUsable())
17822       return ExprEmpty();
17823     if (!LHS.isUsable())
17824       LHS = CO->getLHS();
17825     if (!RHS.isUsable())
17826       RHS = CO->getRHS();
17827     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17828                                 CO->getCond(), LHS.get(), RHS.get());
17829   }
17830 
17831   // [Clang extension]
17832   //   -- If e has the form __extension__ e1...
17833   case Expr::UnaryOperatorClass: {
17834     auto *UO = cast<UnaryOperator>(E);
17835     if (UO->getOpcode() != UO_Extension)
17836       break;
17837     ExprResult Sub = Rebuild(UO->getSubExpr());
17838     if (!Sub.isUsable())
17839       return Sub;
17840     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17841                           Sub.get());
17842   }
17843 
17844   // [Clang extension]
17845   //   -- If e has the form _Generic(...), the set of potential results is the
17846   //      union of the sets of potential results of the associated expressions.
17847   case Expr::GenericSelectionExprClass: {
17848     auto *GSE = cast<GenericSelectionExpr>(E);
17849 
17850     SmallVector<Expr *, 4> AssocExprs;
17851     bool AnyChanged = false;
17852     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17853       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17854       if (AssocExpr.isInvalid())
17855         return ExprError();
17856       if (AssocExpr.isUsable()) {
17857         AssocExprs.push_back(AssocExpr.get());
17858         AnyChanged = true;
17859       } else {
17860         AssocExprs.push_back(OrigAssocExpr);
17861       }
17862     }
17863 
17864     return AnyChanged ? S.CreateGenericSelectionExpr(
17865                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17866                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17867                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17868                       : ExprEmpty();
17869   }
17870 
17871   // [Clang extension]
17872   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17873   //      results is the union of the sets of potential results of the
17874   //      second and third subexpressions.
17875   case Expr::ChooseExprClass: {
17876     auto *CE = cast<ChooseExpr>(E);
17877 
17878     ExprResult LHS = Rebuild(CE->getLHS());
17879     if (LHS.isInvalid())
17880       return ExprError();
17881 
17882     ExprResult RHS = Rebuild(CE->getLHS());
17883     if (RHS.isInvalid())
17884       return ExprError();
17885 
17886     if (!LHS.get() && !RHS.get())
17887       return ExprEmpty();
17888     if (!LHS.isUsable())
17889       LHS = CE->getLHS();
17890     if (!RHS.isUsable())
17891       RHS = CE->getRHS();
17892 
17893     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17894                              RHS.get(), CE->getRParenLoc());
17895   }
17896 
17897   // Step through non-syntactic nodes.
17898   case Expr::ConstantExprClass: {
17899     auto *CE = cast<ConstantExpr>(E);
17900     ExprResult Sub = Rebuild(CE->getSubExpr());
17901     if (!Sub.isUsable())
17902       return Sub;
17903     return ConstantExpr::Create(S.Context, Sub.get());
17904   }
17905 
17906   // We could mostly rely on the recursive rebuilding to rebuild implicit
17907   // casts, but not at the top level, so rebuild them here.
17908   case Expr::ImplicitCastExprClass: {
17909     auto *ICE = cast<ImplicitCastExpr>(E);
17910     // Only step through the narrow set of cast kinds we expect to encounter.
17911     // Anything else suggests we've left the region in which potential results
17912     // can be found.
17913     switch (ICE->getCastKind()) {
17914     case CK_NoOp:
17915     case CK_DerivedToBase:
17916     case CK_UncheckedDerivedToBase: {
17917       ExprResult Sub = Rebuild(ICE->getSubExpr());
17918       if (!Sub.isUsable())
17919         return Sub;
17920       CXXCastPath Path(ICE->path());
17921       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17922                                  ICE->getValueKind(), &Path);
17923     }
17924 
17925     default:
17926       break;
17927     }
17928     break;
17929   }
17930 
17931   default:
17932     break;
17933   }
17934 
17935   // Can't traverse through this node. Nothing to do.
17936   return ExprEmpty();
17937 }
17938 
17939 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17940   // Check whether the operand is or contains an object of non-trivial C union
17941   // type.
17942   if (E->getType().isVolatileQualified() &&
17943       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17944        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17945     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17946                           Sema::NTCUC_LValueToRValueVolatile,
17947                           NTCUK_Destruct|NTCUK_Copy);
17948 
17949   // C++2a [basic.def.odr]p4:
17950   //   [...] an expression of non-volatile-qualified non-class type to which
17951   //   the lvalue-to-rvalue conversion is applied [...]
17952   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17953     return E;
17954 
17955   ExprResult Result =
17956       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17957   if (Result.isInvalid())
17958     return ExprError();
17959   return Result.get() ? Result : E;
17960 }
17961 
17962 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17963   Res = CorrectDelayedTyposInExpr(Res);
17964 
17965   if (!Res.isUsable())
17966     return Res;
17967 
17968   // If a constant-expression is a reference to a variable where we delay
17969   // deciding whether it is an odr-use, just assume we will apply the
17970   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
17971   // (a non-type template argument), we have special handling anyway.
17972   return CheckLValueToRValueConversionOperand(Res.get());
17973 }
17974 
17975 void Sema::CleanupVarDeclMarking() {
17976   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17977   // call.
17978   MaybeODRUseExprSet LocalMaybeODRUseExprs;
17979   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17980 
17981   for (Expr *E : LocalMaybeODRUseExprs) {
17982     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17983       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17984                          DRE->getLocation(), *this);
17985     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17986       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17987                          *this);
17988     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17989       for (VarDecl *VD : *FP)
17990         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17991     } else {
17992       llvm_unreachable("Unexpected expression");
17993     }
17994   }
17995 
17996   assert(MaybeODRUseExprs.empty() &&
17997          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17998 }
17999 
18000 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
18001                                     VarDecl *Var, Expr *E) {
18002   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
18003           isa<FunctionParmPackExpr>(E)) &&
18004          "Invalid Expr argument to DoMarkVarDeclReferenced");
18005   Var->setReferenced();
18006 
18007   if (Var->isInvalidDecl())
18008     return;
18009 
18010   // Record a CUDA/HIP static device/constant variable if it is referenced
18011   // by host code. This is done conservatively, when the variable is referenced
18012   // in any of the following contexts:
18013   //   - a non-function context
18014   //   - a host function
18015   //   - a host device function
18016   // This also requires the reference of the static device/constant variable by
18017   // host code to be visible in the device compilation for the compiler to be
18018   // able to externalize the static device/constant variable.
18019   if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) {
18020     auto *CurContext = SemaRef.CurContext;
18021     if (!CurContext || !isa<FunctionDecl>(CurContext) ||
18022         cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() ||
18023         (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() &&
18024          !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>()))
18025       SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var);
18026   }
18027 
18028   auto *MSI = Var->getMemberSpecializationInfo();
18029   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18030                                        : Var->getTemplateSpecializationKind();
18031 
18032   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18033   bool UsableInConstantExpr =
18034       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18035 
18036   // C++20 [expr.const]p12:
18037   //   A variable [...] is needed for constant evaluation if it is [...] a
18038   //   variable whose name appears as a potentially constant evaluated
18039   //   expression that is either a contexpr variable or is of non-volatile
18040   //   const-qualified integral type or of reference type
18041   bool NeededForConstantEvaluation =
18042       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18043 
18044   bool NeedDefinition =
18045       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18046 
18047   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
18048          "Can't instantiate a partial template specialization.");
18049 
18050   // If this might be a member specialization of a static data member, check
18051   // the specialization is visible. We already did the checks for variable
18052   // template specializations when we created them.
18053   if (NeedDefinition && TSK != TSK_Undeclared &&
18054       !isa<VarTemplateSpecializationDecl>(Var))
18055     SemaRef.checkSpecializationVisibility(Loc, Var);
18056 
18057   // Perform implicit instantiation of static data members, static data member
18058   // templates of class templates, and variable template specializations. Delay
18059   // instantiations of variable templates, except for those that could be used
18060   // in a constant expression.
18061   if (NeedDefinition && isTemplateInstantiation(TSK)) {
18062     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18063     // instantiation declaration if a variable is usable in a constant
18064     // expression (among other cases).
18065     bool TryInstantiating =
18066         TSK == TSK_ImplicitInstantiation ||
18067         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18068 
18069     if (TryInstantiating) {
18070       SourceLocation PointOfInstantiation =
18071           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18072       bool FirstInstantiation = PointOfInstantiation.isInvalid();
18073       if (FirstInstantiation) {
18074         PointOfInstantiation = Loc;
18075         if (MSI)
18076           MSI->setPointOfInstantiation(PointOfInstantiation);
18077           // FIXME: Notify listener.
18078         else
18079           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18080       }
18081 
18082       if (UsableInConstantExpr) {
18083         // Do not defer instantiations of variables that could be used in a
18084         // constant expression.
18085         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18086           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18087         });
18088       } else if (FirstInstantiation ||
18089                  isa<VarTemplateSpecializationDecl>(Var)) {
18090         // FIXME: For a specialization of a variable template, we don't
18091         // distinguish between "declaration and type implicitly instantiated"
18092         // and "implicit instantiation of definition requested", so we have
18093         // no direct way to avoid enqueueing the pending instantiation
18094         // multiple times.
18095         SemaRef.PendingInstantiations
18096             .push_back(std::make_pair(Var, PointOfInstantiation));
18097       }
18098     }
18099   }
18100 
18101   // C++2a [basic.def.odr]p4:
18102   //   A variable x whose name appears as a potentially-evaluated expression e
18103   //   is odr-used by e unless
18104   //   -- x is a reference that is usable in constant expressions
18105   //   -- x is a variable of non-reference type that is usable in constant
18106   //      expressions and has no mutable subobjects [FIXME], and e is an
18107   //      element of the set of potential results of an expression of
18108   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18109   //      conversion is applied
18110   //   -- x is a variable of non-reference type, and e is an element of the set
18111   //      of potential results of a discarded-value expression to which the
18112   //      lvalue-to-rvalue conversion is not applied [FIXME]
18113   //
18114   // We check the first part of the second bullet here, and
18115   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18116   // FIXME: To get the third bullet right, we need to delay this even for
18117   // variables that are not usable in constant expressions.
18118 
18119   // If we already know this isn't an odr-use, there's nothing more to do.
18120   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18121     if (DRE->isNonOdrUse())
18122       return;
18123   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18124     if (ME->isNonOdrUse())
18125       return;
18126 
18127   switch (OdrUse) {
18128   case OdrUseContext::None:
18129     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18130            "missing non-odr-use marking for unevaluated decl ref");
18131     break;
18132 
18133   case OdrUseContext::FormallyOdrUsed:
18134     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18135     // behavior.
18136     break;
18137 
18138   case OdrUseContext::Used:
18139     // If we might later find that this expression isn't actually an odr-use,
18140     // delay the marking.
18141     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18142       SemaRef.MaybeODRUseExprs.insert(E);
18143     else
18144       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18145     break;
18146 
18147   case OdrUseContext::Dependent:
18148     // If this is a dependent context, we don't need to mark variables as
18149     // odr-used, but we may still need to track them for lambda capture.
18150     // FIXME: Do we also need to do this inside dependent typeid expressions
18151     // (which are modeled as unevaluated at this point)?
18152     const bool RefersToEnclosingScope =
18153         (SemaRef.CurContext != Var->getDeclContext() &&
18154          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18155     if (RefersToEnclosingScope) {
18156       LambdaScopeInfo *const LSI =
18157           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18158       if (LSI && (!LSI->CallOperator ||
18159                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18160         // If a variable could potentially be odr-used, defer marking it so
18161         // until we finish analyzing the full expression for any
18162         // lvalue-to-rvalue
18163         // or discarded value conversions that would obviate odr-use.
18164         // Add it to the list of potential captures that will be analyzed
18165         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18166         // unless the variable is a reference that was initialized by a constant
18167         // expression (this will never need to be captured or odr-used).
18168         //
18169         // FIXME: We can simplify this a lot after implementing P0588R1.
18170         assert(E && "Capture variable should be used in an expression.");
18171         if (!Var->getType()->isReferenceType() ||
18172             !Var->isUsableInConstantExpressions(SemaRef.Context))
18173           LSI->addPotentialCapture(E->IgnoreParens());
18174       }
18175     }
18176     break;
18177   }
18178 }
18179 
18180 /// Mark a variable referenced, and check whether it is odr-used
18181 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18182 /// used directly for normal expressions referring to VarDecl.
18183 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18184   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18185 }
18186 
18187 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18188                                Decl *D, Expr *E, bool MightBeOdrUse) {
18189   if (SemaRef.isInOpenMPDeclareTargetContext())
18190     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18191 
18192   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18193     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18194     return;
18195   }
18196 
18197   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18198 
18199   // If this is a call to a method via a cast, also mark the method in the
18200   // derived class used in case codegen can devirtualize the call.
18201   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18202   if (!ME)
18203     return;
18204   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18205   if (!MD)
18206     return;
18207   // Only attempt to devirtualize if this is truly a virtual call.
18208   bool IsVirtualCall = MD->isVirtual() &&
18209                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18210   if (!IsVirtualCall)
18211     return;
18212 
18213   // If it's possible to devirtualize the call, mark the called function
18214   // referenced.
18215   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18216       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18217   if (DM)
18218     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18219 }
18220 
18221 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18222 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18223   // TODO: update this with DR# once a defect report is filed.
18224   // C++11 defect. The address of a pure member should not be an ODR use, even
18225   // if it's a qualified reference.
18226   bool OdrUse = true;
18227   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18228     if (Method->isVirtual() &&
18229         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18230       OdrUse = false;
18231 
18232   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18233     if (!isConstantEvaluated() && FD->isConsteval() &&
18234         !RebuildingImmediateInvocation)
18235       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18236   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18237 }
18238 
18239 /// Perform reference-marking and odr-use handling for a MemberExpr.
18240 void Sema::MarkMemberReferenced(MemberExpr *E) {
18241   // C++11 [basic.def.odr]p2:
18242   //   A non-overloaded function whose name appears as a potentially-evaluated
18243   //   expression or a member of a set of candidate functions, if selected by
18244   //   overload resolution when referred to from a potentially-evaluated
18245   //   expression, is odr-used, unless it is a pure virtual function and its
18246   //   name is not explicitly qualified.
18247   bool MightBeOdrUse = true;
18248   if (E->performsVirtualDispatch(getLangOpts())) {
18249     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18250       if (Method->isPure())
18251         MightBeOdrUse = false;
18252   }
18253   SourceLocation Loc =
18254       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18255   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18256 }
18257 
18258 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18259 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18260   for (VarDecl *VD : *E)
18261     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18262 }
18263 
18264 /// Perform marking for a reference to an arbitrary declaration.  It
18265 /// marks the declaration referenced, and performs odr-use checking for
18266 /// functions and variables. This method should not be used when building a
18267 /// normal expression which refers to a variable.
18268 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18269                                  bool MightBeOdrUse) {
18270   if (MightBeOdrUse) {
18271     if (auto *VD = dyn_cast<VarDecl>(D)) {
18272       MarkVariableReferenced(Loc, VD);
18273       return;
18274     }
18275   }
18276   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18277     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18278     return;
18279   }
18280   D->setReferenced();
18281 }
18282 
18283 namespace {
18284   // Mark all of the declarations used by a type as referenced.
18285   // FIXME: Not fully implemented yet! We need to have a better understanding
18286   // of when we're entering a context we should not recurse into.
18287   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18288   // TreeTransforms rebuilding the type in a new context. Rather than
18289   // duplicating the TreeTransform logic, we should consider reusing it here.
18290   // Currently that causes problems when rebuilding LambdaExprs.
18291   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18292     Sema &S;
18293     SourceLocation Loc;
18294 
18295   public:
18296     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18297 
18298     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18299 
18300     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18301   };
18302 }
18303 
18304 bool MarkReferencedDecls::TraverseTemplateArgument(
18305     const TemplateArgument &Arg) {
18306   {
18307     // A non-type template argument is a constant-evaluated context.
18308     EnterExpressionEvaluationContext Evaluated(
18309         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18310     if (Arg.getKind() == TemplateArgument::Declaration) {
18311       if (Decl *D = Arg.getAsDecl())
18312         S.MarkAnyDeclReferenced(Loc, D, true);
18313     } else if (Arg.getKind() == TemplateArgument::Expression) {
18314       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18315     }
18316   }
18317 
18318   return Inherited::TraverseTemplateArgument(Arg);
18319 }
18320 
18321 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18322   MarkReferencedDecls Marker(*this, Loc);
18323   Marker.TraverseType(T);
18324 }
18325 
18326 namespace {
18327 /// Helper class that marks all of the declarations referenced by
18328 /// potentially-evaluated subexpressions as "referenced".
18329 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18330 public:
18331   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18332   bool SkipLocalVariables;
18333 
18334   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18335       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18336 
18337   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18338     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18339   }
18340 
18341   void VisitDeclRefExpr(DeclRefExpr *E) {
18342     // If we were asked not to visit local variables, don't.
18343     if (SkipLocalVariables) {
18344       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18345         if (VD->hasLocalStorage())
18346           return;
18347     }
18348     S.MarkDeclRefReferenced(E);
18349   }
18350 
18351   void VisitMemberExpr(MemberExpr *E) {
18352     S.MarkMemberReferenced(E);
18353     Visit(E->getBase());
18354   }
18355 };
18356 } // namespace
18357 
18358 /// Mark any declarations that appear within this expression or any
18359 /// potentially-evaluated subexpressions as "referenced".
18360 ///
18361 /// \param SkipLocalVariables If true, don't mark local variables as
18362 /// 'referenced'.
18363 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18364                                             bool SkipLocalVariables) {
18365   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18366 }
18367 
18368 /// Emit a diagnostic that describes an effect on the run-time behavior
18369 /// of the program being compiled.
18370 ///
18371 /// This routine emits the given diagnostic when the code currently being
18372 /// type-checked is "potentially evaluated", meaning that there is a
18373 /// possibility that the code will actually be executable. Code in sizeof()
18374 /// expressions, code used only during overload resolution, etc., are not
18375 /// potentially evaluated. This routine will suppress such diagnostics or,
18376 /// in the absolutely nutty case of potentially potentially evaluated
18377 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18378 /// later.
18379 ///
18380 /// This routine should be used for all diagnostics that describe the run-time
18381 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18382 /// Failure to do so will likely result in spurious diagnostics or failures
18383 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18384 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18385                                const PartialDiagnostic &PD) {
18386   switch (ExprEvalContexts.back().Context) {
18387   case ExpressionEvaluationContext::Unevaluated:
18388   case ExpressionEvaluationContext::UnevaluatedList:
18389   case ExpressionEvaluationContext::UnevaluatedAbstract:
18390   case ExpressionEvaluationContext::DiscardedStatement:
18391     // The argument will never be evaluated, so don't complain.
18392     break;
18393 
18394   case ExpressionEvaluationContext::ConstantEvaluated:
18395     // Relevant diagnostics should be produced by constant evaluation.
18396     break;
18397 
18398   case ExpressionEvaluationContext::PotentiallyEvaluated:
18399   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18400     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18401       FunctionScopes.back()->PossiblyUnreachableDiags.
18402         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18403       return true;
18404     }
18405 
18406     // The initializer of a constexpr variable or of the first declaration of a
18407     // static data member is not syntactically a constant evaluated constant,
18408     // but nonetheless is always required to be a constant expression, so we
18409     // can skip diagnosing.
18410     // FIXME: Using the mangling context here is a hack.
18411     if (auto *VD = dyn_cast_or_null<VarDecl>(
18412             ExprEvalContexts.back().ManglingContextDecl)) {
18413       if (VD->isConstexpr() ||
18414           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18415         break;
18416       // FIXME: For any other kind of variable, we should build a CFG for its
18417       // initializer and check whether the context in question is reachable.
18418     }
18419 
18420     Diag(Loc, PD);
18421     return true;
18422   }
18423 
18424   return false;
18425 }
18426 
18427 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18428                                const PartialDiagnostic &PD) {
18429   return DiagRuntimeBehavior(
18430       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18431 }
18432 
18433 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18434                                CallExpr *CE, FunctionDecl *FD) {
18435   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18436     return false;
18437 
18438   // If we're inside a decltype's expression, don't check for a valid return
18439   // type or construct temporaries until we know whether this is the last call.
18440   if (ExprEvalContexts.back().ExprContext ==
18441       ExpressionEvaluationContextRecord::EK_Decltype) {
18442     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18443     return false;
18444   }
18445 
18446   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18447     FunctionDecl *FD;
18448     CallExpr *CE;
18449 
18450   public:
18451     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18452       : FD(FD), CE(CE) { }
18453 
18454     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18455       if (!FD) {
18456         S.Diag(Loc, diag::err_call_incomplete_return)
18457           << T << CE->getSourceRange();
18458         return;
18459       }
18460 
18461       S.Diag(Loc, diag::err_call_function_incomplete_return)
18462           << CE->getSourceRange() << FD << T;
18463       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18464           << FD->getDeclName();
18465     }
18466   } Diagnoser(FD, CE);
18467 
18468   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18469     return true;
18470 
18471   return false;
18472 }
18473 
18474 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18475 // will prevent this condition from triggering, which is what we want.
18476 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18477   SourceLocation Loc;
18478 
18479   unsigned diagnostic = diag::warn_condition_is_assignment;
18480   bool IsOrAssign = false;
18481 
18482   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18483     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18484       return;
18485 
18486     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18487 
18488     // Greylist some idioms by putting them into a warning subcategory.
18489     if (ObjCMessageExpr *ME
18490           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18491       Selector Sel = ME->getSelector();
18492 
18493       // self = [<foo> init...]
18494       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18495         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18496 
18497       // <foo> = [<bar> nextObject]
18498       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18499         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18500     }
18501 
18502     Loc = Op->getOperatorLoc();
18503   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18504     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18505       return;
18506 
18507     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18508     Loc = Op->getOperatorLoc();
18509   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18510     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18511   else {
18512     // Not an assignment.
18513     return;
18514   }
18515 
18516   Diag(Loc, diagnostic) << E->getSourceRange();
18517 
18518   SourceLocation Open = E->getBeginLoc();
18519   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18520   Diag(Loc, diag::note_condition_assign_silence)
18521         << FixItHint::CreateInsertion(Open, "(")
18522         << FixItHint::CreateInsertion(Close, ")");
18523 
18524   if (IsOrAssign)
18525     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18526       << FixItHint::CreateReplacement(Loc, "!=");
18527   else
18528     Diag(Loc, diag::note_condition_assign_to_comparison)
18529       << FixItHint::CreateReplacement(Loc, "==");
18530 }
18531 
18532 /// Redundant parentheses over an equality comparison can indicate
18533 /// that the user intended an assignment used as condition.
18534 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18535   // Don't warn if the parens came from a macro.
18536   SourceLocation parenLoc = ParenE->getBeginLoc();
18537   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18538     return;
18539   // Don't warn for dependent expressions.
18540   if (ParenE->isTypeDependent())
18541     return;
18542 
18543   Expr *E = ParenE->IgnoreParens();
18544 
18545   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18546     if (opE->getOpcode() == BO_EQ &&
18547         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18548                                                            == Expr::MLV_Valid) {
18549       SourceLocation Loc = opE->getOperatorLoc();
18550 
18551       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18552       SourceRange ParenERange = ParenE->getSourceRange();
18553       Diag(Loc, diag::note_equality_comparison_silence)
18554         << FixItHint::CreateRemoval(ParenERange.getBegin())
18555         << FixItHint::CreateRemoval(ParenERange.getEnd());
18556       Diag(Loc, diag::note_equality_comparison_to_assign)
18557         << FixItHint::CreateReplacement(Loc, "=");
18558     }
18559 }
18560 
18561 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18562                                        bool IsConstexpr) {
18563   DiagnoseAssignmentAsCondition(E);
18564   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18565     DiagnoseEqualityWithExtraParens(parenE);
18566 
18567   ExprResult result = CheckPlaceholderExpr(E);
18568   if (result.isInvalid()) return ExprError();
18569   E = result.get();
18570 
18571   if (!E->isTypeDependent()) {
18572     if (getLangOpts().CPlusPlus)
18573       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18574 
18575     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18576     if (ERes.isInvalid())
18577       return ExprError();
18578     E = ERes.get();
18579 
18580     QualType T = E->getType();
18581     if (!T->isScalarType()) { // C99 6.8.4.1p1
18582       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18583         << T << E->getSourceRange();
18584       return ExprError();
18585     }
18586     CheckBoolLikeConversion(E, Loc);
18587   }
18588 
18589   return E;
18590 }
18591 
18592 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18593                                            Expr *SubExpr, ConditionKind CK) {
18594   // Empty conditions are valid in for-statements.
18595   if (!SubExpr)
18596     return ConditionResult();
18597 
18598   ExprResult Cond;
18599   switch (CK) {
18600   case ConditionKind::Boolean:
18601     Cond = CheckBooleanCondition(Loc, SubExpr);
18602     break;
18603 
18604   case ConditionKind::ConstexprIf:
18605     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18606     break;
18607 
18608   case ConditionKind::Switch:
18609     Cond = CheckSwitchCondition(Loc, SubExpr);
18610     break;
18611   }
18612   if (Cond.isInvalid()) {
18613     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
18614                               {SubExpr});
18615     if (!Cond.get())
18616       return ConditionError();
18617   }
18618   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18619   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18620   if (!FullExpr.get())
18621     return ConditionError();
18622 
18623   return ConditionResult(*this, nullptr, FullExpr,
18624                          CK == ConditionKind::ConstexprIf);
18625 }
18626 
18627 namespace {
18628   /// A visitor for rebuilding a call to an __unknown_any expression
18629   /// to have an appropriate type.
18630   struct RebuildUnknownAnyFunction
18631     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18632 
18633     Sema &S;
18634 
18635     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18636 
18637     ExprResult VisitStmt(Stmt *S) {
18638       llvm_unreachable("unexpected statement!");
18639     }
18640 
18641     ExprResult VisitExpr(Expr *E) {
18642       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18643         << E->getSourceRange();
18644       return ExprError();
18645     }
18646 
18647     /// Rebuild an expression which simply semantically wraps another
18648     /// expression which it shares the type and value kind of.
18649     template <class T> ExprResult rebuildSugarExpr(T *E) {
18650       ExprResult SubResult = Visit(E->getSubExpr());
18651       if (SubResult.isInvalid()) return ExprError();
18652 
18653       Expr *SubExpr = SubResult.get();
18654       E->setSubExpr(SubExpr);
18655       E->setType(SubExpr->getType());
18656       E->setValueKind(SubExpr->getValueKind());
18657       assert(E->getObjectKind() == OK_Ordinary);
18658       return E;
18659     }
18660 
18661     ExprResult VisitParenExpr(ParenExpr *E) {
18662       return rebuildSugarExpr(E);
18663     }
18664 
18665     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18666       return rebuildSugarExpr(E);
18667     }
18668 
18669     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18670       ExprResult SubResult = Visit(E->getSubExpr());
18671       if (SubResult.isInvalid()) return ExprError();
18672 
18673       Expr *SubExpr = SubResult.get();
18674       E->setSubExpr(SubExpr);
18675       E->setType(S.Context.getPointerType(SubExpr->getType()));
18676       assert(E->getValueKind() == VK_RValue);
18677       assert(E->getObjectKind() == OK_Ordinary);
18678       return E;
18679     }
18680 
18681     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18682       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18683 
18684       E->setType(VD->getType());
18685 
18686       assert(E->getValueKind() == VK_RValue);
18687       if (S.getLangOpts().CPlusPlus &&
18688           !(isa<CXXMethodDecl>(VD) &&
18689             cast<CXXMethodDecl>(VD)->isInstance()))
18690         E->setValueKind(VK_LValue);
18691 
18692       return E;
18693     }
18694 
18695     ExprResult VisitMemberExpr(MemberExpr *E) {
18696       return resolveDecl(E, E->getMemberDecl());
18697     }
18698 
18699     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18700       return resolveDecl(E, E->getDecl());
18701     }
18702   };
18703 }
18704 
18705 /// Given a function expression of unknown-any type, try to rebuild it
18706 /// to have a function type.
18707 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18708   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18709   if (Result.isInvalid()) return ExprError();
18710   return S.DefaultFunctionArrayConversion(Result.get());
18711 }
18712 
18713 namespace {
18714   /// A visitor for rebuilding an expression of type __unknown_anytype
18715   /// into one which resolves the type directly on the referring
18716   /// expression.  Strict preservation of the original source
18717   /// structure is not a goal.
18718   struct RebuildUnknownAnyExpr
18719     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18720 
18721     Sema &S;
18722 
18723     /// The current destination type.
18724     QualType DestType;
18725 
18726     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18727       : S(S), DestType(CastType) {}
18728 
18729     ExprResult VisitStmt(Stmt *S) {
18730       llvm_unreachable("unexpected statement!");
18731     }
18732 
18733     ExprResult VisitExpr(Expr *E) {
18734       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18735         << E->getSourceRange();
18736       return ExprError();
18737     }
18738 
18739     ExprResult VisitCallExpr(CallExpr *E);
18740     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18741 
18742     /// Rebuild an expression which simply semantically wraps another
18743     /// expression which it shares the type and value kind of.
18744     template <class T> ExprResult rebuildSugarExpr(T *E) {
18745       ExprResult SubResult = Visit(E->getSubExpr());
18746       if (SubResult.isInvalid()) return ExprError();
18747       Expr *SubExpr = SubResult.get();
18748       E->setSubExpr(SubExpr);
18749       E->setType(SubExpr->getType());
18750       E->setValueKind(SubExpr->getValueKind());
18751       assert(E->getObjectKind() == OK_Ordinary);
18752       return E;
18753     }
18754 
18755     ExprResult VisitParenExpr(ParenExpr *E) {
18756       return rebuildSugarExpr(E);
18757     }
18758 
18759     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18760       return rebuildSugarExpr(E);
18761     }
18762 
18763     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18764       const PointerType *Ptr = DestType->getAs<PointerType>();
18765       if (!Ptr) {
18766         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18767           << E->getSourceRange();
18768         return ExprError();
18769       }
18770 
18771       if (isa<CallExpr>(E->getSubExpr())) {
18772         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18773           << E->getSourceRange();
18774         return ExprError();
18775       }
18776 
18777       assert(E->getValueKind() == VK_RValue);
18778       assert(E->getObjectKind() == OK_Ordinary);
18779       E->setType(DestType);
18780 
18781       // Build the sub-expression as if it were an object of the pointee type.
18782       DestType = Ptr->getPointeeType();
18783       ExprResult SubResult = Visit(E->getSubExpr());
18784       if (SubResult.isInvalid()) return ExprError();
18785       E->setSubExpr(SubResult.get());
18786       return E;
18787     }
18788 
18789     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18790 
18791     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18792 
18793     ExprResult VisitMemberExpr(MemberExpr *E) {
18794       return resolveDecl(E, E->getMemberDecl());
18795     }
18796 
18797     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18798       return resolveDecl(E, E->getDecl());
18799     }
18800   };
18801 }
18802 
18803 /// Rebuilds a call expression which yielded __unknown_anytype.
18804 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18805   Expr *CalleeExpr = E->getCallee();
18806 
18807   enum FnKind {
18808     FK_MemberFunction,
18809     FK_FunctionPointer,
18810     FK_BlockPointer
18811   };
18812 
18813   FnKind Kind;
18814   QualType CalleeType = CalleeExpr->getType();
18815   if (CalleeType == S.Context.BoundMemberTy) {
18816     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18817     Kind = FK_MemberFunction;
18818     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18819   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18820     CalleeType = Ptr->getPointeeType();
18821     Kind = FK_FunctionPointer;
18822   } else {
18823     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18824     Kind = FK_BlockPointer;
18825   }
18826   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18827 
18828   // Verify that this is a legal result type of a function.
18829   if (DestType->isArrayType() || DestType->isFunctionType()) {
18830     unsigned diagID = diag::err_func_returning_array_function;
18831     if (Kind == FK_BlockPointer)
18832       diagID = diag::err_block_returning_array_function;
18833 
18834     S.Diag(E->getExprLoc(), diagID)
18835       << DestType->isFunctionType() << DestType;
18836     return ExprError();
18837   }
18838 
18839   // Otherwise, go ahead and set DestType as the call's result.
18840   E->setType(DestType.getNonLValueExprType(S.Context));
18841   E->setValueKind(Expr::getValueKindForType(DestType));
18842   assert(E->getObjectKind() == OK_Ordinary);
18843 
18844   // Rebuild the function type, replacing the result type with DestType.
18845   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18846   if (Proto) {
18847     // __unknown_anytype(...) is a special case used by the debugger when
18848     // it has no idea what a function's signature is.
18849     //
18850     // We want to build this call essentially under the K&R
18851     // unprototyped rules, but making a FunctionNoProtoType in C++
18852     // would foul up all sorts of assumptions.  However, we cannot
18853     // simply pass all arguments as variadic arguments, nor can we
18854     // portably just call the function under a non-variadic type; see
18855     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18856     // However, it turns out that in practice it is generally safe to
18857     // call a function declared as "A foo(B,C,D);" under the prototype
18858     // "A foo(B,C,D,...);".  The only known exception is with the
18859     // Windows ABI, where any variadic function is implicitly cdecl
18860     // regardless of its normal CC.  Therefore we change the parameter
18861     // types to match the types of the arguments.
18862     //
18863     // This is a hack, but it is far superior to moving the
18864     // corresponding target-specific code from IR-gen to Sema/AST.
18865 
18866     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18867     SmallVector<QualType, 8> ArgTypes;
18868     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18869       ArgTypes.reserve(E->getNumArgs());
18870       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18871         Expr *Arg = E->getArg(i);
18872         QualType ArgType = Arg->getType();
18873         if (E->isLValue()) {
18874           ArgType = S.Context.getLValueReferenceType(ArgType);
18875         } else if (E->isXValue()) {
18876           ArgType = S.Context.getRValueReferenceType(ArgType);
18877         }
18878         ArgTypes.push_back(ArgType);
18879       }
18880       ParamTypes = ArgTypes;
18881     }
18882     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18883                                          Proto->getExtProtoInfo());
18884   } else {
18885     DestType = S.Context.getFunctionNoProtoType(DestType,
18886                                                 FnType->getExtInfo());
18887   }
18888 
18889   // Rebuild the appropriate pointer-to-function type.
18890   switch (Kind) {
18891   case FK_MemberFunction:
18892     // Nothing to do.
18893     break;
18894 
18895   case FK_FunctionPointer:
18896     DestType = S.Context.getPointerType(DestType);
18897     break;
18898 
18899   case FK_BlockPointer:
18900     DestType = S.Context.getBlockPointerType(DestType);
18901     break;
18902   }
18903 
18904   // Finally, we can recurse.
18905   ExprResult CalleeResult = Visit(CalleeExpr);
18906   if (!CalleeResult.isUsable()) return ExprError();
18907   E->setCallee(CalleeResult.get());
18908 
18909   // Bind a temporary if necessary.
18910   return S.MaybeBindToTemporary(E);
18911 }
18912 
18913 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18914   // Verify that this is a legal result type of a call.
18915   if (DestType->isArrayType() || DestType->isFunctionType()) {
18916     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18917       << DestType->isFunctionType() << DestType;
18918     return ExprError();
18919   }
18920 
18921   // Rewrite the method result type if available.
18922   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18923     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18924     Method->setReturnType(DestType);
18925   }
18926 
18927   // Change the type of the message.
18928   E->setType(DestType.getNonReferenceType());
18929   E->setValueKind(Expr::getValueKindForType(DestType));
18930 
18931   return S.MaybeBindToTemporary(E);
18932 }
18933 
18934 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18935   // The only case we should ever see here is a function-to-pointer decay.
18936   if (E->getCastKind() == CK_FunctionToPointerDecay) {
18937     assert(E->getValueKind() == VK_RValue);
18938     assert(E->getObjectKind() == OK_Ordinary);
18939 
18940     E->setType(DestType);
18941 
18942     // Rebuild the sub-expression as the pointee (function) type.
18943     DestType = DestType->castAs<PointerType>()->getPointeeType();
18944 
18945     ExprResult Result = Visit(E->getSubExpr());
18946     if (!Result.isUsable()) return ExprError();
18947 
18948     E->setSubExpr(Result.get());
18949     return E;
18950   } else if (E->getCastKind() == CK_LValueToRValue) {
18951     assert(E->getValueKind() == VK_RValue);
18952     assert(E->getObjectKind() == OK_Ordinary);
18953 
18954     assert(isa<BlockPointerType>(E->getType()));
18955 
18956     E->setType(DestType);
18957 
18958     // The sub-expression has to be a lvalue reference, so rebuild it as such.
18959     DestType = S.Context.getLValueReferenceType(DestType);
18960 
18961     ExprResult Result = Visit(E->getSubExpr());
18962     if (!Result.isUsable()) return ExprError();
18963 
18964     E->setSubExpr(Result.get());
18965     return E;
18966   } else {
18967     llvm_unreachable("Unhandled cast type!");
18968   }
18969 }
18970 
18971 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18972   ExprValueKind ValueKind = VK_LValue;
18973   QualType Type = DestType;
18974 
18975   // We know how to make this work for certain kinds of decls:
18976 
18977   //  - functions
18978   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18979     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18980       DestType = Ptr->getPointeeType();
18981       ExprResult Result = resolveDecl(E, VD);
18982       if (Result.isInvalid()) return ExprError();
18983       return S.ImpCastExprToType(Result.get(), Type,
18984                                  CK_FunctionToPointerDecay, VK_RValue);
18985     }
18986 
18987     if (!Type->isFunctionType()) {
18988       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18989         << VD << E->getSourceRange();
18990       return ExprError();
18991     }
18992     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18993       // We must match the FunctionDecl's type to the hack introduced in
18994       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18995       // type. See the lengthy commentary in that routine.
18996       QualType FDT = FD->getType();
18997       const FunctionType *FnType = FDT->castAs<FunctionType>();
18998       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18999       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19000       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19001         SourceLocation Loc = FD->getLocation();
19002         FunctionDecl *NewFD = FunctionDecl::Create(
19003             S.Context, FD->getDeclContext(), Loc, Loc,
19004             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19005             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
19006             /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
19007 
19008         if (FD->getQualifier())
19009           NewFD->setQualifierInfo(FD->getQualifierLoc());
19010 
19011         SmallVector<ParmVarDecl*, 16> Params;
19012         for (const auto &AI : FT->param_types()) {
19013           ParmVarDecl *Param =
19014             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19015           Param->setScopeInfo(0, Params.size());
19016           Params.push_back(Param);
19017         }
19018         NewFD->setParams(Params);
19019         DRE->setDecl(NewFD);
19020         VD = DRE->getDecl();
19021       }
19022     }
19023 
19024     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19025       if (MD->isInstance()) {
19026         ValueKind = VK_RValue;
19027         Type = S.Context.BoundMemberTy;
19028       }
19029 
19030     // Function references aren't l-values in C.
19031     if (!S.getLangOpts().CPlusPlus)
19032       ValueKind = VK_RValue;
19033 
19034   //  - variables
19035   } else if (isa<VarDecl>(VD)) {
19036     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19037       Type = RefTy->getPointeeType();
19038     } else if (Type->isFunctionType()) {
19039       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19040         << VD << E->getSourceRange();
19041       return ExprError();
19042     }
19043 
19044   //  - nothing else
19045   } else {
19046     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19047       << VD << E->getSourceRange();
19048     return ExprError();
19049   }
19050 
19051   // Modifying the declaration like this is friendly to IR-gen but
19052   // also really dangerous.
19053   VD->setType(DestType);
19054   E->setType(Type);
19055   E->setValueKind(ValueKind);
19056   return E;
19057 }
19058 
19059 /// Check a cast of an unknown-any type.  We intentionally only
19060 /// trigger this for C-style casts.
19061 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19062                                      Expr *CastExpr, CastKind &CastKind,
19063                                      ExprValueKind &VK, CXXCastPath &Path) {
19064   // The type we're casting to must be either void or complete.
19065   if (!CastType->isVoidType() &&
19066       RequireCompleteType(TypeRange.getBegin(), CastType,
19067                           diag::err_typecheck_cast_to_incomplete))
19068     return ExprError();
19069 
19070   // Rewrite the casted expression from scratch.
19071   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19072   if (!result.isUsable()) return ExprError();
19073 
19074   CastExpr = result.get();
19075   VK = CastExpr->getValueKind();
19076   CastKind = CK_NoOp;
19077 
19078   return CastExpr;
19079 }
19080 
19081 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19082   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19083 }
19084 
19085 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19086                                     Expr *arg, QualType &paramType) {
19087   // If the syntactic form of the argument is not an explicit cast of
19088   // any sort, just do default argument promotion.
19089   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19090   if (!castArg) {
19091     ExprResult result = DefaultArgumentPromotion(arg);
19092     if (result.isInvalid()) return ExprError();
19093     paramType = result.get()->getType();
19094     return result;
19095   }
19096 
19097   // Otherwise, use the type that was written in the explicit cast.
19098   assert(!arg->hasPlaceholderType());
19099   paramType = castArg->getTypeAsWritten();
19100 
19101   // Copy-initialize a parameter of that type.
19102   InitializedEntity entity =
19103     InitializedEntity::InitializeParameter(Context, paramType,
19104                                            /*consumed*/ false);
19105   return PerformCopyInitialization(entity, callLoc, arg);
19106 }
19107 
19108 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19109   Expr *orig = E;
19110   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19111   while (true) {
19112     E = E->IgnoreParenImpCasts();
19113     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19114       E = call->getCallee();
19115       diagID = diag::err_uncasted_call_of_unknown_any;
19116     } else {
19117       break;
19118     }
19119   }
19120 
19121   SourceLocation loc;
19122   NamedDecl *d;
19123   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19124     loc = ref->getLocation();
19125     d = ref->getDecl();
19126   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19127     loc = mem->getMemberLoc();
19128     d = mem->getMemberDecl();
19129   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19130     diagID = diag::err_uncasted_call_of_unknown_any;
19131     loc = msg->getSelectorStartLoc();
19132     d = msg->getMethodDecl();
19133     if (!d) {
19134       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19135         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19136         << orig->getSourceRange();
19137       return ExprError();
19138     }
19139   } else {
19140     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19141       << E->getSourceRange();
19142     return ExprError();
19143   }
19144 
19145   S.Diag(loc, diagID) << d << orig->getSourceRange();
19146 
19147   // Never recoverable.
19148   return ExprError();
19149 }
19150 
19151 /// Check for operands with placeholder types and complain if found.
19152 /// Returns ExprError() if there was an error and no recovery was possible.
19153 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19154   if (!Context.isDependenceAllowed()) {
19155     // C cannot handle TypoExpr nodes on either side of a binop because it
19156     // doesn't handle dependent types properly, so make sure any TypoExprs have
19157     // been dealt with before checking the operands.
19158     ExprResult Result = CorrectDelayedTyposInExpr(E);
19159     if (!Result.isUsable()) return ExprError();
19160     E = Result.get();
19161   }
19162 
19163   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19164   if (!placeholderType) return E;
19165 
19166   switch (placeholderType->getKind()) {
19167 
19168   // Overloaded expressions.
19169   case BuiltinType::Overload: {
19170     // Try to resolve a single function template specialization.
19171     // This is obligatory.
19172     ExprResult Result = E;
19173     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19174       return Result;
19175 
19176     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19177     // leaves Result unchanged on failure.
19178     Result = E;
19179     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19180       return Result;
19181 
19182     // If that failed, try to recover with a call.
19183     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19184                          /*complain*/ true);
19185     return Result;
19186   }
19187 
19188   // Bound member functions.
19189   case BuiltinType::BoundMember: {
19190     ExprResult result = E;
19191     const Expr *BME = E->IgnoreParens();
19192     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19193     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19194     if (isa<CXXPseudoDestructorExpr>(BME)) {
19195       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19196     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19197       if (ME->getMemberNameInfo().getName().getNameKind() ==
19198           DeclarationName::CXXDestructorName)
19199         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19200     }
19201     tryToRecoverWithCall(result, PD,
19202                          /*complain*/ true);
19203     return result;
19204   }
19205 
19206   // ARC unbridged casts.
19207   case BuiltinType::ARCUnbridgedCast: {
19208     Expr *realCast = stripARCUnbridgedCast(E);
19209     diagnoseARCUnbridgedCast(realCast);
19210     return realCast;
19211   }
19212 
19213   // Expressions of unknown type.
19214   case BuiltinType::UnknownAny:
19215     return diagnoseUnknownAnyExpr(*this, E);
19216 
19217   // Pseudo-objects.
19218   case BuiltinType::PseudoObject:
19219     return checkPseudoObjectRValue(E);
19220 
19221   case BuiltinType::BuiltinFn: {
19222     // Accept __noop without parens by implicitly converting it to a call expr.
19223     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19224     if (DRE) {
19225       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19226       if (FD->getBuiltinID() == Builtin::BI__noop) {
19227         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19228                               CK_BuiltinFnToFnPtr)
19229                 .get();
19230         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19231                                 VK_RValue, SourceLocation(),
19232                                 FPOptionsOverride());
19233       }
19234     }
19235 
19236     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19237     return ExprError();
19238   }
19239 
19240   case BuiltinType::IncompleteMatrixIdx:
19241     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19242              ->getRowIdx()
19243              ->getBeginLoc(),
19244          diag::err_matrix_incomplete_index);
19245     return ExprError();
19246 
19247   // Expressions of unknown type.
19248   case BuiltinType::OMPArraySection:
19249     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19250     return ExprError();
19251 
19252   // Expressions of unknown type.
19253   case BuiltinType::OMPArrayShaping:
19254     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19255 
19256   case BuiltinType::OMPIterator:
19257     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19258 
19259   // Everything else should be impossible.
19260 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19261   case BuiltinType::Id:
19262 #include "clang/Basic/OpenCLImageTypes.def"
19263 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19264   case BuiltinType::Id:
19265 #include "clang/Basic/OpenCLExtensionTypes.def"
19266 #define SVE_TYPE(Name, Id, SingletonId) \
19267   case BuiltinType::Id:
19268 #include "clang/Basic/AArch64SVEACLETypes.def"
19269 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \
19270   case BuiltinType::Id:
19271 #include "clang/Basic/PPCTypes.def"
19272 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19273 #define PLACEHOLDER_TYPE(Id, SingletonId)
19274 #include "clang/AST/BuiltinTypes.def"
19275     break;
19276   }
19277 
19278   llvm_unreachable("invalid placeholder type!");
19279 }
19280 
19281 bool Sema::CheckCaseExpression(Expr *E) {
19282   if (E->isTypeDependent())
19283     return true;
19284   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19285     return E->getType()->isIntegralOrEnumerationType();
19286   return false;
19287 }
19288 
19289 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19290 ExprResult
19291 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19292   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19293          "Unknown Objective-C Boolean value!");
19294   QualType BoolT = Context.ObjCBuiltinBoolTy;
19295   if (!Context.getBOOLDecl()) {
19296     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19297                         Sema::LookupOrdinaryName);
19298     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19299       NamedDecl *ND = Result.getFoundDecl();
19300       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19301         Context.setBOOLDecl(TD);
19302     }
19303   }
19304   if (Context.getBOOLDecl())
19305     BoolT = Context.getBOOLType();
19306   return new (Context)
19307       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19308 }
19309 
19310 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19311     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19312     SourceLocation RParen) {
19313 
19314   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19315 
19316   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19317     return Spec.getPlatform() == Platform;
19318   });
19319 
19320   VersionTuple Version;
19321   if (Spec != AvailSpecs.end())
19322     Version = Spec->getVersion();
19323 
19324   // The use of `@available` in the enclosing function should be analyzed to
19325   // warn when it's used inappropriately (i.e. not if(@available)).
19326   if (getCurFunctionOrMethodDecl())
19327     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19328   else if (getCurBlock() || getCurLambda())
19329     getCurFunction()->HasPotentialAvailabilityViolations = true;
19330 
19331   return new (Context)
19332       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19333 }
19334 
19335 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19336                                     ArrayRef<Expr *> SubExprs, QualType T) {
19337   if (!Context.getLangOpts().RecoveryAST)
19338     return ExprError();
19339 
19340   if (isSFINAEContext())
19341     return ExprError();
19342 
19343   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19344     // We don't know the concrete type, fallback to dependent type.
19345     T = Context.DependentTy;
19346   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19347 }
19348